Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int DEBUGLEVEL = 6;
- bool TESTDATA = false; //Send Test data instead of real data
- const char* ssid = "yourssid!";
- const char* pass = "yourpassword";
- #define MAIL_FROM "garage@xxxx.net"
- #define MAIL_TO "garage@xxxx.net"
- #define MAIL_USER "xxxx" //username for SMTP encoded in base64
- #define MAIL_PASS "xxxx" //password for SMTP encoded in base64 WARNING, this is not encrypted!
- char mailserver[] = "192.168.99.7"; // your mailserver
- char host[] = "garagedoor";
- bool runDHT = false;
- bool runDSTemp = false;
- #include <IRremoteESP8266.h>
- IRsend irsend(16);
- #include <DallasTemperature.h>
- #include <OneWire.h>
- #define ONE_WIRE_BUS D1 //the ds18b20
- #include <QueueList.h>
- #include <DHT.h>
- #define DHTTYPE DHT11
- #define DHTPIN D6 //pin for the dht11
- #define TEMPERATURE_PRECISION 12
- #include <TimeLib.h>
- #include <TimeLord.h> //calcs sunrise and sunset
- #include <TimeAlarms.h> //https://www.pjrc.com/teensy/td_libs_TimeAlarms.html
- #include <WiFiClient.h>
- #include <ESP8266WebServer.h>
- #include <ESP8266WiFi.h>
- #include <WiFiUdp.h>
- #include <ESP8266Ping.h>
- #include <ArduinoOTA.h>
- #include <PubSubClient.h>
- //#include <NewPing.h>
- #define DoorSensor D5
- #define DoorRelay D1
- #define TRIGGER_PIN D1
- #define ECHO_PIN D2
- #define MAX_DISTANCE 200
- //NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);
- int pingdistance;
- #include <ESP8266mDNS.h>
- MDNSResponder mdns;
- #define SensorPin A0
- /*
- debug levels
- 1 boot data
- 2
- 3 what is sent to datasend and syslog
- 4
- 5
- 6 ntp data
- 7 full comms
- on wemos d2 is the onboard led
- on nodemcu 1 is the onboard led
- */
- static uint32_t DATA_SAMPLE_INTERVAL = 60000; // ms
- #ifndef Pins_Arduino_h
- #define Pins_Arduino_h
- #include "../generic/common.h"
- static const uint8_t SDA = 4;
- static const uint8_t SCL = 5;
- static const uint8_t LED_BUILTIN = 2;
- static const uint8_t BUILTIN_LED = 2;
- static const uint8_t D0 = 16;
- static const uint8_t D1 = 5;//SCL
- static const uint8_t D2 = 4;//SCA
- static const uint8_t D3 = 0;
- static const uint8_t D4 = 2;//Wemos LED
- static const uint8_t D5 = 14;
- static const uint8_t D6 = 12;
- static const uint8_t D7 = 13;
- static const uint8_t D8 = 15;
- static const uint8_t RX = 3;
- static const uint8_t TX = 1;
- #endif /* Pins_Arduino_h */
- int gpio0_pin = 0;
- int lastboot;
- IPAddress syslogServer(192, 168, 99, 7);
- const char* dataserver = "192.168.99.7"; // Your domain
- IPAddress timeServer(192, 168, 99, 7);
- IPAddress zeros(0, 0, 0, 0);
- IPAddress ip(192,168,99,61); //Node static IP
- IPAddress dns(192,168,99,7); //Node static IP
- IPAddress gateway(192,168,99,1);
- IPAddress subnet(255,255,255,0);
- const char* mqtt_server = "192.168.99.7";
- const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
- int sensorValue = 0; // value read from the pot
- bool timesetviantp = false;
- bool lastbootset = false;
- String lb;
- OneWire oneWire(ONE_WIRE_BUS);
- DallasTemperature DS18B20(&oneWire);
- DeviceAddress insideThermometer, outsideThermometer;
- QueueList <String> tcpqueue;
- QueueList <String> syslogqueue;
- //WiFiServer server2(80);
- const int EST = -5;
- const int EDT = -4;
- bool SendPressureData = false;
- int LightReading;
- int32_t rssi;
- unsigned int uptime;
- bool GATHERDATAFORCE = false;
- WiFiUDP udp;
- unsigned int localPort = 8888; // local port to listen for udp packets
- DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
- float humidity, temp_f,dstemp1; // Values read from sensor
- ESP8266WebServer server(80);
- unsigned long counter1;
- WiFiClient client;
- PubSubClient mqttclient(client);
- long lastMsg = 0;
- char msg[50];
- int value = 0;
- String cmd3;
- unsigned long gatherdatatimer = millis();
- bool doorflag = false;
- void setup() {
- Serial.begin(115200);
- delay(100);
- irsend.begin();
- Serial.println("");
- /*
- WL_IDLE_STATUS=0
- WL_NO_SSID_AVAIL=1
- WL_SCAN_COMPLETED=2
- WL_CONNECT_FAILED=4
- WL_CONNECTED=3
- WL_CONNECTION_LOST=5
- WL_DISCONNECTED=6
- WL_NO_SHIELD=255
- */
- pinMode(BUILTIN_LED, OUTPUT);
- digitalWrite(BUILTIN_LED, LOW);
- digitalWrite(DoorRelay, LOW);
- pinMode(DoorRelay, OUTPUT);
- pinMode(DoorSensor, INPUT_PULLUP);
- Serial.println("");
- Serial.print("Connecting to ");
- Serial.println(ssid);
- //WiFi.config(ip, dns, gateway, subnet);
- WiFi.begin(ssid, pass);
- mqttclient.setServer(mqtt_server, 1883);
- mqttclient.setCallback(callback);
- /* while (WiFi.status() != WL_CONNECTED && millis() <10000) {
- delay(500);
- if (DEBUGLEVEL>=3) Serial.print("Wifi Status=");
- if (DEBUGLEVEL>=3) Serial.println(WiFi.status());
- }
- while (WiFi.localIP() == zeros && millis() < 20000) {
- delay(500);
- if (DEBUGLEVEL>=3) Serial.print("ip should equal 0 IP=");
- if (DEBUGLEVEL>=3) Serial.println(WiFi.localIP());
- } */
- if (WiFi.localIP() != zeros) {
- if (DEBUGLEVEL>=3) Serial.print("IP=");
- if (DEBUGLEVEL>=3) Serial.println(WiFi.localIP());
- }
- Serial.println();
- Serial.print("IP number assigned by DHCP is ");
- Serial.println(WiFi.localIP());
- Serial.println("Starting udp");
- udp.begin(localPort);
- Serial.print("Local port: ");
- Serial.println(udp.localPort());
- Serial.println("waiting for sync");
- ntp();
- lastboot = calculateDayOfYear(day(),month(),year());
- syslog("Booted");
- syslog(__DATE__);
- syslog(__TIME__);
- syslog(__FILE__);
- // server2.begin();
- Serial.println("Server started");
- // Print the IP address
- Serial.print("Use this URL to connect: ");
- Serial.print("http://");
- Serial.print(WiFi.localIP());
- Serial.println("/");
- Alarm.timerRepeat(14400, ntp);
- if (mdns.begin("GarageESP", WiFi.localIP())) {
- Serial.println("MDNS responder started");
- }
- server.on("/home", [](){
- //pingdistance = sonar.ping_cm();
- server.send(200, "text/html", basepage());
- });
- server.on("/", [](){
- //pingdistance = sonar.ping_cm();
- server.send(200, "text/html", basepage());
- });
- server.on("/prtg", [](){
- server.send(200, "text/html", prtgpage());
- rssi = getRSSI(ssid);
- });
- server.on("/operatedoor", [](){
- doorflag = true;
- server.send(200, "text/html", basepage());
- });
- server.on("/gatherdata", [](){
- GATHERDATAFORCE = true;
- server.send(200, "text/html", basepage());
- });
- server.on("/ac", [](){
- irsend.sendNEC(279939191, 32);
- server.send(200, "text/html", basepage());
- });
- server.on("/tempup", [](){
- irsend.sendNEC(279949391, 32);
- server.send(200, "text/html", basepage());
- });
- server.on("/tempdown", [](){
- irsend.sendNEC(279933071, 32);
- server.send(200, "text/html", basepage());
- });
- server.begin();
- Serial.println("HTTP server started");
- // Hostname defaults to esp8266-[ChipID]
- ArduinoOTA.setHostname(host);
- // No authentication by default
- // ArduinoOTA.setPassword((const char *)"123");
- ArduinoOTA.onStart([]() {
- Serial.println("Start");
- });
- ArduinoOTA.onEnd([]() {
- Serial.println("\nEnd");
- });
- ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
- Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
- });
- ArduinoOTA.onError([](ota_error_t error) {
- Serial.printf("Error[%u]: ", error);
- if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
- else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
- else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
- else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
- else if (error == OTA_END_ERROR) Serial.println("End Failed");
- });
- ArduinoOTA.begin();
- Serial.println("Ready");
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- //pingdistance = sonar.ping_cm();
- }
- void loop(){
- GatherData();
- processTCP();
- processSyslog();
- Alarm.delay(0);
- server.handleClient();
- //processMQTT();
- readlight();
- //readpressure();
- setlastboot();
- ArduinoOTA.handle();
- //blinkLED();
- operatedoor();
- readDigitalinputs();
- }
- #define inputarrlen 1
- int Dinputarr[inputarrlen] = {DoorSensor};
- bool prevDigitalInput[inputarrlen] = {1};
- unsigned long opened[inputarrlen] = {0};
- void readDigitalinputs(){
- int securedset = 0;
- #define inputarrlen 1
- const int Dinputarr[inputarrlen] = {DoorSensor};
- static bool prevDigitalInput[inputarrlen] = {1};
- static unsigned long opened[inputarrlen] = {0};
- static unsigned long temptime = millis();
- static unsigned long securesettimer = millis();
- static unsigned long dooropenedtoolongtimer [inputarrlen]= {millis()};
- if (millis() - temptime > 100UL){
- temptime = millis();
- for(int x=0;x<inputarrlen;x++){//read the onboard
- bool currentDigitalInput = digitalRead(Dinputarr[x]);
- securedset += currentDigitalInput;
- if (prevDigitalInput[x]!=currentDigitalInput) {
- cmd3 = "Input ";
- //strcpy_P(buffer2, (char*)pgm_read_word(&(string_table[x]))); // Necessary casts and dereferencing, just copy.
- cmd3 += Dinputarr[x];
- cmd3 += "-";
- //cmd3 += String(buffer2);
- cmd3 += " changed to ";
- if (currentDigitalInput) {
- cmd3 += "Open";
- opened[x] = millis();
- }
- else {
- cmd3 += "Closed. ";
- cmd3 += "Open for: ";
- cmd3 += (millis() - opened[x])/1000/60;
- cmd3 += "m ";
- cmd3 += (millis() - opened[x])/1000%60;
- cmd3 += "s";
- }
- prevDigitalInput[x]=currentDigitalInput;
- if (millis() < 8000) return;
- syslog(cmd3);
- }
- else if ((millis() - opened[x])/1000 > 600 && millis() - dooropenedtoolongtimer[x] >30000 && currentDigitalInput){
- dooropenedtoolongtimer[x] = millis();
- //strcpy_P(buffer2, (char*)pgm_read_word(&(string_table[x]))); // Necessary casts and dereferencing, just copy.
- cmd3 = Dinputarr[x];
- //cmd3 += "-";
- //cmd3 += String(buffer2);
- cmd3 += " opened too long Opened for ";
- cmd3 += (millis() - opened[x])/1000;
- cmd3 += " seconds ";
- Serial.println(cmd3);
- }
- }
- if (millis() - securesettimer >300000){
- securesettimer = millis();
- cmd3 = "Secure set: ";
- cmd3 += securedset;
- syslog(cmd3);
- }
- }
- }
- void blinkled2(){
- static unsigned long blinker = millis();
- if (millis()- blinker >1000){
- blinker = millis();
- digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
- }
- }
- void blinkLED() {
- static int brightness = 0; // how bright the LED is
- static int ledstage =0;
- static unsigned long ledblinker = millis();
- if (ledblinker + 24 <= millis()) {
- if (ledstage == 0){ //ascent1
- brightness = brightness + 30;
- if (brightness > 180 )ledstage++;
- }
- else if (ledstage == 1){ //decent1
- brightness = brightness - 20;
- if (brightness <21 )ledstage++;
- }
- else if (ledstage == 2){ //ascent2
- brightness = brightness + 30;
- if (brightness > 215 )ledstage++;
- }
- else {//decent2
- brightness = brightness - 5;
- if (brightness < 5 )ledstage=0;
- }
- if (ledblinker + 250 <= millis()) {
- digitalWrite(BUILTIN_LED, brightness);
- ledblinker = millis();
- }
- }
- }
- void setlastboot(){
- static unsigned long initialntptimer = millis();
- if (timesetviantp && !lastbootset){
- lastbootset = true;
- lastboot = calculateDayOfYear(day(),month(),year());
- Serial.println("Last boot set!");
- Serial.print("Last boot day is: ");
- Serial.println(lastboot);
- lb = (year());
- lb += "-";
- if(month() <=9) lb +="0";
- lb += (month());
- lb+= "-";
- if(day() <=9) lb +="0";
- lb += (day());
- lb+= " ";
- if(hour() <=9) lb +="0";
- lb += (hour());
- lb+= ":";
- if(minute() <=9) lb +="0";
- lb += (minute());
- lb+= ":";
- if(second() <=9) lb +="0";
- lb += (second());
- Alarm.alarmRepeat(23, 00, 0, ElevenAlarm); //daily at 3am we create the sunrise and set alarms
- syslog("lastboot set");
- if (DEBUGLEVEL>=3) Serial.print("Wifi setup in ");
- if (DEBUGLEVEL>=3) Serial.print(millis());
- if (DEBUGLEVEL>=3) Serial.println(" ms");
- }
- else if (!timesetviantp && millis() - initialntptimer > 10000){
- initialntptimer = millis();
- ntp();
- }
- }
- void operatedoor(){
- if(doorflag){
- digitalWrite(DoorRelay, HIGH);
- delay(1000);
- digitalWrite(DoorRelay, LOW);
- doorflag = false;
- syslog("Operated Door");
- }
- }
- void readlight(){
- static unsigned long readlighttimer = millis();
- if (millis() - readlighttimer > 1000 ){
- readlighttimer = millis();
- LightReading = analogRead(A0);
- }
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- // Switch on the LED if an 1 was received as first character
- if ((char)payload[0] == '1') {
- digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
- // but actually the LED is on; this is because
- // it is acive low on the ESP-01)
- } else {
- digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
- }
- }
- void mqttreconnect() {
- static unsigned long recontimer = millis();
- // Loop until we're reconnected
- if (!mqttclient.connected() && millis() - recontimer > 5000) {
- recontimer = millis();
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (mqttclient.connect("ESP8266Client")) {
- Serial.println("connected");
- // Once connected, publish an announcement...
- mqttclient.publish("outTopic", "hello world");
- // ... and resubscribe
- mqttclient.subscribe("inTopic");
- } else {
- Serial.print("failed, rc=");
- Serial.print(mqttclient.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- }
- }
- }
- void processMQTT(){
- static unsigned long recontimer = millis();
- // Loop until we're reconnected
- if (!mqttclient.connected() && millis() - recontimer > 5000) {
- recontimer = millis();
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (mqttclient.connect("ESP8266Client")) {
- Serial.println("connected");
- // Once connected, publish an announcement...
- mqttclient.publish("outTopic", "hello world");
- // ... and resubscribe
- mqttclient.subscribe("inTopic");
- } else {
- Serial.print("failed, rc=");
- Serial.print(mqttclient.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- }
- }
- else {
- mqttclient.loop();
- unsigned long now = millis();
- if (now - lastMsg > 2000) {
- lastMsg = now;
- ++value;
- // snprintf (msg, 75, "temp %4.2F", dstemp1);
- // sprintf (msg, "temp %f", dstemp1);
- dtostrf(dstemp1,5,2,msg);
- Serial.print("Publish message: ");
- Serial.println(msg);
- mqttclient.publish("garagetemp", msg);
- }}
- }
- String prtgpage(){
- String thePage = "<prtg>";
- thePage += "<result><channel>uptime</channel><value>";
- thePage += uptime;
- thePage += "</value><FLOAT>1</FLOAT><CustomUnit>d</CustomUnit></result>";
- if (rssi<0){
- thePage += "<result><channel>rssi</channel><value>";
- thePage += rssi;
- thePage += "</value><FLOAT>1</FLOAT><CustomUnit>db</CustomUnit></result>";
- }
- thePage += "<result><channel>pingdistance</channel><value>";
- thePage += pingdistance;
- thePage += "</value><FLOAT>1</FLOAT><CustomUnit>cm</CustomUnit></result>";
- thePage += "<result><channel>raw a0</channel><value>";
- thePage +=1023- LightReading;
- thePage += "</value><FLOAT>1</FLOAT><CustomUnit>A0</CustomUnit></result>";
- thePage += "<result><channel>DoorStatus</channel><value>";
- thePage += digitalRead(DoorSensor);
- thePage += "</value><FLOAT>1</FLOAT></result>";
- thePage += "</prtg>";
- return thePage;
- }
- String basepage(){
- String thePage = "<h1>The ";
- thePage += host;
- if(TESTDATA) thePage += "test";
- thePage += " ESP</h1>";
- thePage += "<p><a href=\"operatedoor\"><button>Operate Door</button></a> ";
- thePage += "<br><br>";
- thePage += "<a href=\"ac\"><button>AC</button></a> ";
- thePage += "<a href=\"tempup\"><button>tempup</button></a> ";
- thePage += "<a href=\"tempdown\"><button>tempdown</button></a> ";
- thePage += "<br><br>";
- thePage += "<a href=\"gatherdata\"><button>Gatherdata</button></a> ";
- thePage += "<a href=\"ntp\"><button>NTP</button></a> ";
- thePage += "<a href=\"home\"><button>Update page</button></a> ";
- thePage +="</p>";
- thePage += "<br>";
- thePage += "The garage door is ";
- if (!digitalRead(DoorSensor)) thePage += "closed";
- else thePage += "open";
- thePage += ".<br>";
- thePage += "The light sensor reads ";
- thePage += 1023- LightReading;
- thePage += ".<br>";
- thePage += "The A0 Raw ";
- thePage += LightReading;
- thePage += ".<br>";
- thePage += "The LED is ";
- if (digitalRead(BUILTIN_LED))thePage += "off";
- else thePage += "on";
- thePage += ".<br>";
- thePage += "The distance is ";
- thePage += pingdistance;
- thePage += ".<br>";
- thePage += "The uptime is ";
- thePage += uptime;
- thePage += " days.<br>";
- thePage += "<br><br>";
- thePage +="This Page was created at: ";
- if(hour() <=9) thePage +="0";
- thePage +=hour();
- thePage +=":";
- if(minute() <=9) thePage +="0";
- thePage +=minute();
- thePage +=":";
- if(second() <=9) thePage +="0";
- thePage += second();
- thePage += ".<br>";
- thePage +="Last boot: ";
- thePage +=lb;
- thePage += ".<br>";
- thePage += "Build Date: ";
- thePage +=(__DATE__);
- thePage += ": ";
- thePage +=(__TIME__);
- thePage += "<br>";
- thePage += "Build file: ";
- thePage +=(__FILE__);
- return thePage;
- }
- /*
- void servepage(){
- // Check if a client has connected
- WiFiClient client = server2.available();
- if (!client) {
- return;
- }
- // Wait until the client sends some data
- Serial.println("new client");
- while(!client.available()){
- delay(1);
- }
- // Read the first line of the request
- String request = client.readStringUntil('\r');
- Serial.println(request);
- client.flush();
- // Match the request
- int value = LOW;
- if (request.indexOf("/LED1") != -1) {
- digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
- value = LOW;
- }
- if (request.indexOf("/LED=OFF") != -1) {
- digitalWrite(BUILTIN_LED, HIGH);
- value = HIGH;
- }
- // Set BUILTIN_LED according to the request
- //digitalWrite(BUILTIN_LED, value);
- // Return the response
- client.println("HTTP/1.1 200 OK");
- client.println("Content-Type: text/html");
- client.println("Connection: close"); // the connection will be closed after completion of the response
- client.println("Refresh: 5"); // refresh the page automatically every 5 sec
- client.println();
- client.println("<!DOCTYPE HTML>");
- client.println("<html>");
- client.print("Led pin is now: ");
- if(!digitalRead(BUILTIN_LED)) {
- client.print("On");
- } else {
- client.print("Off");
- }
- client.println("<br><br>");
- client.println("Click <a href=\"/LED1\">here</a> toggle the LED on pin 2 ON<br>");
- client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 2 OFF<br>");
- client.println("<br><br>");
- client.print("The time is: ");
- if(hour() <=9) client.print("0");
- client.print(hour());
- client.print(":");
- if(minute() <=9) client.print("0");
- client.print(minute());
- client.print(":");
- if(second() <=9) client.print("0");
- client.println(second());
- client.println("</html>");
- delay(1);
- Serial.println("Client disonnected");
- Serial.println("");
- }
- */
- void GatherData(){
- if (millis() - gatherdatatimer > DATA_SAMPLE_INTERVAL || GATHERDATAFORCE){//once every five minutes update the temp
- gatherdatatimer = millis();
- GATHERDATAFORCE = false;
- Serial.print("Wifi status: ");
- Serial.println(WiFi.status());
- // pingdistance = sonar.ping_cm();
- if (runDHT) {getDHTtemperature(); // read sensor
- Serial.print("DHT Temp: ");
- Serial.println(String(temp_f));
- Serial.print("DHT humidity: ");
- Serial.println(String(humidity));
- if (!isnan(temp_f)){
- if(TESTDATA) cmd3 = "test";
- else cmd3 = host;
- cmd3 += "temp2,";
- cmd3 += (String(temp_f));
- //tcpqueue.push (cmd3);
- if(TESTDATA) cmd3 = "test";
- else cmd3 = host;
- cmd3 += "hum1,";
- cmd3 += (String(humidity));
- //tcpqueue.push (cmd3);
- if (DEBUGLEVEL>=5)syslog(cmd3);
- }
- }
- if (runDSTemp){
- dstemp1 = GetDsTemp();
- if (dstemp1 != 0){
- if(TESTDATA) cmd3 = "test";
- else cmd3 = host;
- cmd3 += "temp1,";
- cmd3 += dstemp1;
- //tcpqueue.push (cmd3);
- if (DEBUGLEVEL>=5)syslog(cmd3);
- }
- else Serial.println("DS temp failed");
- if (DEBUGLEVEL>=5)syslog(cmd3);
- }
- int dayofyear = calculateDayOfYear(day(),month(),year()); //current day of year
- uptime = dayofyear - lastboot;
- if(TESTDATA) cmd3 = "test";
- else cmd3 = host;
- cmd3 += ("uptime,");
- cmd3 += (uptime);
- //tcpqueue.push(cmd3);
- if (DEBUGLEVEL>=5) syslog(cmd3);
- //rssi = getRSSI(ssid);
- if(TESTDATA) cmd3 = "test";
- else cmd3 = host;
- cmd3 += "wifi,";
- cmd3 += rssi;
- //tcpqueue.push (cmd3);
- if (DEBUGLEVEL>=5) syslog(cmd3);
- SendPressureData = true;
- }
- }
- int calculateDayOfYear(int day, int month, int year) {
- // Given a day, month, and year (4 digit), returns
- // the day of year. Errors return 999.
- int daysInMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
- // Verify we got a 4-digit year
- if (year < 1000) {
- return 999;
- }
- // Check if it is a leap year, this is confusing business
- // See: https://support.microsoft.com/en-us/kb/214019
- if (year%4 == 0) {
- if (year%100 != 0) {
- daysInMonth[1] = 29;
- }
- else {
- if (year%400 == 0) {
- daysInMonth[1] = 29;
- }
- }
- }
- // Make sure we are on a valid day of the month
- if (day < 1)
- {
- return 999;
- } else if (day > daysInMonth[month-1]) {
- return 999;
- }
- int doy = 0;
- for (int i = 0; i < month - 1; i++) {
- doy += daysInMonth[i];
- }
- doy += day;
- return doy;
- }
- void printAddress(DeviceAddress deviceAddress){// function to print a device address
- for (uint8_t i = 0; i < 8; i++) {
- if (deviceAddress[i] < 16) Serial.print("0");
- Serial.print(deviceAddress[i], HEX);
- }
- }
- String ipToString(IPAddress ip){
- String s="";
- for (int i=0; i<4; i++)
- s += i ? "." + String(ip[i]) : String(ip[i]);
- return s;
- //- See more at: http://www.esp8266.com/viewtopic.php?p=25466#sthash.YLEOLQu6.dpuf
- }
- void processTCP(){
- String sensorname;
- String sensordata;
- if (!tcpqueue.isEmpty() && checkconnection()){
- static unsigned long lasttcpsent = millis();
- if(millis()-lasttcpsent < 500) return;
- lasttcpsent = millis();
- cmd3 = tcpqueue.pop ();
- int commaIndex = cmd3.indexOf(',');
- sensorname = cmd3.substring(0, commaIndex);
- sensordata = cmd3.substring(commaIndex+1);
- cmd3 = "GET /";
- cmd3 += sensorname;
- cmd3 += F("?value=");
- cmd3 += sensordata;
- cmd3 += F(" HTTP/1.1\r\n");
- cmd3 += F("Host: server:5050\r\n\r\n");
- WiFiClient client;
- const int httpPort = 5050;
- if (!client.connect(dataserver, httpPort)) {
- Serial.println("connection failed");
- return;
- }
- client.print(cmd3);
- if (DEBUGLEVEL>=5)Serial.println(cmd3);
- delay(100);
- while(client.available()){
- cmd3 = client.readStringUntil('\r');
- if (DEBUGLEVEL>=7) Serial.println(cmd3);
- }
- }
- }
- void processSyslog(){
- if (!syslogqueue.isEmpty()){
- static unsigned long lastsyslogsent = millis();
- if(millis()-lastsyslogsent < 100) return;
- lastsyslogsent = millis();
- String Somedata = syslogqueue.pop();
- unsigned int msg_length = Somedata.length();
- byte* p = (byte*)malloc(msg_length);
- memcpy(p, Somedata.c_str(), msg_length);
- udp.beginPacket(syslogServer, 514);
- //udp.write(Somedata.c_str(), msg_length);
- udp.write(p, msg_length);
- udp.endPacket();
- free(p);
- }
- }
- int32_t getRSSI(const char* target_ssid) {
- byte available_networks = WiFi.scanNetworks();
- for (int network = 0; network < available_networks; network++) {
- if (strcmp(WiFi.SSID(network).c_str(), target_ssid) == 0) {
- return WiFi.RSSI(network);
- }
- }
- return 0;
- }
- float GetDsTemp() {
- float temp;DS18B20.requestTemperatures();
- temp = DS18B20.getTempCByIndex(0);
- if(DEBUGLEVEL>+5)Serial.print("Raw temp data ");
- if(DEBUGLEVEL>+5)Serial.println(temp);
- if (temp == 85.0 || temp == (-127.0)) return 0;
- temp = temp *1.8 +32;
- return temp;
- }
- void getDHTtemperature() {
- // Wait at least 2 seconds seconds between measurements.
- // if the difference between the current time and last time you read
- // the sensor is bigger than the interval you set, read the sensor
- // Works better than delay for things happening elsewhere also
- const long interval = 2000; // interval at which to read sensor
- static unsigned long previousMillis = 0; // will store last temp was read
- unsigned long currentMillis = millis();
- if(currentMillis - previousMillis >= interval) {
- // save the last time you read the sensor
- previousMillis = currentMillis;
- // Reading temperature for humidity takes about 250 milliseconds!
- // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
- humidity = dht.readHumidity(); // Read humidity (percent)
- temp_f = dht.readTemperature(true); // Read temperature as Fahrenheit
- // Check if any reads failed and exit early (to try again).
- if (isnan(humidity) || isnan(temp_f)) {
- Serial.println("Failed to read from DHT sensor!");
- return;
- }
- }
- }
- /*-------- NTP code ----------*/
- const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
- byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
- void ntp(){
- syslog("ntp begin sync");
- if (checkconnection()) setSyncProvider(getNtpTime);
- syslog("ntp finished sync");
- }
- time_t getNtpTime(){
- while (udp.parsePacket() > 0) ; // discard any previously received packets
- if (DEBUGLEVEL >=7)Serial.println("Transmit NTP Request");
- sendNTPpacket(timeServer);
- uint32_t beginWait = millis();
- while (millis() - beginWait < 1500) {
- int size = udp.parsePacket();
- if (size >= NTP_PACKET_SIZE) {
- if (DEBUGLEVEL >=7)Serial.println("Receive NTP Response");
- udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
- unsigned long secsSince1900;
- // convert four bytes starting at location 40 to a long integer
- secsSince1900 = (unsigned long)packetBuffer[40] << 24;
- secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
- secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
- secsSince1900 |= (unsigned long)packetBuffer[43];
- //setSyncProvider((getExternalTime)secsSince1900 - 2208988800UL + EST * SECS_PER_HOUR);
- timesetviantp = true;
- if (IsDST) return secsSince1900 - 2208988800UL + EDT * SECS_PER_HOUR;
- else return secsSince1900 - 2208988800UL + EST * SECS_PER_HOUR;
- }
- }
- Serial.println("No NTP Response :-(");
- return 0; // return 0 if unable to get the time
- }
- bool IsDST() {
- // IsDST() returns true if DST, false otherwise
- // variables: mo - month [1-12], dy - date [1-31], dw - day of the week [0-Sunday, 1-Monday etc.]
- if (month() < 3 || month() > 11) { return false; } // January, February, and December are out.
- if (month() > 3 && month() < 11) { return true; } // April to October are in DST
- int lastSunday = day() - weekday();
- if (month() == 3) { return lastSunday >= 7; } // In March, we are DST if the previous Sunday was on or after the 8th.
- return lastSunday < 0; // In November we must be before the first Sunday to be DST - the previous Sunday must be before the 1st.
- }
- void sendNTPpacket(IPAddress &address){// send an NTP request to the time server at the given address
- // set all bytes in the buffer to 0
- memset(packetBuffer, 0, NTP_PACKET_SIZE);
- // Initialize values needed to form NTP request
- // (see URL above for details on the packets)
- packetBuffer[0] = 0b11100011; // LI, Version, Mode
- packetBuffer[1] = 0; // Stratum, or type of clock
- packetBuffer[2] = 6; // Polling Interval
- packetBuffer[3] = 0xEC; // Peer Clock Precision
- // 8 bytes of zero for Root Delay & Root Dispersion
- packetBuffer[12] = 49;
- packetBuffer[13] = 0x4E;
- packetBuffer[14] = 49;
- packetBuffer[15] = 52;
- // all NTP fields have been given values, now
- // you can send a packet requesting a timestamp:
- udp.beginPacket(address, 123); //NTP requests are to port 123
- udp.write(packetBuffer, NTP_PACKET_SIZE);
- udp.endPacket();
- }
- void syslog(String x){
- static int syslogindex;
- syslogindex++;
- String Somedata = "<166>"; //LOCAL4.INFO
- Somedata += syslogindex;
- if (hour() <=9) Somedata += " 0";
- else Somedata += " ";
- Somedata += String(hour());
- Somedata += ":";
- if (minute() <=9) Somedata += "0";
- Somedata += String(minute());
- Somedata += ":";
- if (second() <=9) Somedata += "0";
- Somedata += String(second());
- Somedata += " ";
- Somedata += host;
- if(TESTDATA) Somedata += "Test ";
- else Somedata += " ";
- Somedata += x;
- if (DEBUGLEVEL>=5) Serial.print(F("syslog: "));
- if (DEBUGLEVEL>=5) Serial.println(Somedata);
- if (syslogqueue.count()<20)syslogqueue.push(Somedata);
- else if (DEBUGLEVEL>=6) Serial.println("Syslog queue is full");
- }
- bool checkconnection(){
- static int badcounter = 0;
- if (WiFi.status() == WL_CONNECTED)return true;
- if(Ping.ping(timeServer)){
- if (DEBUGLEVEL>=3) Serial.println("Check conn - ping success");
- return true;
- }
- else if (DEBUGLEVEL>=3) Serial.println("Check conn - ping failed");
- if (WiFi.status() != WL_CONNECTED) {
- if (DEBUGLEVEL>=3) Serial.print("Wifi Status did not equal WL_CONNECTED Status=");
- if (DEBUGLEVEL>=3) Serial.println(WiFi.status());
- WiFi.config(ip, dns, gateway, subnet);
- WiFi.begin(ssid, pass);
- unsigned long connecttime = millis();
- /* while (WiFi.status() != WL_CONNECTED && millis() - connecttime <20000) {
- delay(500);
- if (DEBUGLEVEL>=3) Serial.print("Wifi Status=");
- if (DEBUGLEVEL>=3) Serial.println(WiFi.status());
- } */
- Serial.println(".");
- if (WiFi.status() == WL_CONNECTED) return true;
- }
- else {
- badcounter++;
- if (badcounter > 10) ESP.reset();
- return false;
- }
- }
- void ElevenAlarm(){
- if (digitalRead(DoorSensor)) {
- sendEmail("The Garage Door is open","");
- }
- if (LightReading< 500){
- sendEmail("The Garage Light is on","");
- }
- syslog("elevenalarm done");
- }
- //email
- byte sendEmail(String mailSubject, String mailMessage){
- #define MAIL_FROM "garage@xxxx.net"
- #define MAIL_TO "garage@xxxx.net"
- #define MAIL_USER "xxxx"
- #define MAIL_PASS "xxxx"
- char mailserver[] = "192.168.99.7";
- int port = 25;
- byte thisByte = 0;
- byte respCode;
- if(client.connect(mailserver,port) == 1) {
- Serial.println(F("connected"));
- } else {
- Serial.println(F("connection failed"));
- return 0;
- }
- if(!eRcv()) return 0;
- Serial.println(F("Sending hello"));
- // replace 1.2.3.4 with your Arduino's ip
- client.println("EHLO 1.2.3.4");
- if(!eRcv()) return 0;
- Serial.println(F("Sending auth login"));
- client.println("auth login");
- if(!eRcv()) return 0;
- Serial.println(F("Sending User"));
- // Change to your base64 encoded user
- client.println(MAIL_USER);
- if(!eRcv()) return 0;
- Serial.println(F("Sending Password"));
- // change to your base64 encoded password
- client.println(MAIL_PASS);
- if(!eRcv()) return 0;
- // change to your email address (sender)
- Serial.println(F("Sending From"));
- client.print(F("MAIL From: "));
- client.println(F(MAIL_FROM));
- if(!eRcv()) return 0;
- // change to recipient address
- Serial.println(F("Sending To"));
- client.print(F("RCPT To: "));
- client.println(F(MAIL_TO));
- if(!eRcv()) return 0;
- Serial.println(F("Sending DATA"));
- client.println("DATA");
- if(!eRcv()) return 0;
- Serial.println(F("Sending email"));
- // change to recipient address
- //client.println("To: You <me@theawesomes.net>");
- client.print(F("To: "));
- client.println(F(MAIL_TO));
- client.print("Subject: ");
- client.print(mailSubject);
- client.println("\r\n");
- // change to your address
- //client.println("From: Me <me@theawesomes.net>");
- client.print(F("From: "));
- client.println(F(MAIL_FROM));
- client.print("Subject: ");
- client.print(mailSubject);
- client.println("\r\n");
- client.println(mailMessage);
- client.println(".");
- if(!eRcv()) return 0;
- Serial.println(F("Sending QUIT"));
- client.println("QUIT");
- if(!eRcv()) return 0;
- client.stop();
- Serial.println(F("disconnected"));
- return 1;
- }
- byte eRcv(){
- byte respCode;
- byte thisByte;
- int loopCount = 0;
- while(!client.available()) {
- delay(1);
- loopCount++;
- // if nothing received for 10 seconds, timeout
- if(loopCount > 10000) {
- client.stop();
- Serial.println(F("\r\nTimeout"));
- return 0;
- }
- }
- respCode = client.peek();
- while(client.available()) {
- thisByte = client.read();
- Serial.write(thisByte);
- }
- if(respCode >= '4') {
- efail();
- return 0;
- }
- return 1;
- }
- void efail(){
- byte thisByte = 0;
- int loopCount = 0;
- client.println(F("QUIT"));
- while(!client.available()) {
- delay(1);
- loopCount++;
- // if nothing received for 10 seconds, timeout
- if(loopCount > 10000) {
- client.stop();
- Serial.println(F("\r\nTimeout"));
- return;
- }
- }
- while(client.available()) {
- thisByte = client.read();
- Serial.write(thisByte);
- }
- client.stop();
- Serial.println(F("disconnected"));
- }
Add Comment
Please, Sign In to add comment