Advertisement
Guest User

Untitled

a guest
Nov 30th, 2017
461
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.92 KB | None | 0 0
  1.  
  2. #include <ESP8266WiFi.h>
  3. #include <WiFiClient.h>
  4. #include <ESP8266WebServer.h>
  5. #include <ESP8266mDNS.h>
  6. #include <FS.h>
  7. #include <EEPROM.h>
  8. #include "memoryAccess.h"
  9.  
  10. #include "style.h"     // custom stylesheet, get it from stylesheet
  11. #include "script.h"
  12. #include "index.h"     // Index page html, get it from MAIN_page
  13. #include "settings.h"  // Settings page html, get it from SETTINGS_page
  14.  
  15. // User variables
  16. const String MemoryAccessVersion = "cp-a2";
  17. const String deviceType = "clapSensor";           // This is what kind of device it is, crucial for the homeServer when determing which API to use
  18. const int wifiConnectionTimeout = 5;              // n*1 sec
  19. char ssid[30];
  20. char password[30];
  21. char APssid[30];
  22. String deviceName;
  23. String deviceLocation;
  24. String deviceId;
  25.  
  26. memoryAccess MemoryAccess;
  27.  
  28. const int lampPin = 14;   // Pin the appliance is connected to
  29. const int sensorPin = 5;  // Pin the sensor is connected to
  30.  
  31. bool lampOn;        // Is the appliance turned on?
  32. bool sensorActive;  // Should we care about sensor input?
  33. bool buttonState;   // Used to make button not flash indefinetly
  34.  
  35. const int bufferSize = 19;  // This will be 20 samples, counting with zero
  36. long sampleRate = 100;
  37. long lastSampleTime = 0;
  38. int soundBuffer[bufferSize + 1];  // with a sampleRate of 100, this is 2 seconds worth of sound
  39. int sensorvalue = 0;
  40. int samplePeak = 0;
  41. int nClaps = 0;
  42. int sensorthreshold = 650;
  43.  
  44. long timeOfLastClap = 0;
  45. long minTimeBetweenClaps = 4000;
  46. long maxTimeBetweenClaps = 8000;
  47.  
  48. ESP8266WebServer server ( 80 );  // webServer on port 80
  49.  
  50. void setup ( void ) {
  51.     // Activate serial
  52.     Serial.begin ( 115200 );
  53.     //Serial.setDebugOutput(true);
  54.     SPIFFS.begin();
  55.     MemoryAccess.init();
  56.  
  57.     if (MemoryAccess.readAscii("version") == MemoryAccessVersion) {
  58.         deviceName = MemoryAccess.readAscii("deviceName");
  59.         deviceLocation = MemoryAccess.readAscii("deviceLocation");
  60.         deviceId = MemoryAccess.readAscii("deviceId");
  61.         MemoryAccess.readAscii("SSID").toCharArray(ssid, 30);
  62.         MemoryAccess.readAscii("Password").toCharArray(password, 30);
  63.         (deviceType + "-" + deviceId).toCharArray(APssid, 30);
  64.     } else {
  65.         // SET TO DEFAULT VALUES
  66.         String _uniqId = uniqId();
  67.         MemoryAccess.writeAscii("version", MemoryAccessVersion);
  68.         MemoryAccess.writeAscii("deviceName", "clapSensor" + _uniqId);
  69.         MemoryAccess.writeAscii("deviceLocation", "Milky way");
  70.         MemoryAccess.writeAscii("deviceId", _uniqId);
  71.         MemoryAccess.writeAscii("SSID", ".");
  72.         MemoryAccess.writeAscii("Password", "");
  73.         MemoryAccess.commit();
  74.         Serial.println("Have set default values.");
  75.         hardReset();
  76.     }
  77.  
  78.     Serial.print("ssid: ");
  79.     Serial.println(ssid);
  80.     Serial.print("Password: ");
  81.     Serial.println(password);
  82.     Serial.print("deviceName: ");
  83.     Serial.println(deviceName);
  84.     Serial.print("deviceLocation: ");
  85.     Serial.println(deviceLocation);
  86.     Serial.print("deviceId: ");
  87.     Serial.println(deviceId);
  88.  
  89.  
  90.     // Setup pins and set default values
  91.     pinMode ( lampPin, OUTPUT );
  92.     //pinMode ( sensorPin, INPUT );
  93.     lampOn = false; // Vil at denne skal bli husket, altså være samme etter boot
  94.     sensorActive = true;
  95.     digitalWrite(lampPin, lampOn);
  96.  
  97.     // Try to connect to WiFi
  98.     WiFi.begin ( ssid, password );
  99.  
  100.     // Wait for connection
  101.     int connTime = 0;
  102.     while ( WiFi.status() != WL_CONNECTED ) {
  103.         if (connTime >= wifiConnectionTimeout) { break; }
  104.         delay ( 1000 );
  105.         Serial.print ( "." );
  106.         connTime++;
  107.     }
  108.  
  109.     Serial.println ( "" );
  110.  
  111.     if ( WiFi.status() == WL_CONNECTED ) {
  112.         Serial.print ( "Connected to " );
  113.         Serial.println ( ssid );
  114.         Serial.print ( "IP address: " );
  115.         Serial.println ( WiFi.localIP() );
  116.     } else {
  117.         WiFi.disconnect();
  118.         //WiFi.softAP(APssid);  // add password here as second parameter, currently just a open hotspot
  119.         IPAddress myIP = WiFi.softAPIP();
  120.         Serial.print("APssid: ");
  121.         Serial.println(APssid);
  122.         Serial.print("AP IP address: ");
  123.         Serial.println(myIP);
  124.     }
  125.  
  126.     if ( MDNS.begin ( "esp8266" ) ) {
  127.         Serial.println ( "MDNS responder started" );
  128.     }
  129.  
  130.     // Gui
  131.     server.on ( "/", handleRoot );
  132.     server.on ( "/settings", handleSettings );
  133.     // Json
  134.     server.on ( "/j/", handleJson );
  135.     server.on ( "/j", handleJson );
  136.     // Others
  137.     server.on ( "/style.css", handleStylesheet );
  138.     server.on ( "/script.js", handleScript );
  139.     server.serveStatic("/bootstrap.css", SPIFFS, "/bootstrap.css");
  140.     server.onNotFound ( handleNotFound );
  141.     server.begin();
  142.     Serial.println ( "HTTP server started" );
  143. }
  144.  
  145. void loop ( void ) {
  146.     server.handleClient();
  147.  
  148.     unsigned long currentMillis = millis();
  149.     sensorvalue = analogRead(A0);
  150.     yield();
  151.  
  152.     if (sensorvalue >= sensorthreshold) {
  153.         if (currentMillis > lastSampleTime + minTimeBetweenClaps) {
  154.             lampOn = !lampOn;
  155.             digitalWrite(lampPin, lampOn);
  156.  
  157.             lastSampleTime = currentMillis;
  158.             yield();
  159.         }
  160.     }
  161.  
  162.     /*  This is what i really want to put in this loop
  163.     if (currentMillis < lastSampleTime + sampleRate) {
  164.         sampleSensor();
  165.     } else {
  166.         processSample();
  167.     } */
  168. }
  169.  
  170. void sampleSensor() {
  171.     // Check if we are ready to do a new sample, if not find heigth of current
  172.     if (sensorvalue > samplePeak) {
  173.         samplePeak = sensorvalue;
  174.     }
  175. }
  176.  
  177. void processSample() {
  178.     int sample = 0;  // This is the bin value of this sample
  179.     if (samplePeak >= sensorthreshold) {
  180.         sample = 1;
  181.     }  // Set to one if it reads "HIGH"
  182.  
  183.     // Left shift buffer
  184.     for (int i = 0; i < bufferSize; i++) {
  185.         soundBuffer[i] = soundBuffer[i + 1];
  186.         yield();
  187.     }
  188.     // Add current sample to the end
  189.     soundBuffer[bufferSize] = sample;
  190.  
  191.     // Cleanup
  192.     samplePeak = 0;
  193.     lastSampleTime = 0;
  194. }
  195.  
  196. String uniqId() {
  197.     randomSeed(analogRead(A0));
  198.     String _uniqId = "";
  199.     for (int i = 0; i < 10; i++) {
  200.         int currSet = random(1,3);
  201.         if (currSet == 1) {
  202.             char chr = random(48, 57);
  203.             _uniqId += String(chr);
  204.         } else if (currSet == 2) {
  205.             char chr = random(65, 90);
  206.             _uniqId += String(chr);
  207.         } else {
  208.             char chr = random(97, 122);
  209.             _uniqId += String(chr);
  210.         }
  211.     }
  212.     return(_uniqId);
  213. }
  214.  
  215. void setLamp(String action) {
  216.     if (action == "ON") {
  217.         lampOn = true;
  218.     } else if (action == "OFF") {
  219.         lampOn = false;
  220.     } else if (action == "TOGGLE") {
  221.         lampOn = !lampOn;
  222.     }
  223.     digitalWrite(lampPin, lampOn);
  224.     yield();
  225. }
  226.  
  227. void setSensor(String action) {
  228.     if (action == "ON") {
  229.         sensorActive = true;
  230.     } else if (action == "OFF") {
  231.         sensorActive = false;
  232.     }
  233. }
  234.  
  235. void handleRoot() {
  236.  
  237.     String bootstrapLink = "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css\" integrity=\"sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\" crossorigin=\"anonymous\">";
  238.  
  239.     for (int i = 0; i < server.args(); i++) {
  240.         String argKey = server.argName(i);
  241.         String argVal = server.arg(i);
  242.         if (argKey == "l") { bootstrapLink = "<link rel=\"stylesheet\" href=\"./bootstrap.css\">"; }
  243.     }
  244.  
  245.     String htmlPage = MAIN_page;
  246.     htmlPage.replace("{{NAME}}", deviceName);
  247.     htmlPage.replace("{{Location}}", deviceLocation);
  248.     htmlPage.replace("{{BOOTSTRAPLINK}}", bootstrapLink);
  249.     if (lampOn) {
  250.         htmlPage.replace("{{LAMPACTIVECHECKED}}", "checked");
  251.     } else {
  252.         htmlPage.replace("{{LAMPACTIVECHECKED}}", "");
  253.     }
  254.     if (sensorActive) {
  255.         htmlPage.replace("{{SENSORCHECKED}}", "checked");
  256.     } else {
  257.         htmlPage.replace("{{SENSORCHECKED}}", "");
  258.     }
  259.     server.send ( 200, "text/html", htmlPage);
  260. }
  261.  
  262. void handleJson() {
  263.     // escape dobbel tøddler med en \ slik \" for å ha dobbel tøddler i en string
  264.  
  265.     for (int i = 0; i < server.args(); i++) {
  266.         String argKey = server.argName(i);
  267.         String argVal = server.arg(i);
  268.  
  269.         if (argKey == "lamp") {
  270.             if (argVal == "1" || argVal == "true") { setLamp("ON"); }
  271.             else if (argVal == "0" || argVal == "false") { setLamp("OFF"); }
  272.             else if (argVal == "toggle" || argVal == "TOGGLE"){ setLamp("TOGGLE"); }
  273.         } else if (argKey == "sens") {
  274.             if (argVal == "1" || argVal == "true") { setSensor("ON"); }
  275.             else { setSensor("OFF"); }
  276.         }
  277.     }
  278.  
  279.     String jsonAnswer = "{";
  280.     jsonAnswer += "\"deviceName\":\"";
  281.     jsonAnswer += deviceName;
  282.     jsonAnswer += "\",\"deviceId\":\"";
  283.     jsonAnswer += deviceId;
  284.     jsonAnswer += "\",\"deviceType\":\"";
  285.     jsonAnswer += deviceType;
  286.     jsonAnswer += "\",\"deviceLocation\":\"";
  287.     jsonAnswer += deviceLocation;
  288.     jsonAnswer += "\",\"lampOn\":\"";
  289.     jsonAnswer += (String)lampOn;
  290.     jsonAnswer += "\",\"sensorOn\":\"";
  291.     jsonAnswer += (String)sensorActive;
  292.     jsonAnswer += "\"}";
  293.     server.send ( 200, "text/html", jsonAnswer);
  294. }
  295.  
  296. void handleSettings() {
  297.     bool settingsSaved = false;
  298.     String successMsg = "";
  299.     String bootstrapLink = "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css\" integrity=\"sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\" crossorigin=\"anonymous\">";
  300.     String type, _deviceName, _deviceLocation, _ssid, _password;
  301.  
  302.     for (int i = 0; i < server.args(); i++) {
  303.         String argKey = server.argName(i);
  304.         String argVal = stripString(server.arg(i));
  305.  
  306.         if (argKey == "txtDeviceName") {
  307.             _deviceName = argVal;
  308.         } else if (argKey == "txtDeviceLocation") {
  309.             _deviceLocation = argVal;
  310.         } else if (argKey == "txtSSID") {
  311.             _ssid = argVal;
  312.         } else if (argKey == "txtPassword") {
  313.             _password = argVal;
  314.         } else if (argKey == "type") {
  315.             type = argVal;
  316.         } else if (argKey == "l") {
  317.             bootstrapLink = "<link rel=\"stylesheet\" href=\"./bootstrap.css\">";
  318.         }
  319.     }
  320.  
  321.     if (type == "settings") {
  322.         if (_deviceName != "") {
  323.             MemoryAccess.writeAscii("deviceName", _deviceName);
  324.         } else if (_deviceLocation != "") {
  325.             MemoryAccess.writeAscii("deviceLocation", _deviceLocation);
  326.         } else if (_ssid != "") {
  327.             MemoryAccess.writeAscii("SSID", _ssid);
  328.             MemoryAccess.writeAscii("Password", _password);
  329.         }
  330.         MemoryAccess.commit();
  331.         successMsg = "Settings updated!";
  332.         settingsSaved = true;
  333.     } else {
  334.         Serial.println("Type undefined...");
  335.     }
  336.  
  337.     String htmlResponse = SETTINGS_page;
  338.     htmlResponse.replace("{{NAME}}", deviceName);
  339.     htmlResponse.replace("{{SUCCESSMSG}}", successMsg);
  340.     htmlResponse.replace("{{DEVICENAME}}", deviceName);
  341.     htmlResponse.replace("{{DEVICELOCATION}}", deviceLocation);
  342.     htmlResponse.replace("{{BOOTSTRAPLINK}}", bootstrapLink);
  343.     server.send( 200, "text/html", htmlResponse );
  344.  
  345.     if (settingsSaved) { hardReset(); }
  346. }
  347.  
  348. void handleStylesheet() {
  349.     String style = stylesheet;
  350.     server.send ( 200, "text/css", style);
  351. }
  352.  
  353. void handleScript() {
  354.     server.send( 200, "text/javascript", main_script);
  355. }
  356.  
  357. void handleNotFound() {
  358.   String message = "File Not Found\n\n";
  359.   message += "URI: ";
  360.   message += server.uri();
  361.   message += "\nMethod: ";
  362.   message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  363.   message += "\nArguments: ";
  364.   message += server.args();
  365.   message += "\n";
  366.  
  367.   for ( uint8_t i = 0; i < server.args(); i++ ) {
  368.     message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  369.   }
  370.  
  371.   server.send ( 404, "text/plain", message );
  372. }
  373.  
  374. String stripString(String _string) {
  375.     _string.replace("\n", "");
  376.     return _string;
  377. }
  378.  
  379. void hardReset() {
  380.     Serial.println("Triggering Watchdog hard reset in 1 sec...");
  381.     ESP.wdtDisable();
  382.     delay(1000);
  383.     while (1);
  384. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement