Guest User

GarageDoorESP

a guest
Jun 25th, 2017
941
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 32.94 KB | None | 0 0
  1. int DEBUGLEVEL = 6;
  2. bool TESTDATA = false; //Send Test data instead of real data
  3.  
  4. const char* ssid = "yourssid!";
  5. const char* pass = "yourpassword";
  6.  
  7.  
  8. #define MAIL_FROM "garage@xxxx.net"
  9. #define MAIL_TO "garage@xxxx.net"
  10. #define MAIL_USER "xxxx" //username for SMTP encoded in base64
  11. #define MAIL_PASS "xxxx" //password for SMTP encoded in base64 WARNING, this is not encrypted!
  12. char mailserver[] = "192.168.99.7"; // your mailserver
  13.  
  14. char host[] = "garagedoor";
  15. bool runDHT = false;
  16. bool runDSTemp = false;
  17. #include <IRremoteESP8266.h>
  18. IRsend irsend(16);
  19.  
  20. #include <DallasTemperature.h>
  21. #include <OneWire.h>
  22. #define ONE_WIRE_BUS D1 //the ds18b20
  23.  
  24. #include <QueueList.h>
  25. #include <DHT.h>
  26. #define DHTTYPE DHT11
  27. #define DHTPIN  D6 //pin for the dht11
  28. #define TEMPERATURE_PRECISION 12
  29.  
  30. #include <TimeLib.h>
  31. #include <TimeLord.h> //calcs sunrise and sunset
  32. #include <TimeAlarms.h> //https://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  33.  
  34. #include <WiFiClient.h>
  35. #include <ESP8266WebServer.h>
  36. #include <ESP8266WiFi.h>
  37. #include <WiFiUdp.h>
  38. #include <ESP8266Ping.h>
  39.  
  40. #include <ArduinoOTA.h>
  41. #include <PubSubClient.h>
  42.  
  43. //#include <NewPing.h>
  44.  
  45. #define DoorSensor D5
  46. #define DoorRelay D1
  47. #define TRIGGER_PIN D1
  48. #define ECHO_PIN D2
  49. #define MAX_DISTANCE 200
  50. //NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);
  51. int pingdistance;
  52. #include <ESP8266mDNS.h>
  53.  
  54. MDNSResponder mdns;
  55.  
  56. #define SensorPin A0
  57.  
  58. /*
  59. debug levels
  60. 1 boot data
  61. 2
  62. 3 what is sent to datasend and syslog
  63. 4
  64. 5
  65. 6 ntp data
  66. 7 full comms
  67. on wemos d2 is the onboard led
  68. on nodemcu 1 is the onboard led
  69.  
  70. */
  71. static  uint32_t DATA_SAMPLE_INTERVAL = 60000; // ms
  72. #ifndef Pins_Arduino_h
  73. #define Pins_Arduino_h
  74.  
  75. #include "../generic/common.h"
  76.  
  77. static const uint8_t SDA = 4;
  78. static const uint8_t SCL = 5;
  79.  
  80. static const uint8_t LED_BUILTIN = 2;
  81. static const uint8_t BUILTIN_LED = 2;
  82.  
  83. static const uint8_t D0   = 16;
  84. static const uint8_t D1   = 5;//SCL
  85. static const uint8_t D2   = 4;//SCA
  86. static const uint8_t D3   = 0;
  87. static const uint8_t D4   = 2;//Wemos LED
  88. static const uint8_t D5   = 14;
  89. static const uint8_t D6   = 12;
  90. static const uint8_t D7   = 13;
  91. static const uint8_t D8   = 15;
  92. static const uint8_t RX   = 3;
  93. static const uint8_t TX   = 1;
  94.  
  95. #endif /* Pins_Arduino_h */
  96. int gpio0_pin = 0;
  97.  
  98. int lastboot;
  99. IPAddress syslogServer(192, 168, 99, 7);
  100. const char* dataserver = "192.168.99.7"; // Your domain  
  101. IPAddress timeServer(192, 168, 99, 7);
  102. IPAddress zeros(0, 0, 0, 0);
  103. IPAddress ip(192,168,99,61);  //Node static IP
  104. IPAddress dns(192,168,99,7);  //Node static IP
  105. IPAddress gateway(192,168,99,1);
  106. IPAddress subnet(255,255,255,0);
  107.  
  108.  
  109. const char* mqtt_server = "192.168.99.7";
  110. const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
  111. int sensorValue = 0;        // value read from the pot
  112. bool timesetviantp = false;
  113. bool lastbootset = false;
  114.  
  115. String lb;
  116.  
  117. OneWire oneWire(ONE_WIRE_BUS);
  118. DallasTemperature DS18B20(&oneWire);
  119.  
  120. DeviceAddress insideThermometer, outsideThermometer;
  121.  
  122. QueueList <String> tcpqueue;
  123. QueueList <String> syslogqueue;
  124. //WiFiServer server2(80);
  125.  
  126. const int EST = -5;    
  127. const int EDT = -4;    
  128. bool SendPressureData  = false;
  129. int LightReading;
  130. int32_t rssi;
  131. unsigned int uptime;
  132. bool GATHERDATAFORCE = false;
  133. WiFiUDP udp;
  134. unsigned int localPort = 8888;  // local port to listen for udp packets
  135. DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
  136. float humidity, temp_f,dstemp1;  // Values read from sensor
  137. ESP8266WebServer server(80);
  138. unsigned long counter1;
  139. WiFiClient client;
  140. PubSubClient mqttclient(client);
  141. long lastMsg = 0;
  142. char msg[50];
  143. int value = 0;
  144. String cmd3;
  145. unsigned long gatherdatatimer = millis();
  146. bool doorflag = false;
  147.  
  148. void setup() {
  149.     Serial.begin(115200);
  150.     delay(100);
  151.     irsend.begin();
  152.  
  153.     Serial.println("");
  154.     /*  
  155. WL_IDLE_STATUS=0
  156. WL_NO_SSID_AVAIL=1
  157. WL_SCAN_COMPLETED=2
  158. WL_CONNECT_FAILED=4
  159. WL_CONNECTED=3
  160. WL_CONNECTION_LOST=5
  161. WL_DISCONNECTED=6
  162. WL_NO_SHIELD=255
  163. */
  164.  
  165.     pinMode(BUILTIN_LED, OUTPUT);
  166.     digitalWrite(BUILTIN_LED, LOW);
  167.    
  168.     digitalWrite(DoorRelay, LOW);
  169.     pinMode(DoorRelay, OUTPUT);
  170.    
  171.     pinMode(DoorSensor, INPUT_PULLUP);
  172.  
  173.     Serial.println("");
  174.     Serial.print("Connecting to ");
  175.     Serial.println(ssid);
  176.     //WiFi.config(ip, dns, gateway, subnet);
  177.     WiFi.begin(ssid, pass);
  178.     mqttclient.setServer(mqtt_server, 1883);
  179.     mqttclient.setCallback(callback);
  180.     /*  while (WiFi.status() != WL_CONNECTED && millis()  <10000) {
  181.         delay(500);
  182.         if (DEBUGLEVEL>=3) Serial.print("Wifi Status=");
  183.         if (DEBUGLEVEL>=3) Serial.println(WiFi.status());
  184.     }
  185.     while (WiFi.localIP() == zeros && millis()  < 20000) {
  186.         delay(500);
  187.         if (DEBUGLEVEL>=3) Serial.print("ip should equal 0 IP=");
  188.         if (DEBUGLEVEL>=3) Serial.println(WiFi.localIP());
  189.     } */
  190.    
  191.     if (WiFi.localIP() != zeros) {
  192.         if (DEBUGLEVEL>=3) Serial.print("IP=");
  193.         if (DEBUGLEVEL>=3) Serial.println(WiFi.localIP());
  194.     }
  195.  
  196.    
  197.  
  198.     Serial.println();
  199.     Serial.print("IP number assigned by DHCP is ");
  200.     Serial.println(WiFi.localIP());
  201.     Serial.println("Starting udp");
  202.     udp.begin(localPort);
  203.     Serial.print("Local port: ");
  204.     Serial.println(udp.localPort());
  205.     Serial.println("waiting for sync");
  206.     ntp();
  207.     lastboot = calculateDayOfYear(day(),month(),year());
  208.     syslog("Booted");
  209.     syslog(__DATE__);
  210.     syslog(__TIME__);
  211.     syslog(__FILE__);
  212.    
  213.     //  server2.begin();
  214.     Serial.println("Server started");
  215.  
  216.     // Print the IP address
  217.     Serial.print("Use this URL to connect: ");
  218.     Serial.print("http://");
  219.     Serial.print(WiFi.localIP());
  220.     Serial.println("/");
  221.    
  222.     Alarm.timerRepeat(14400, ntp);
  223.     if (mdns.begin("GarageESP", WiFi.localIP())) {
  224.         Serial.println("MDNS responder started");
  225.     }
  226.  
  227.     server.on("/home", [](){
  228.         //pingdistance = sonar.ping_cm();
  229.         server.send(200, "text/html", basepage());
  230.     });
  231.     server.on("/", [](){
  232.         //pingdistance = sonar.ping_cm();
  233.         server.send(200, "text/html", basepage());
  234.     });
  235.     server.on("/prtg", [](){
  236.         server.send(200, "text/html", prtgpage());
  237.         rssi = getRSSI(ssid);
  238.     });
  239.     server.on("/operatedoor", [](){
  240.         doorflag = true;
  241.         server.send(200, "text/html", basepage());
  242.     });
  243.     server.on("/gatherdata", [](){
  244.         GATHERDATAFORCE = true;
  245.         server.send(200, "text/html", basepage());
  246.     });
  247.    
  248.     server.on("/ac", [](){
  249.         irsend.sendNEC(279939191, 32);
  250.         server.send(200, "text/html", basepage());
  251.     });
  252.     server.on("/tempup", [](){
  253.         irsend.sendNEC(279949391, 32);
  254.         server.send(200, "text/html", basepage());
  255.     });
  256.     server.on("/tempdown", [](){
  257.         irsend.sendNEC(279933071, 32);
  258.         server.send(200, "text/html", basepage());
  259.     });
  260.    
  261.     server.begin();
  262.     Serial.println("HTTP server started");
  263.    
  264.     // Hostname defaults to esp8266-[ChipID]
  265.     ArduinoOTA.setHostname(host);
  266.  
  267.     // No authentication by default
  268.     // ArduinoOTA.setPassword((const char *)"123");
  269.  
  270.     ArduinoOTA.onStart([]() {
  271.         Serial.println("Start");
  272.     });
  273.     ArduinoOTA.onEnd([]() {
  274.         Serial.println("\nEnd");
  275.     });
  276.     ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  277.         Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  278.     });
  279.     ArduinoOTA.onError([](ota_error_t error) {
  280.         Serial.printf("Error[%u]: ", error);
  281.         if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  282.         else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  283.         else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  284.         else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  285.         else if (error == OTA_END_ERROR) Serial.println("End Failed");
  286.     });
  287.     ArduinoOTA.begin();
  288.     Serial.println("Ready");
  289.     Serial.print("IP address: ");
  290.     Serial.println(WiFi.localIP());
  291.  
  292.     //pingdistance = sonar.ping_cm();
  293. }
  294. void loop(){  
  295.     GatherData();
  296.     processTCP();
  297.     processSyslog();
  298.     Alarm.delay(0);
  299.     server.handleClient();
  300.     //processMQTT();
  301.     readlight();
  302.     //readpressure();
  303.     setlastboot();
  304.     ArduinoOTA.handle();
  305.     //blinkLED();
  306.     operatedoor();
  307.     readDigitalinputs();
  308. }
  309.  
  310. #define inputarrlen  1
  311. int Dinputarr[inputarrlen] = {DoorSensor};
  312. bool prevDigitalInput[inputarrlen] = {1};
  313. unsigned long opened[inputarrlen] = {0};
  314.  
  315.  
  316. void readDigitalinputs(){
  317.     int securedset = 0;
  318.     #define inputarrlen  1
  319.     const int Dinputarr[inputarrlen] = {DoorSensor};
  320.     static bool prevDigitalInput[inputarrlen] = {1};
  321.     static unsigned long opened[inputarrlen] = {0};
  322.     static unsigned long temptime = millis();
  323.     static unsigned long securesettimer = millis();
  324.    
  325.     static unsigned long dooropenedtoolongtimer [inputarrlen]= {millis()};
  326.     if (millis() - temptime > 100UL){
  327.         temptime = millis();
  328.         for(int x=0;x<inputarrlen;x++){//read the onboard
  329.             bool currentDigitalInput = digitalRead(Dinputarr[x]);
  330.             securedset += currentDigitalInput;
  331.  
  332.             if (prevDigitalInput[x]!=currentDigitalInput) {
  333.                 cmd3 = "Input ";
  334.                 //strcpy_P(buffer2, (char*)pgm_read_word(&(string_table[x]))); // Necessary casts and dereferencing, just copy.
  335.                 cmd3 += Dinputarr[x];
  336.                 cmd3 += "-";
  337.                 //cmd3 += String(buffer2);
  338.                 cmd3 += " changed to ";
  339.                 if (currentDigitalInput) {
  340.                     cmd3 += "Open";
  341.                     opened[x] = millis();
  342.                 }
  343.                 else {
  344.                     cmd3 += "Closed. ";
  345.                    
  346.                     cmd3 += "Open for: ";
  347.                     cmd3 += (millis() - opened[x])/1000/60;
  348.                     cmd3 += "m ";
  349.                     cmd3 += (millis() - opened[x])/1000%60;
  350.                     cmd3 += "s";
  351.                    
  352.                 }  
  353.                 prevDigitalInput[x]=currentDigitalInput;
  354.                 if (millis() < 8000) return;
  355.                 syslog(cmd3);
  356.             }
  357.             else if ((millis() - opened[x])/1000 > 600 && millis() - dooropenedtoolongtimer[x] >30000 && currentDigitalInput){     
  358.  
  359.                 dooropenedtoolongtimer[x] = millis();
  360.                 //strcpy_P(buffer2, (char*)pgm_read_word(&(string_table[x]))); // Necessary casts and dereferencing, just copy.
  361.                 cmd3 = Dinputarr[x];
  362.                 //cmd3 += "-";
  363.                 //cmd3 += String(buffer2);
  364.                 cmd3 += " opened too long Opened for ";
  365.                 cmd3 += (millis() - opened[x])/1000;
  366.                 cmd3 += " seconds ";
  367.                 Serial.println(cmd3);
  368.             }
  369.         }
  370.        
  371.  
  372.        
  373.         if (millis() - securesettimer >300000){
  374.             securesettimer = millis();
  375.             cmd3 = "Secure set: ";
  376.             cmd3 +=  securedset;
  377.             syslog(cmd3);
  378.         }
  379.     }
  380. }
  381.  
  382.  
  383. void blinkled2(){
  384.     static unsigned long blinker = millis();
  385.     if (millis()- blinker  >1000){
  386.         blinker = millis();
  387.         digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
  388.     }
  389. }
  390. void blinkLED() {
  391.     static  int brightness = 0;    // how bright the LED is
  392.     static int ledstage =0;
  393.     static unsigned long ledblinker = millis();
  394.     if (ledblinker + 24 <= millis()) {
  395.         if (ledstage == 0){ //ascent1
  396.             brightness = brightness + 30;
  397.             if (brightness > 180 )ledstage++;
  398.         }    
  399.         else if (ledstage == 1){ //decent1
  400.             brightness = brightness - 20;
  401.             if (brightness <21 )ledstage++;
  402.         }  
  403.         else  if (ledstage == 2){ //ascent2
  404.             brightness = brightness + 30;
  405.             if (brightness > 215 )ledstage++;
  406.         }  
  407.         else {//decent2
  408.             brightness = brightness - 5;
  409.             if (brightness < 5 )ledstage=0;
  410.         }
  411.        
  412.         if (ledblinker + 250 <= millis()) {
  413.             digitalWrite(BUILTIN_LED, brightness);
  414.             ledblinker = millis();
  415.         }
  416.     }
  417. }
  418. void setlastboot(){
  419.     static unsigned long initialntptimer = millis();
  420.     if (timesetviantp && !lastbootset){
  421.         lastbootset = true;
  422.         lastboot = calculateDayOfYear(day(),month(),year());
  423.         Serial.println("Last boot set!");
  424.         Serial.print("Last boot day is: ");
  425.         Serial.println(lastboot);
  426.         lb = (year());
  427.         lb += "-";
  428.         if(month() <=9) lb +="0";
  429.         lb += (month());
  430.         lb+= "-";
  431.         if(day() <=9) lb +="0";
  432.         lb += (day());
  433.         lb+= " ";
  434.         if(hour() <=9) lb +="0";
  435.         lb += (hour());
  436.         lb+= ":";
  437.         if(minute() <=9) lb +="0";
  438.         lb += (minute());
  439.         lb+= ":";
  440.         if(second() <=9) lb +="0";
  441.         lb += (second());
  442.         Alarm.alarmRepeat(23, 00, 0, ElevenAlarm); //daily at 3am we create the sunrise and set alarms
  443.         syslog("lastboot set");
  444.         if (DEBUGLEVEL>=3) Serial.print("Wifi setup in ");
  445.         if (DEBUGLEVEL>=3) Serial.print(millis());
  446.         if (DEBUGLEVEL>=3) Serial.println(" ms");
  447.     }
  448.     else if (!timesetviantp && millis() - initialntptimer > 10000){
  449.         initialntptimer = millis();
  450.         ntp();
  451.     }
  452. }
  453. void operatedoor(){
  454.     if(doorflag){
  455.         digitalWrite(DoorRelay, HIGH);
  456.         delay(1000);
  457.         digitalWrite(DoorRelay, LOW);
  458.         doorflag = false;
  459.         syslog("Operated Door");
  460.     }
  461. }
  462. void readlight(){
  463.     static unsigned long readlighttimer = millis();
  464.     if (millis() - readlighttimer > 1000 ){
  465.         readlighttimer = millis();
  466.         LightReading = analogRead(A0);
  467.     }
  468. }
  469. void callback(char* topic, byte* payload, unsigned int length) {
  470.     Serial.print("Message arrived [");
  471.     Serial.print(topic);
  472.     Serial.print("] ");
  473.     for (int i = 0; i < length; i++) {
  474.         Serial.print((char)payload[i]);
  475.     }
  476.     Serial.println();
  477.  
  478.     // Switch on the LED if an 1 was received as first character
  479.     if ((char)payload[0] == '1') {
  480.         digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
  481.         // but actually the LED is on; this is because
  482.         // it is acive low on the ESP-01)
  483.     } else {
  484.         digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  485.     }
  486.  
  487. }
  488. void mqttreconnect() {
  489.     static unsigned long recontimer = millis();
  490.     // Loop until we're reconnected
  491.     if (!mqttclient.connected() && millis() - recontimer > 5000) {
  492.         recontimer = millis();
  493.         Serial.print("Attempting MQTT connection...");
  494.         // Attempt to connect
  495.         if (mqttclient.connect("ESP8266Client")) {
  496.             Serial.println("connected");
  497.             // Once connected, publish an announcement...
  498.             mqttclient.publish("outTopic", "hello world");
  499.             // ... and resubscribe
  500.             mqttclient.subscribe("inTopic");
  501.         } else {
  502.             Serial.print("failed, rc=");
  503.             Serial.print(mqttclient.state());
  504.             Serial.println(" try again in 5 seconds");
  505.             // Wait 5 seconds before retrying
  506.         }
  507.     }
  508. }
  509. void processMQTT(){
  510.     static unsigned long recontimer = millis();
  511.     // Loop until we're reconnected
  512.     if (!mqttclient.connected() && millis() - recontimer > 5000) {
  513.         recontimer = millis();
  514.         Serial.print("Attempting MQTT connection...");
  515.         // Attempt to connect
  516.         if (mqttclient.connect("ESP8266Client")) {
  517.             Serial.println("connected");
  518.             // Once connected, publish an announcement...
  519.             mqttclient.publish("outTopic", "hello world");
  520.             // ... and resubscribe
  521.             mqttclient.subscribe("inTopic");
  522.         } else {
  523.             Serial.print("failed, rc=");
  524.             Serial.print(mqttclient.state());
  525.             Serial.println(" try again in 5 seconds");
  526.             // Wait 5 seconds before retrying
  527.         }
  528.     }
  529.     else {
  530.         mqttclient.loop();
  531.  
  532.         unsigned long now = millis();
  533.         if (now - lastMsg > 2000) {
  534.             lastMsg = now;
  535.             ++value;
  536.             //  snprintf (msg, 75, "temp %4.2F", dstemp1);
  537.             // sprintf (msg, "temp %f", dstemp1);
  538.             dtostrf(dstemp1,5,2,msg);
  539.            
  540.             Serial.print("Publish message: ");
  541.             Serial.println(msg);
  542.             mqttclient.publish("garagetemp", msg);
  543.         }}
  544. }
  545. String prtgpage(){
  546.     String thePage = "<prtg>";
  547.  
  548.     thePage += "<result><channel>uptime</channel><value>";
  549.     thePage += uptime;
  550.     thePage += "</value><FLOAT>1</FLOAT><CustomUnit>d</CustomUnit></result>";
  551.     if (rssi<0){
  552.         thePage += "<result><channel>rssi</channel><value>";
  553.         thePage += rssi;
  554.         thePage += "</value><FLOAT>1</FLOAT><CustomUnit>db</CustomUnit></result>";
  555.     }
  556.     thePage += "<result><channel>pingdistance</channel><value>";
  557.     thePage += pingdistance;
  558.     thePage += "</value><FLOAT>1</FLOAT><CustomUnit>cm</CustomUnit></result>";
  559.    
  560.     thePage += "<result><channel>raw a0</channel><value>";
  561.     thePage +=1023- LightReading;
  562.     thePage += "</value><FLOAT>1</FLOAT><CustomUnit>A0</CustomUnit></result>";
  563.  
  564.     thePage += "<result><channel>DoorStatus</channel><value>";
  565.     thePage += digitalRead(DoorSensor);
  566.     thePage += "</value><FLOAT>1</FLOAT></result>";
  567.    
  568.    
  569.     thePage += "</prtg>";
  570.     return thePage;
  571.    
  572. }
  573. String basepage(){
  574.     String thePage = "<h1>The ";
  575.     thePage += host;
  576.     if(TESTDATA) thePage += "test";
  577.     thePage += " ESP</h1>";
  578.     thePage += "<p><a href=\"operatedoor\"><button>Operate Door</button></a>&nbsp";
  579.    
  580.     thePage += "<br><br>";
  581.     thePage += "<a href=\"ac\"><button>AC</button></a>&nbsp";
  582.     thePage += "<a href=\"tempup\"><button>tempup</button></a>&nbsp";
  583.     thePage += "<a href=\"tempdown\"><button>tempdown</button></a>&nbsp";
  584.     thePage += "<br><br>";
  585.     thePage += "<a href=\"gatherdata\"><button>Gatherdata</button></a>&nbsp";
  586.     thePage += "<a href=\"ntp\"><button>NTP</button></a>&nbsp";
  587.     thePage += "<a href=\"home\"><button>Update page</button></a>&nbsp";
  588.  
  589.     thePage +="</p>";
  590.     thePage += "<br>";
  591.    
  592.     thePage += "The garage door is ";
  593.     if (!digitalRead(DoorSensor)) thePage += "closed";
  594.     else  thePage += "open";
  595.     thePage += ".<br>";
  596.  
  597.     thePage += "The light sensor reads ";
  598.     thePage += 1023- LightReading;
  599.     thePage += ".<br>";
  600.    
  601.     thePage += "The A0 Raw ";
  602.     thePage += LightReading;
  603.     thePage += ".<br>";
  604.    
  605.     thePage += "The LED is ";
  606.     if (digitalRead(BUILTIN_LED))thePage += "off";
  607.     else thePage += "on";
  608.     thePage += ".<br>";
  609.  
  610.     thePage += "The distance is ";
  611.     thePage += pingdistance;
  612.     thePage += ".<br>";
  613.  
  614.     thePage += "The uptime is ";
  615.     thePage += uptime;
  616.     thePage += " days.<br>";
  617.    
  618.     thePage += "<br><br>";
  619.     thePage +="This Page was created at: ";
  620.     if(hour() <=9) thePage +="0";
  621.     thePage +=hour();
  622.     thePage +=":";
  623.     if(minute() <=9) thePage +="0";
  624.     thePage +=minute();
  625.     thePage +=":";
  626.     if(second() <=9) thePage +="0";
  627.     thePage += second();
  628.     thePage += ".<br>";
  629.     thePage +="Last boot: ";
  630.    
  631.     thePage +=lb;
  632.    
  633.     thePage += ".<br>";
  634.    
  635.     thePage += "Build Date: ";
  636.     thePage +=(__DATE__);
  637.     thePage += ":  ";
  638.     thePage +=(__TIME__);
  639.     thePage += "<br>";
  640.     thePage += "Build file: ";
  641.     thePage +=(__FILE__);
  642.     return thePage;
  643. }
  644. /*
  645. void servepage(){
  646.         // Check if a client has connected
  647.     WiFiClient client = server2.available();
  648.     if (!client) {
  649.         return;
  650.     }
  651.  
  652.     // Wait until the client sends some data
  653.     Serial.println("new client");
  654.     while(!client.available()){
  655.         delay(1);
  656.     }
  657.  
  658.     // Read the first line of the request
  659.     String request = client.readStringUntil('\r');
  660.     Serial.println(request);
  661.     client.flush();
  662.  
  663.     // Match the request
  664.  
  665.     int value = LOW;
  666.     if (request.indexOf("/LED1") != -1) {
  667.         digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
  668.         value = LOW;
  669.     }
  670.     if (request.indexOf("/LED=OFF") != -1) {
  671.         digitalWrite(BUILTIN_LED, HIGH);
  672.         value = HIGH;
  673.     }
  674.  
  675.     // Set BUILTIN_LED according to the request
  676.     //digitalWrite(BUILTIN_LED, value);
  677.  
  678.     // Return the response
  679.  
  680.         client.println("HTTP/1.1 200 OK");
  681.         client.println("Content-Type: text/html");
  682.         client.println("Connection: close");  // the connection will be closed after completion of the response
  683.         client.println("Refresh: 5");  // refresh the page automatically every 5 sec
  684.         client.println();
  685.         client.println("<!DOCTYPE HTML>");
  686.         client.println("<html>");
  687.        
  688.        
  689.        
  690.     client.print("Led pin is now: ");
  691.  
  692.     if(!digitalRead(BUILTIN_LED)) {
  693.         client.print("On");
  694.     } else {
  695.         client.print("Off");
  696.     }
  697.     client.println("<br><br>");
  698.     client.println("Click <a href=\"/LED1\">here</a> toggle the LED on pin 2 ON<br>");
  699.     client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 2 OFF<br>");
  700.    
  701.     client.println("<br><br>");
  702.    
  703.     client.print("The time is: ");
  704.     if(hour() <=9) client.print("0");
  705.     client.print(hour());
  706.     client.print(":");
  707.     if(minute() <=9) client.print("0");
  708.     client.print(minute());
  709.     client.print(":");
  710.     if(second() <=9) client.print("0");
  711.     client.println(second());
  712.        
  713.     client.println("</html>");
  714.  
  715.     delay(1);
  716.     Serial.println("Client disonnected");
  717.     Serial.println("");
  718.    
  719. }
  720.  
  721. */
  722. void GatherData(){
  723.     if (millis() - gatherdatatimer > DATA_SAMPLE_INTERVAL || GATHERDATAFORCE){//once every five minutes update the temp
  724.         gatherdatatimer = millis();
  725.         GATHERDATAFORCE = false;
  726.         Serial.print("Wifi status: ");
  727.         Serial.println(WiFi.status());
  728.        
  729.        
  730.         //      pingdistance = sonar.ping_cm();
  731.         if (runDHT) {getDHTtemperature();       // read sensor
  732.             Serial.print("DHT Temp: ");
  733.             Serial.println(String(temp_f));
  734.             Serial.print("DHT humidity: ");
  735.             Serial.println(String(humidity));
  736.             if (!isnan(temp_f)){
  737.                 if(TESTDATA) cmd3 = "test";
  738.                 else cmd3 = host;
  739.                 cmd3 += "temp2,";
  740.                 cmd3 += (String(temp_f));
  741.                 //tcpqueue.push (cmd3);
  742.                
  743.                 if(TESTDATA) cmd3 = "test";
  744.                 else cmd3 = host;
  745.                 cmd3 += "hum1,";
  746.                 cmd3 += (String(humidity));
  747.                 //tcpqueue.push (cmd3);
  748.                 if (DEBUGLEVEL>=5)syslog(cmd3);
  749.             }
  750.         }
  751.  
  752.        
  753.         if (runDSTemp){
  754.             dstemp1 =  GetDsTemp();
  755.             if (dstemp1 != 0){
  756.                 if(TESTDATA) cmd3 = "test";
  757.                 else cmd3 = host;
  758.                 cmd3 += "temp1,";
  759.                 cmd3 += dstemp1;
  760.                 //tcpqueue.push (cmd3);
  761.                 if (DEBUGLEVEL>=5)syslog(cmd3);
  762.             }
  763.             else Serial.println("DS temp failed");
  764.             if (DEBUGLEVEL>=5)syslog(cmd3);
  765.         }
  766.        
  767.         int dayofyear = calculateDayOfYear(day(),month(),year()); //current day of year
  768.         uptime = dayofyear - lastboot;
  769.         if(TESTDATA) cmd3 = "test";
  770.         else cmd3 = host;
  771.         cmd3 +=  ("uptime,");
  772.         cmd3 += (uptime);
  773.         //tcpqueue.push(cmd3);
  774.         if (DEBUGLEVEL>=5) syslog(cmd3);
  775.        
  776.         //rssi = getRSSI(ssid);
  777.         if(TESTDATA) cmd3 = "test";
  778.         else cmd3 = host;
  779.         cmd3 += "wifi,";
  780.         cmd3 += rssi;
  781.         //tcpqueue.push (cmd3);
  782.         if (DEBUGLEVEL>=5) syslog(cmd3);   
  783.        
  784.         SendPressureData = true;
  785.     }
  786. }
  787.  
  788. int calculateDayOfYear(int day, int month, int year) {
  789.     // Given a day, month, and year (4 digit), returns
  790.     // the day of year. Errors return 999.
  791.     int daysInMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
  792.  
  793.     // Verify we got a 4-digit year
  794.     if (year < 1000) {
  795.         return 999;
  796.     }
  797.  
  798.     // Check if it is a leap year, this is confusing business
  799.     // See: https://support.microsoft.com/en-us/kb/214019
  800.     if (year%4  == 0) {
  801.         if (year%100 != 0) {
  802.             daysInMonth[1] = 29;
  803.         }
  804.         else {
  805.             if (year%400 == 0) {
  806.                 daysInMonth[1] = 29;
  807.             }
  808.         }
  809.     }
  810.  
  811.     // Make sure we are on a valid day of the month
  812.     if (day < 1)
  813.     {
  814.         return 999;
  815.     } else if (day > daysInMonth[month-1]) {
  816.         return 999;
  817.     }
  818.  
  819.     int doy = 0;
  820.     for (int i = 0; i < month - 1; i++) {
  821.         doy += daysInMonth[i];
  822.     }
  823.  
  824.     doy += day;
  825.     return doy;
  826. }
  827. void printAddress(DeviceAddress deviceAddress){// function to print a device address
  828.     for (uint8_t i = 0; i < 8; i++) {
  829.         if (deviceAddress[i] < 16) Serial.print("0");
  830.         Serial.print(deviceAddress[i], HEX);
  831.     }
  832. }
  833. String ipToString(IPAddress ip){
  834.     String s="";
  835.     for (int i=0; i<4; i++)
  836.     s += i  ? "." + String(ip[i]) : String(ip[i]);
  837.     return s;
  838.     //- See more at: http://www.esp8266.com/viewtopic.php?p=25466#sthash.YLEOLQu6.dpuf
  839. }
  840.  
  841. void processTCP(){
  842.     String sensorname;
  843.     String sensordata;
  844.     if (!tcpqueue.isEmpty() && checkconnection()){
  845.         static unsigned long lasttcpsent = millis();
  846.         if(millis()-lasttcpsent < 500) return;
  847.         lasttcpsent = millis();
  848.         cmd3 = tcpqueue.pop ();
  849.         int commaIndex = cmd3.indexOf(',');
  850.         sensorname = cmd3.substring(0, commaIndex);
  851.         sensordata = cmd3.substring(commaIndex+1);
  852.         cmd3 = "GET /";
  853.         cmd3 += sensorname;
  854.         cmd3 += F("?value=");
  855.         cmd3 += sensordata;
  856.         cmd3 += F(" HTTP/1.1\r\n");
  857.         cmd3 += F("Host: server:5050\r\n\r\n");
  858.  
  859.  
  860.         WiFiClient client;
  861.         const int httpPort = 5050;
  862.         if (!client.connect(dataserver, httpPort)) {
  863.             Serial.println("connection failed");
  864.             return;
  865.         }
  866.         client.print(cmd3);
  867.         if (DEBUGLEVEL>=5)Serial.println(cmd3);
  868.         delay(100);
  869.         while(client.available()){
  870.             cmd3 = client.readStringUntil('\r');
  871.             if (DEBUGLEVEL>=7) Serial.println(cmd3);
  872.         }
  873.        
  874.     }  
  875. }
  876. void processSyslog(){
  877.     if (!syslogqueue.isEmpty()){
  878.         static unsigned long lastsyslogsent = millis();
  879.         if(millis()-lastsyslogsent < 100) return;
  880.         lastsyslogsent = millis();
  881.         String Somedata = syslogqueue.pop();
  882.         unsigned int msg_length = Somedata.length();
  883.         byte* p = (byte*)malloc(msg_length);
  884.         memcpy(p, Somedata.c_str(), msg_length);
  885.         udp.beginPacket(syslogServer, 514);
  886.         //udp.write(Somedata.c_str(), msg_length);
  887.         udp.write(p, msg_length);
  888.         udp.endPacket();
  889.         free(p);
  890.     }
  891. }
  892. int32_t getRSSI(const char* target_ssid) {
  893.     byte available_networks = WiFi.scanNetworks();
  894.     for (int network = 0; network < available_networks; network++) {
  895.         if (strcmp(WiFi.SSID(network).c_str(), target_ssid) == 0) {
  896.             return WiFi.RSSI(network);
  897.         }
  898.     }
  899.     return 0;
  900. }
  901. float GetDsTemp() {
  902.     float temp;DS18B20.requestTemperatures();
  903.     temp = DS18B20.getTempCByIndex(0);
  904.     if(DEBUGLEVEL>+5)Serial.print("Raw temp data ");
  905.     if(DEBUGLEVEL>+5)Serial.println(temp);
  906.    
  907.     if (temp == 85.0 || temp == (-127.0)) return 0;
  908.     temp = temp *1.8 +32;
  909.     return temp;
  910. }
  911. void getDHTtemperature() {
  912.     // Wait at least 2 seconds seconds between measurements.
  913.     // if the difference between the current time and last time you read
  914.     // the sensor is bigger than the interval you set, read the sensor
  915.     // Works better than delay for things happening elsewhere also
  916.    
  917.     const long interval = 2000;              // interval at which to read sensor
  918.     static unsigned long previousMillis = 0;        // will store last temp was read
  919.     unsigned long currentMillis = millis();
  920.  
  921.     if(currentMillis - previousMillis >= interval) {
  922.         // save the last time you read the sensor
  923.         previousMillis = currentMillis;  
  924.  
  925.         // Reading temperature for humidity takes about 250 milliseconds!
  926.         // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
  927.         humidity = dht.readHumidity();          // Read humidity (percent)
  928.         temp_f = dht.readTemperature(true);     // Read temperature as Fahrenheit
  929.         // Check if any reads failed and exit early (to try again).
  930.         if (isnan(humidity) || isnan(temp_f)) {
  931.             Serial.println("Failed to read from DHT sensor!");
  932.             return;
  933.         }
  934.     }
  935. }
  936. /*-------- NTP code ----------*/
  937. const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
  938. byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
  939. void ntp(){
  940.     syslog("ntp begin sync");
  941.     if (checkconnection()) setSyncProvider(getNtpTime);
  942.     syslog("ntp finished sync");
  943. }
  944. time_t getNtpTime(){
  945.     while (udp.parsePacket() > 0) ; // discard any previously received packets
  946.     if (DEBUGLEVEL >=7)Serial.println("Transmit NTP Request");
  947.     sendNTPpacket(timeServer);
  948.     uint32_t beginWait = millis();
  949.     while (millis() - beginWait < 1500) {
  950.         int size = udp.parsePacket();
  951.         if (size >= NTP_PACKET_SIZE) {
  952.             if (DEBUGLEVEL >=7)Serial.println("Receive NTP Response");
  953.             udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
  954.             unsigned long secsSince1900;
  955.             // convert four bytes starting at location 40 to a long integer
  956.             secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
  957.             secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  958.             secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  959.             secsSince1900 |= (unsigned long)packetBuffer[43];
  960.             //setSyncProvider((getExternalTime)secsSince1900 - 2208988800UL + EST * SECS_PER_HOUR);
  961.             timesetviantp = true;
  962.             if (IsDST)  return secsSince1900 - 2208988800UL + EDT * SECS_PER_HOUR;
  963.             else return secsSince1900 - 2208988800UL +  EST * SECS_PER_HOUR;
  964.         }
  965.     }
  966.     Serial.println("No NTP Response :-(");
  967.     return 0; // return 0 if unable to get the time
  968. }
  969. bool IsDST() {
  970.     // IsDST() returns true if DST, false otherwise
  971.     // variables: mo - month [1-12], dy - date [1-31], dw - day of the week [0-Sunday, 1-Monday etc.]
  972.     if (month() < 3 || month() > 11) { return false; }      // January, February, and December are out.
  973.     if (month() > 3 && month() < 11) { return true;  }      // April to October are in DST
  974.     int lastSunday = day() - weekday();
  975.     if (month() == 3) { return lastSunday >= 7; }      // In March, we are DST if the previous Sunday was on or after the 8th.
  976.     return lastSunday < 0;                       // In November we must be before the first Sunday to be DST - the previous Sunday must be before the 1st.
  977. }
  978. void sendNTPpacket(IPAddress &address){// send an NTP request to the time server at the given address
  979.     // set all bytes in the buffer to 0
  980.     memset(packetBuffer, 0, NTP_PACKET_SIZE);
  981.     // Initialize values needed to form NTP request
  982.     // (see URL above for details on the packets)
  983.     packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  984.     packetBuffer[1] = 0;     // Stratum, or type of clock
  985.     packetBuffer[2] = 6;     // Polling Interval
  986.     packetBuffer[3] = 0xEC;  // Peer Clock Precision
  987.     // 8 bytes of zero for Root Delay & Root Dispersion
  988.     packetBuffer[12]  = 49;
  989.     packetBuffer[13]  = 0x4E;
  990.     packetBuffer[14]  = 49;
  991.     packetBuffer[15]  = 52;
  992.     // all NTP fields have been given values, now
  993.     // you can send a packet requesting a timestamp:                
  994.     udp.beginPacket(address, 123); //NTP requests are to port 123
  995.     udp.write(packetBuffer, NTP_PACKET_SIZE);
  996.     udp.endPacket();
  997. }
  998. void syslog(String x){
  999.     static int syslogindex;
  1000.     syslogindex++;
  1001.     String Somedata = "<166>"; //LOCAL4.INFO
  1002.     Somedata += syslogindex;
  1003.     if (hour() <=9) Somedata += " 0";
  1004.     else Somedata += " ";
  1005.     Somedata += String(hour());
  1006.     Somedata += ":";
  1007.     if (minute() <=9)   Somedata += "0";
  1008.     Somedata += String(minute());
  1009.     Somedata += ":";
  1010.     if (second() <=9)   Somedata += "0";
  1011.     Somedata += String(second());  
  1012.     Somedata += " ";
  1013.     Somedata += host;
  1014.     if(TESTDATA)  Somedata += "Test ";
  1015.     else Somedata += " ";
  1016.     Somedata += x;
  1017.     if (DEBUGLEVEL>=5) Serial.print(F("syslog: "));
  1018.     if (DEBUGLEVEL>=5) Serial.println(Somedata);
  1019.     if (syslogqueue.count()<20)syslogqueue.push(Somedata);
  1020.     else if (DEBUGLEVEL>=6) Serial.println("Syslog queue is full");
  1021. }
  1022. bool checkconnection(){
  1023.     static int badcounter = 0;
  1024.     if (WiFi.status() == WL_CONNECTED)return true;
  1025.     if(Ping.ping(timeServer)){
  1026.         if (DEBUGLEVEL>=3) Serial.println("Check conn - ping success");
  1027.         return true;
  1028.     }
  1029.     else if (DEBUGLEVEL>=3) Serial.println("Check conn - ping failed");
  1030.    
  1031.     if (WiFi.status() != WL_CONNECTED) {
  1032.         if (DEBUGLEVEL>=3) Serial.print("Wifi Status did not equal WL_CONNECTED Status=");
  1033.         if (DEBUGLEVEL>=3) Serial.println(WiFi.status());
  1034.  
  1035.         WiFi.config(ip, dns, gateway, subnet);
  1036.         WiFi.begin(ssid, pass);
  1037.        
  1038.         unsigned long connecttime = millis();
  1039.         /*      while (WiFi.status() != WL_CONNECTED && millis() - connecttime <20000) {
  1040.             delay(500);
  1041.             if (DEBUGLEVEL>=3) Serial.print("Wifi Status=");
  1042.             if (DEBUGLEVEL>=3) Serial.println(WiFi.status());
  1043.         } */
  1044.         Serial.println(".");
  1045.         if (WiFi.status() == WL_CONNECTED) return true;
  1046.     }
  1047.     else {
  1048.         badcounter++;
  1049.         if (badcounter > 10) ESP.reset();
  1050.         return false;  
  1051.        
  1052.     }
  1053. }
  1054. void ElevenAlarm(){
  1055.     if (digitalRead(DoorSensor)) {
  1056.         sendEmail("The Garage Door is open","");
  1057.     }  
  1058.     if (LightReading< 500){
  1059.         sendEmail("The Garage Light is on","");
  1060.     }
  1061.    
  1062.     syslog("elevenalarm done");
  1063. }
  1064. //email
  1065. byte sendEmail(String mailSubject, String mailMessage){
  1066. #define MAIL_FROM "garage@xxxx.net"
  1067. #define MAIL_TO "garage@xxxx.net"
  1068. #define MAIL_USER "xxxx"
  1069. #define MAIL_PASS "xxxx"
  1070.     char mailserver[] = "192.168.99.7";
  1071.     int port = 25;
  1072.     byte thisByte = 0;
  1073.     byte respCode;
  1074.  
  1075.     if(client.connect(mailserver,port) == 1) {
  1076.         Serial.println(F("connected"));
  1077.     } else {
  1078.         Serial.println(F("connection failed"));
  1079.         return 0;
  1080.     }
  1081.     if(!eRcv()) return 0;
  1082.  
  1083.     Serial.println(F("Sending hello"));
  1084.     // replace 1.2.3.4 with your Arduino's ip
  1085.     client.println("EHLO 1.2.3.4");
  1086.     if(!eRcv()) return 0;
  1087.  
  1088.     Serial.println(F("Sending auth login"));
  1089.     client.println("auth login");
  1090.     if(!eRcv()) return 0;
  1091.  
  1092.     Serial.println(F("Sending User"));
  1093.     // Change to your base64 encoded user
  1094.     client.println(MAIL_USER);
  1095.     if(!eRcv()) return 0;
  1096.  
  1097.     Serial.println(F("Sending Password"));
  1098.     // change to your base64 encoded password
  1099.     client.println(MAIL_PASS);
  1100.     if(!eRcv()) return 0;
  1101.  
  1102.     // change to your email address (sender)
  1103.     Serial.println(F("Sending From"));
  1104.     client.print(F("MAIL From: "));
  1105.     client.println(F(MAIL_FROM));
  1106.     if(!eRcv()) return 0;
  1107.  
  1108.     // change to recipient address
  1109.     Serial.println(F("Sending To"));
  1110.     client.print(F("RCPT To: "));
  1111.     client.println(F(MAIL_TO));
  1112.     if(!eRcv()) return 0;
  1113.  
  1114.     Serial.println(F("Sending DATA"));
  1115.     client.println("DATA");
  1116.     if(!eRcv()) return 0;
  1117.  
  1118.     Serial.println(F("Sending email"));
  1119.  
  1120.     // change to recipient address
  1121.     //client.println("To: You <me@theawesomes.net>");
  1122.     client.print(F("To: "));
  1123.     client.println(F(MAIL_TO));
  1124.    
  1125.     client.print("Subject: ");
  1126.     client.print(mailSubject);
  1127.     client.println("\r\n");
  1128.    
  1129.     // change to your address
  1130.     //client.println("From: Me <me@theawesomes.net>");
  1131.     client.print(F("From: "));
  1132.     client.println(F(MAIL_FROM));
  1133.    
  1134.    
  1135.     client.print("Subject: ");
  1136.     client.print(mailSubject);
  1137.     client.println("\r\n");
  1138.     client.println(mailMessage);
  1139.     client.println(".");
  1140.     if(!eRcv()) return 0;
  1141.  
  1142.     Serial.println(F("Sending QUIT"));
  1143.     client.println("QUIT");
  1144.     if(!eRcv()) return 0;
  1145.  
  1146.     client.stop();
  1147.     Serial.println(F("disconnected"));
  1148.  
  1149.     return 1;
  1150. }
  1151. byte eRcv(){
  1152.     byte respCode;
  1153.     byte thisByte;
  1154.     int loopCount = 0;
  1155.  
  1156.     while(!client.available()) {
  1157.         delay(1);
  1158.         loopCount++;
  1159.         // if nothing received for 10 seconds, timeout
  1160.         if(loopCount > 10000) {
  1161.             client.stop();
  1162.             Serial.println(F("\r\nTimeout"));
  1163.             return 0;
  1164.         }
  1165.     }
  1166.     respCode = client.peek();
  1167.     while(client.available())   {  
  1168.         thisByte = client.read();    
  1169.         Serial.write(thisByte);
  1170.     }
  1171.  
  1172.     if(respCode >= '4') {
  1173.         efail();
  1174.         return 0;  
  1175.     }
  1176.  
  1177.     return 1;
  1178. }
  1179. void efail(){
  1180.     byte thisByte = 0;
  1181.     int loopCount = 0;
  1182.     client.println(F("QUIT"));
  1183.     while(!client.available()) {
  1184.         delay(1);
  1185.         loopCount++;
  1186.  
  1187.         // if nothing received for 10 seconds, timeout
  1188.         if(loopCount > 10000) {
  1189.             client.stop();
  1190.             Serial.println(F("\r\nTimeout"));
  1191.             return;
  1192.         }
  1193.     }
  1194.     while(client.available())   {  
  1195.         thisByte = client.read();    
  1196.         Serial.write(thisByte);
  1197.     }
  1198.     client.stop();
  1199.     Serial.println(F("disconnected"));
  1200. }
Add Comment
Please, Sign In to add comment