{{ /* To upload through terminal you can use: curl -F "image=@firmware.bin" <IP>/update */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266HTTPUpdateServer.h> #include <WiFiUdp.h> #include <Time.h> //#include <ESP8266mDNS.h> #include <PubSubClient.h> #include "DHT.h" /*--------------------------------------------------*/ IPAddress staticIP(192, 168, 0, 160); IPAddress gateway(192, 168, 0, 100); IPAddress subnet(255, 255, 255, 0); const char* ssid = "xxx"; const char* password = "xxx"; const char* update_path = "/update"; const char* update_username = "xxx"; const char* update_password = "xxx"; //const char* host = "esp8266-webupdate"; /*--------------------------------------------------*/ WiFiClient wifiClient; ESP8266WebServer httpServer(80); ESP8266HTTPUpdateServer httpUpdater; /*--------------------------------------------------*/ const char* ntpServerName = "time.nist.gov"; const unsigned int ntp_port = 2390; // local port to listen for UDP packets const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets WiFiUDP ntpudp; // A UDP instance to let us send and receive packets over UDP IPAddress timeServerIP; // NTP server address time_t seconds = 0; // send an NTP request to the time server at the given address void sendNTPpacket(void) { // 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; //get a random server from the pool WiFi.hostByName(ntpServerName, timeServerIP); // all NTP fields have been given values, now // you can send a packet requesting a timestamp: ntpudp.beginPacket(timeServerIP, 123); //NTP requests are to port 123 ntpudp.write(packetBuffer, NTP_PACKET_SIZE); ntpudp.endPacket(); } void receiveNTPpacket(void) { int cb = ntpudp.parsePacket(); if (!cb) { /* no packet yet */ } else { ntpudp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer //the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): unsigned long secsSince1900 = highWord << 16 | lowWord; // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: const unsigned long seventyYears = 2208988800UL; // subtract seventy years: seconds = secsSince1900 - seventyYears; // setTime((time_t)epoch); } } /*--------------------------------------------------*/ const char* mqtt_client_name = "ESP-Outdoor"; const char* mqtt_server_name = "192.168.0.150"; const char* mqtt_topic_temperature = "balkon/temp"; const char* mqtt_topic_humidity = "balkon/feuchte"; // forward decl. void mqtt_callback(char* topic, byte* payload, unsigned int length); PubSubClient mqtt_client(mqtt_server_name, 1883, mqtt_callback, wifiClient); void mqtt_callback(char* topic, byte* payload, unsigned int length) { // handle message arrived } void mqtt_connect(void) { if (mqtt_client.connect(mqtt_client_name)) { mqtt_client.publish("outTopic", "Hello from ESP"); } } /*--------------------------------------------------*/ #define DHTPIN 2 #define DHTTYPE DHT22 // DHT11, DHT21 (AM2301), DHT22 (AM2302) float dht_temperature = 0, dht_humidity = 0; DHT dht(DHTPIN, DHTTYPE); void dht_read(bool publish) { dht_temperature = dht.readTemperature(); dht_humidity = dht.readHumidity(); if (publish && !(isnan(dht_temperature)) && !(isnan(dht_humidity))) { String tmp = String(dht_temperature); mqtt_client.publish(mqtt_topic_temperature, (char *)tmp.c_str()); tmp = String(dht_humidity); mqtt_client.publish(mqtt_topic_humidity, (char *)tmp.c_str()); } } /*--------------------------------------------------*/ String webSite,javaScript; void buildJavascript() { javaScript = "<SCRIPT>\n"; javaScript += "var xmlHttp=createXmlHttpObject();\n"; javaScript += "function createXmlHttpObject(){\n"; javaScript += " if(window.XMLHttpRequest){\n"; javaScript += " xmlHttp=new XMLHttpRequest();\n"; javaScript += " }else{\n"; javaScript += " xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n"; javaScript += " }\n"; javaScript += " return xmlHttp;\n"; javaScript += "}\n"; javaScript += "function process(){\n"; javaScript += " if(xmlHttp.readyState==0 || xmlHttp.readyState==4){\n"; javaScript += " xmlHttp.open('PUT','xml',true);\n"; javaScript += " xmlHttp.onreadystatechange=handleServerResponse;\n"; // no brackets????? javaScript += " xmlHttp.send(null);\n"; javaScript += " }\n"; javaScript += " setTimeout('process()',10000);\n"; javaScript += "}\n"; javaScript += "function handleServerResponse(){\n"; javaScript += " if(xmlHttp.readyState==4 && xmlHttp.status==200){\n"; javaScript += " xmlResponse=xmlHttp.responseXML;\n"; //javaScript += " xmldoc = xmlResponse.getElementsByTagName('response');\n"; //javaScript += " message = xmldoc[0].firstChild.nodeValue;\n"; //javaScript += " document.getElementById('runtime').innerHTML=message;\n"; javaScript += " xmldoc = xmlResponse.getElementsByTagName('temp');\n"; javaScript += " message = xmldoc[0].firstChild.nodeValue;\n"; javaScript += " document.getElementById('temp').innerHTML=message;\n"; javaScript += " xmldoc = xmlResponse.getElementsByTagName('hum');\n"; javaScript += " message = xmldoc[0].firstChild.nodeValue;\n"; javaScript += " document.getElementById('hum').innerHTML=message;\n"; javaScript += " }\n"; javaScript += "}\n"; javaScript += "</SCRIPT>\n"; } void buildWebsite() { buildJavascript(); webSite = "<!DOCTYPE HTML>\n"; webSite += javaScript; webSite += "<BODY onload='process()'>\n"; webSite += "<center><BR>Website for DHT22 using AJAX<BR>\n"; //webSite += "<A id='runtime'></A>\n"; webSite += "Temperature: <A id='temp'>" + (String)dht_temperature + "</A>°C\n"; webSite += "Humidity: <A id='hum'>" + (String)dht_humidity + "</A>%\n"; webSite += "</BODY>\n"; webSite += "</HTML>\n"; } void handleRoot(void) { buildWebsite(); httpServer.send(200,"text/html", webSite); } /*--------------------------------------------------*/ String TempStr, XML; String dht_response(void) { TempStr = "<temp>" + (String)dht_temperature + "</temp>"; //TempStr += "<hum>" + (String)dht_humidity + "</hum>"; TempStr += "<hum>" + (String)seconds + "</hum>"; return TempStr; } void buildXML(void) { XML = "<?xml version='1.0'?>"; XML += "<response>"; XML += dht_response(); XML += "</response>"; } void handleXML(void) { buildXML(); httpServer.send(200,"text/xml", XML); } /*--------------------------------------------------*/ void setup(void) { Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); WiFi.mode(WIFI_AP_STA); WiFi.begin(ssid, password); WiFi.config(staticIP, gateway, subnet); while (WiFi.waitForConnectResult() != WL_CONNECTED) { WiFi.begin(ssid, password); Serial.println("WiFi failed, retrying."); } // MDNS.begin(host); httpUpdater.setup(&httpServer, update_path, update_username, update_password); httpServer.on("/", handleRoot); httpServer.on("/xml", handleXML); httpServer.begin(); dht.begin(); dht_read(false); ntpudp.begin(ntp_port); sendNTPpacket(); // MDNS.addService("http", "tcp", 80); // Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and password '%s'\n", // host, update_path, update_username, update_password); } /*--------------------------------------------------*/ void loop(void) { if (!mqtt_client.connected()) { mqtt_connect(); } mqtt_client.loop(); httpServer.handleClient(); { static long last = 0; long now = millis(); if (now - last > 10000) { last = now; dht_read(true); receiveNTPpacket(); } } } }}
