From 50939fa50dcf33023e3e3d2a15f1a12567ccb62b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phan=20Bernard?= <stephan.bernard@inrae.fr> Date: Wed, 9 Nov 2022 09:02:41 +0100 Subject: [PATCH] =?UTF-8?q?Version=20utilis=C3=A9e=20par=20le=20n=C5=93ud?= =?UTF-8?q?=20capteur=20=C3=A0=20partir=20du=208=20novembre=202022?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Co2Huzzah/Co2Huzzah.ino | 174 ++++++++++++++---------------- Co2Huzzah/data/setupDateTime.html | 2 +- Co2Huzzah/data/setupWifi.html | 24 ++++- 3 files changed, 102 insertions(+), 98 deletions(-) diff --git a/Co2Huzzah/Co2Huzzah.ino b/Co2Huzzah/Co2Huzzah.ino index 67ce917..75870e9 100644 --- a/Co2Huzzah/Co2Huzzah.ino +++ b/Co2Huzzah/Co2Huzzah.ino @@ -30,6 +30,7 @@ #define DEFAULT_SSID "irstea_invite" #define DEFAULT_HOST "CO2opain" #define DEFAULT_AP_PASSWD "CO2chon2" +#define DEFAULT_MQTT_BROKER "10.63.65.95" /* ------------------------------------------------- */ /* Keep some usual Strings static and shared */ @@ -63,7 +64,7 @@ static int ntpUpdateInterval = NTP_UPDATE_INTERVAL; static bool writeData = false; static String ntpServerName = "fr.pool.ntp.org"; -static String timezone = "Europe/Paris"; +static String timezone = "Europe/Brussels"; const char *timeformat = "Y-m-d~TH:i:s;T"; /* ---------- filesystem ---------- */ @@ -111,11 +112,11 @@ static char cbuf[BUF_SIZE]; static bool LED_STATUS = false; /* ---------- MQTT ------------------------*/ -const char *mqtt_broker = "10.63.65.95"; +static char mqtt_broker[16]; const char *topic_co2 = "N4/ESP8266/SDC30/CO2"; const char *topic_temp = "N4/ESP8266/SDC30/airTemperature"; const char *topic_hum = "N4/ESP8266/SDC30/airHumidity"; -const int mqtt_port = 1883; +static int mqtt_port = 1883; const char *client_id = "CO2Pain"; WiFiClient espClient; @@ -125,31 +126,18 @@ PubSubClient client(espClient); /*----------- MQTT ---------- */ -void publishMQTT() -{ - for (int i = 0; i < 5; i++) - { - { - if (!client.connected()) - { - client.connect(client_id); - delay(2000); - } - else - { - break; - } - } - char *co2_str[8]; - dtostrf(co2, 5, 0, co2_str); - client.publish(topic_co2, co2_str); - char *temp_str[8]; - dtostrf(temperature, 6, 2, temp_str); - client.publish(topic_temp, temp_str); - char *hum_str[8]; - dtostrf(humidity, 6, 2, hum_str); - client.publish(topic_hum, hum_str); +void publishMQTT() { + for (int i = 0; (i < 5) && (!client.connected()); i++) { + client.connect(client_id); + delay(2000); } + if (!client.connected()) return; + dtostrf(co2, 5, 0, cbuf); + client.publish(topic_co2, cbuf); + dtostrf(temperature, 6, 2, cbuf); + client.publish(topic_temp, cbuf); + dtostrf(humidity, 6, 2, cbuf); + client.publish(topic_hum, cbuf); } /* ---------- HTTP ---------- */ @@ -376,41 +364,46 @@ bool initWifi() delay(100); WiFi.softAP(host, ap_password); delay(100); + client.setServer(mqtt_broker, mqtt_port); + delay(100); return wifiConnect(ssid, password); } template <typename ServerType> -void handleWifiSet(esp8266webserver::ESP8266WebServerTemplate<ServerType> *server) -{ - bool cnx, donotsave = true; +void handleWifiSet(esp8266webserver::ESP8266WebServerTemplate<ServerType> *server) { + bool modif = false, cnx, donotsave = true; #ifndef DEMO_MODE + buf = (*server).arg("broker"); + if (buf.length() > 0) { + modif = true; + buf.toCharArray(mqtt_broker, sizeof(mqtt_broker)); + buf = (*server).arg("port"); + mqtt_port = buf.toInt(); + } buf = (*server).arg("ssid"); - if (buf.length() > 0) - { + if (buf.length() > 0) { + modif = true; buf.toCharArray(ssid, sizeof(ssid)); buf = (*server).arg("pass"); buf.toCharArray(password, sizeof(password)); donotsave = (*server).hasArg("save"); } - else - return; + if (!modif) return; cnx = initWifi(); - if (cnx) - { - if ((fsOK) && (!donotsave)) - { + if (cnx) { + if ((fsOK) && (!donotsave)) { Serial.print(MSG[INFO]); Serial.println(F("Saving Wifi configuration.")); File file = fileSystem->open("/wifiSetup.cfg", "w"); file.println(ssid); file.println(password); + file.println(mqtt_broker); + file.println(mqtt_port); delay(10); file.close(); } - } - else - { + } else { Serial.print(MSG[WARN]); Serial.println(F("Resetting.")); ESP.reset(); @@ -440,6 +433,19 @@ void handleAP(esp8266webserver::ESP8266WebServerTemplate<ServerType> *server) void HTTPhandleAP() { return handleAP(&HTTPserver); } void HTTPShandleAP() { return handleAP(&HTTPSserver); } +template <typename ServerType> +void handleMQTTbroker(esp8266webserver::ESP8266WebServerTemplate<ServerType> *server) { + buf = "{\"broker\":\""; + buf += mqtt_broker; + buf += "\",\"port\":\""; + buf += mqtt_port; + buf += "\"}"; + (*server).send(200, MSG[MIME_JSON], buf); +} + +void HTTPhandleMQTTbroker() { return handleMQTTbroker(&HTTPserver); } +void HTTPShandleMQTTbroker() { return handleMQTTbroker(&HTTPSserver); } + template <typename ServerType> void handleAPSet(esp8266webserver::ESP8266WebServerTemplate<ServerType> *server) { @@ -474,6 +480,8 @@ void handleAPSet(esp8266webserver::ESP8266WebServerTemplate<ServerType> *server) #endif handleFileRead(server, "/"); } + + void HTTPhandleAPSet() { return handleAPSet(&HTTPserver); } void HTTPShandleAPSet() { return handleAPSet(&HTTPSserver); } @@ -785,6 +793,8 @@ void setup() buf.toCharArray(host, sizeof(host)); buf = DEFAULT_AP_PASSWD; buf.toCharArray(ap_password, sizeof(ap_password)); + buf = DEFAULT_MQTT_BROKER; + buf.toCharArray(mqtt_broker, sizeof(mqtt_broker)); buf = ""; buf.toCharArray(password, sizeof(password)); @@ -804,24 +814,22 @@ void setup() fileSystem->setConfig(fileSystemConfig); fsOK = fileSystem->begin(); - if (!fsOK) - { + if (!fsOK) { Serial.print(MSG[WARN]); Serial.println(F("Filesystem init failed !")); - } - else - { + } else { Serial.print(MSG[INFO]); Serial.println(F("Reading configuration files.")); File file = fileSystem->open("/wifiSetup.cfg", "r"); - if (file) - { + if (file) { readLineInFile(file, ssid, sizeof(ssid)); readLineInFile(file, password, sizeof(password)); + readLineInFile(file, mqtt_broker, sizeof(mqtt_broker)); + readLineInFile(file, cbuf, sizeof(cbuf)); + buf = cbuf; + mqtt_port = buf.toInt(); file.close(); - } - else - { + } else { Serial.print(MSG[WARN]); Serial.println(F("No wifi setup file found.")); } @@ -899,13 +907,10 @@ void setup() Serial.print(F("AP IP address: ")); Serial.println(WiFi.softAPIP()); - if (MDNS.begin(host)) - { + if (MDNS.begin(host)) { MDNS.addService("http", "tcp", 80); MDNS.addService("https", "tcp", 443); - } - else - { + } else { Serial.print(MSG[WARN]); Serial.println(F("Error setting up MDNS responder!")); } @@ -919,6 +924,7 @@ void setup() HTTPserver.on("/sensor", HTTP_GET, HTTPhandleSensor); HTTPserver.on("/listfiles", HTTP_GET, HTTPhandleFileList); HTTPserver.on("/scan", HTTP_GET, HTTPhandleWifiScan); + HTTPserver.on("/mqttbroker", HTTP_GET, HTTPhandleMQTTbroker); HTTPserver.on("/ap", HTTP_GET, HTTPhandleAP); HTTPserver.on("/status", HTTP_GET, HTTPhandleStatus); HTTPserver.on("/dtz", HTTP_GET, HTTPhandleDateTimeZone); @@ -935,6 +941,7 @@ void setup() HTTPSserver.on("/sensor", HTTP_GET, HTTPShandleSensor); HTTPSserver.on("/listfiles", HTTP_GET, HTTPShandleFileList); HTTPSserver.on("/scan", HTTP_GET, HTTPShandleWifiScan); + HTTPSserver.on("/mqttbroker", HTTP_GET, HTTPShandleMQTTbroker); HTTPSserver.on("/ap", HTTP_GET, HTTPShandleAP); HTTPSserver.on("/status", HTTP_GET, HTTPShandleStatus); HTTPSserver.on("/dtz", HTTP_GET, HTTPShandleDateTimeZone); @@ -953,8 +960,7 @@ void setup() setServer(ntpServerName); waitForSync(60); /* Waits NTP sync for max. 60 seconds. */ setInterval(120); /* Try every 2 minutes until success */ - if (!tz.setLocation(timezone)) - { + if (!tz.setLocation(timezone)) { Serial.print(MSG[WARN]); Serial.print(F("Timezone setting failed -> ")); Serial.println(timezone); @@ -964,14 +970,12 @@ void setup() delay(1000); i = 0; - while ((!(sensorOK = airSensor.begin())) && (i++ < 6)) - { + while ((!(sensorOK = airSensor.begin())) && (i++ < 6)) { Serial.print(MSG[ERR]); Serial.println(F("Air sensor not detected. Please check wiring. Waiting 10s...")); delay(10000); } - if (sensorOK) - { + if (sensorOK) { airSensor.setMeasurementInterval(interval); airSensor.setAltitudeCompensation(altitude); } @@ -979,26 +983,20 @@ void setup() /* Set datafile name */ tzOK = (timeStatus() == timeSet); - if (tzOK) - { + if (tzOK) { setInterval(ntpUpdateInterval); datafile = "data/" + tz.dateTime("YmdHi") + ".csv"; Serial.print(MSG[INFO]); Serial.print(F("NTP date and time set : ")); Serial.println(tz.dateTime(timeformat)); - } - else - { + } else { Serial.print(MSG[WARN]); Serial.println(F("NTP date and time not set.")); - if (fsOK) - { /* If !(fsOK), we won't save any data. */ + if (fsOK) { /* If !(fsOK), we won't save any data. */ Dir dir = fileSystem->openDir("/data"); j = 0; - while (dir.next()) - { - if (!dir.isDirectory()) - { + while (dir.next()) { + if (!dir.isDirectory()) { // Always return names without leading "/" if (dir.fileName()[0] == '/') buf = &(dir.fileName()[1]); @@ -1013,21 +1011,18 @@ void setup() datafile = "data/" + String(j) + "-NS.csv"; else datafile = F("data/197001010000-NS.csv"); - } - else - { + } else { datafile = ""; } } - if ((datafile.length() > 0) && (writeData)) - { + if ((datafile.length() > 0) && (writeData)) { Serial.print(MSG[INFO]); Serial.print(F("Writing data into ")); Serial.println(datafile); } /* --- MQTT --- */ - publishMQTT(); + /*publishMQTT();*/ /* La première mesure est vide */ } void loop() @@ -1067,8 +1062,7 @@ void loop() } /* --- Get sensor data if available and write it to file. --- */ - if (getSensorData()) - { + if (getSensorData()) { /* Write to file */ cbuf[0] = ';'; buf = tzOK ? tz.dateTime(timeformat) : ""; @@ -1082,19 +1076,14 @@ void loop() buf += millis(); Serial.print(F("[MEASURE] ")); Serial.println(buf); - if ((writeData) && (fsOK)) - { /* Write to file */ + if ((writeData) && (fsOK)) { /* Write to file */ file = LittleFS.open(datafile, "a"); - if (!file) - { + if (!file) { Serial.print(MSG[ERR]); Serial.print(F("Failed to open file for appending : ")); Serial.println(datafile); - } - else - { - if (!file.println(buf)) - { + } else { + if (!file.println(buf)) { Serial.print(MSG[ERR]); Serial.print(F("Failed to write data to file ")); Serial.println(datafile); @@ -1102,11 +1091,10 @@ void loop() file.close(); } } + /* --- MQTT --- */ + publishMQTT(); } - /* --- MQTT --- */ - publishMQTT(); - HTTPserver.handleClient(); HTTPSserver.handleClient(); MDNS.update(); diff --git a/Co2Huzzah/data/setupDateTime.html b/Co2Huzzah/data/setupDateTime.html index 0431aff..962b1f2 100644 --- a/Co2Huzzah/data/setupDateTime.html +++ b/Co2Huzzah/data/setupDateTime.html @@ -27,7 +27,7 @@ var opts=` ffEtc/Greenwichĸ+00¸Greenwich Mean Time : Dublin—Edinburgh—Lisbon—Londonə ff¦Amsterdamĸ+01¸Amsterdam—Berlin—Bern—Rome—Stockholm—Viennaə ff¦Belgradeĸ+01¸Belgrade—Bratislava—Budapest—Ljubljana—Pragueə -ff¦Parisĸ+01¸Brussels—Copenhagen—Madrid—Parisə +ff¦Brusselsĸ+01¸Brussels—Copenhagen—Madrid—Parisə ff¦Sarajevoĸ+01¸Sarajevo—Skopje—Warsaw—Zagrebəff¶Lagosĸ+01¸West Central Africaə ff¤Ammanĸ+02¸Ammanəff¦Athensĸ+02¸Athens—Bucharest—Istanbuləff¤Beirutĸ+02¸Beirutə ff¶Cairoĸ+02¸Cairoəff¶Harareĸ+02¸Harare—Pretoriaə diff --git a/Co2Huzzah/data/setupWifi.html b/Co2Huzzah/data/setupWifi.html index dc20f31..ac60343 100644 --- a/Co2Huzzah/data/setupWifi.html +++ b/Co2Huzzah/data/setupWifi.html @@ -12,6 +12,13 @@ .then(function (response) {return response.json();}) .then(function (data) { listScan(data);}) .catch(function (err) { console.log('error: ' + err); }); + fetch('mqttbroker') + .then(function (response) {return response.json();}) + .then(function (data) { fillForm(data);}) + .catch(function (err) { console.log('error: ' + err); }); + function fillForm(data) { + document.getElementById("mqtt").value = data.broker; + document.getElementById("port").value = data.port; } function listScan(data) { var mainContainer = document.getElementById("listwifi"); if (data.length == 0) { @@ -62,16 +69,25 @@ <tr><td>Password : </td><td><input type='password' id='pass' name='pass' length=64 /></td></tr> </table></div> <div class="itxt"><div class="chk"><input type="checkbox" onclick="showPw()">Show Password</div></div> +</div></div> + +<div class="linfo"><div class="ititle">MQTT</div><div class="icont"><div class="itxt"> +<table> +<tr><td>Broker : </td><td><input type='text' id='mqtt' name='broker' length=16 /></td></tr> +<tr><td>Port : </td><td><input type='text' id='port' name='port' length=5 /></td></tr> +</table> +</div></div></div> + +<div class="linfo"><div class="icont"> <div class="itxt"><div class="chk"><input type='checkbox' id='donotsave' name='save'> <label for='donotsave'>Do not save to flash.</label></div></div> <div class="itxt"><div class="btn"><input type='submit' value='Set' /></div></div> -</div></div></form> +</div></div> + +</form> <form id="donotsend"> <div class="linfo"><div class="ititle">Detected AP</div><div class="icont"> <div id="listwifi"><div class="itxt"><div class="loader"></div></div></div> </div></div></form> - - - </div> </form></div></body></html> -- GitLab