No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.cpp 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * main.cpp
  3. *
  4. * ESP8266 / ESP32 Environmental Sensor
  5. *
  6. * ----------------------------------------------------------------------------
  7. * "THE BEER-WARE LICENSE" (Revision 42):
  8. * <xythobuz@xythobuz.de> wrote this file. As long as you retain this notice
  9. * you can do whatever you want with this stuff. If we meet some day, and you
  10. * think this stuff is worth it, you can buy me a beer in return. Thomas Buck
  11. * ----------------------------------------------------------------------------
  12. */
  13. #include <Arduino.h>
  14. #include <Wire.h>
  15. #include <PubSubClient.h>
  16. #if defined(ARDUINO_ARCH_ESP8266)
  17. #include <ESP8266WiFi.h>
  18. #include <ESP8266WebServer.h>
  19. #include <ESP8266mDNS.h>
  20. #elif defined(ARDUINO_ARCH_ESP32)
  21. #include <WiFi.h>
  22. #include <WebServer.h>
  23. #include <ESPmDNS.h>
  24. #endif
  25. #include "config.h"
  26. #include "relais.h"
  27. #include "SimpleUpdater.h"
  28. #define BUILTIN_LED_PIN 1
  29. UPDATE_WEB_SERVER server(80);
  30. SimpleUpdater updater;
  31. #ifdef ENABLE_MQTT
  32. WiFiClient mqttClient;
  33. PubSubClient mqtt(mqttClient);
  34. #endif // ENABLE_MQTT
  35. #ifdef ENABLE_INFLUXDB_LOGGING
  36. #include <InfluxDb.h>
  37. Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT);
  38. #define INFLUX_MAX_ERRORS_RESET 10
  39. int error_count = 0;
  40. #endif // ENABLE_INFLUXDB_LOGGING
  41. #ifdef ENABLE_NTP
  42. #include <WiFiUdp.h>
  43. #include <NTPClient.h>
  44. WiFiUDP ntpUDP;
  45. NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 2 * 60 * 60, 5 * 60 * 1000);
  46. #endif // ENABLE_NTP
  47. unsigned long last_server_handle_time = 0;
  48. unsigned long last_db_write_time = 0;
  49. unsigned long last_led_blink_time = 0;
  50. unsigned long last_timing_check_time = 0;
  51. String relais_name[RELAIS_COUNT] = {
  52. String(" (Small Light)"),
  53. String(" (Big Light)"),
  54. String(""),
  55. String(" (Fan)"),
  56. };
  57. bool relais_state[RELAIS_COUNT] = { false, false, false, false };
  58. String auto_set_state = String("");
  59. #ifdef ENABLE_NTP
  60. void handleAutoTimingCheck(void) {
  61. relais_state[3] = true; // always keep fan on
  62. if ((timeClient.getHours() >= 20) || (timeClient.getHours() < 10)) {
  63. // small light from 20:00 to 10:00
  64. relais_state[0] = true;
  65. relais_state[1] = false;
  66. auto_set_state = String(F("Small Light at Night (")) + String(timeClient.getFormattedTime()) + String(F(")"));
  67. } else {
  68. // big light from 10:00 to 20:00
  69. relais_state[0] = false;
  70. relais_state[1] = true;
  71. auto_set_state = String(F("Big Light while Daylight (")) + String(timeClient.getFormattedTime()) + String(F(")"));
  72. }
  73. for (int i = 0; i < RELAIS_COUNT; i++) {
  74. relais_set(i, relais_state[i] ? 1 : 0);
  75. }
  76. }
  77. #endif // ENABLE_NTP
  78. void handlePage(int mode = -1, int id = 0) {
  79. String message = F("<html><head>\n");
  80. message += F("<title>" ESP_PLATFORM_NAME " MQTT Relais</title>\n");
  81. message += F("</head><body>\n");
  82. message += F("<h1>" ESP_PLATFORM_NAME " MQTT Relais</h1>\n");
  83. message += F("\n<p>\n");
  84. for (int i = 0; i < RELAIS_COUNT; i++) {
  85. message += String(F("<a href=\"/on?id=")) + String(i) + String(F("\">Relais ")) + String(i) + String(F(" On")) + relais_name[i] + String(F("</a><br>\n"));
  86. message += String(F("<a href=\"/off?id=")) + String(i) + String(F("\">Relais ")) + String(i) + String(F(" Off")) + relais_name[i] + String(F("</a><br>\n"));
  87. }
  88. message += String(F("<a href=\"/on?id=")) + String(RELAIS_COUNT) + String(F("\">All Relais On</a><br>\n"));
  89. message += String(F("<a href=\"/off?id=")) + String(RELAIS_COUNT) + String(F("\">All Relais Off</a><br>\n"));
  90. message += F("</p>\n");
  91. if (mode >= 0) {
  92. message += F("<p>");
  93. message += F("Turned Relais ");
  94. message += (id < RELAIS_COUNT) ? String(id) : String(F("1-4"));
  95. message += (mode ? String(F(" On")) : String(F(" Off")));
  96. message += F("</p>\n");
  97. }
  98. message += F("\n<p>\n");
  99. for (int i = 0; i < RELAIS_COUNT; i++) {
  100. message += String(F("Relais ")) + String(i) + String(F(" = ")) + (relais_state[i] ? String(F("On")) : String(F("Off"))) + String(F("<br>\n"));
  101. }
  102. message += F("</p>\n");
  103. #ifdef ENABLE_NTP
  104. message += F("<p>Time from NTP: ");
  105. message += String(timeClient.getFormattedTime());
  106. message += F("</p>\n");
  107. message += F("<p>Auto-State: ");
  108. message += auto_set_state;
  109. message += F("</p>\n");
  110. unsigned long next_min = (AUTO_TIMING_INTERVAL - (millis() - last_timing_check_time)) / (1000 * 60);
  111. message += F("<p>Next Auto-State in ");
  112. message += String(next_min);
  113. message += F("min</p>\n");
  114. #endif // ENABLE_NTP
  115. message += F("<p><a href=\"/\">Refresh Page</a></p>\n");
  116. message += F("\n<p>\n");
  117. message += F("Version: ");
  118. message += ESP_RELAIS_VERSION;
  119. message += F("\n<br>\n");
  120. message += F("Location: ");
  121. message += SENSOR_LOCATION;
  122. message += F("\n<br>\n");
  123. message += F("MAC: ");
  124. message += WiFi.macAddress();
  125. message += F("\n</p>\n");
  126. #if defined(ARDUINO_ARCH_ESP8266)
  127. message += F("\n<p>\n");
  128. message += F("Reset reason: ");
  129. message += ESP.getResetReason();
  130. message += F("\n<br>\n");
  131. message += F("Free heap: ");
  132. message += String(ESP.getFreeHeap());
  133. message += F(" (");
  134. message += String(ESP.getHeapFragmentation());
  135. message += F("% fragmentation)");
  136. message += F("\n<br>\n");
  137. message += F("Free sketch space: ");
  138. message += String(ESP.getFreeSketchSpace());
  139. message += F("\n<br>\n");
  140. message += F("Flash chip real size: ");
  141. message += String(ESP.getFlashChipRealSize());
  142. if (ESP.getFlashChipSize() != ESP.getFlashChipRealSize()) {
  143. message += F("\n<br>\n");
  144. message += F("WARNING: sdk chip size (");
  145. message += (ESP.getFlashChipSize());
  146. message += F(") does not match!");
  147. }
  148. message += F("\n</p>\n");
  149. #elif defined(ARDUINO_ARCH_ESP32)
  150. message += F("\n<p>\n");
  151. message += F("Free heap: ");
  152. message += String(ESP.getFreeHeap() / 1024.0);
  153. message += F("k\n<br>\n");
  154. message += F("Free sketch space: ");
  155. message += String(ESP.getFreeSketchSpace() / 1024.0);
  156. message += F("k\n<br>\n");
  157. message += F("Flash chip size: ");
  158. message += String(ESP.getFlashChipSize() / 1024.0);
  159. message += F("k\n</p>\n");
  160. #endif
  161. message += F("<p>\n");
  162. message += F("Try <a href=\"/update\">/update</a> for OTA firmware updates!\n");
  163. message += F("</p>\n");
  164. message += F("<p>\n");
  165. #ifdef ENABLE_INFLUXDB_LOGGING
  166. message += F("InfluxDB: ");
  167. message += INFLUXDB_DATABASE;
  168. message += F(" @ ");
  169. message += INFLUXDB_HOST;
  170. message += F(":");
  171. message += String(INFLUXDB_PORT);
  172. message += F("\n");
  173. #else
  174. message += F("InfluxDB logging not enabled!\n");
  175. #endif
  176. message += F("</p>\n");
  177. message += F("</body></html>\n");
  178. server.send(200, "text/html", message);
  179. }
  180. void handleOn() {
  181. String id_string = server.arg("id");
  182. int id = id_string.toInt();
  183. if ((id >= 0) && (id < RELAIS_COUNT)) {
  184. relais_set(id, 1);
  185. relais_state[id] = true;
  186. } else {
  187. for (int i = 0; i < RELAIS_COUNT; i++) {
  188. relais_set(i, 1);
  189. relais_state[i] = true;
  190. }
  191. }
  192. // only reset to default after 15min
  193. last_timing_check_time = millis();
  194. handlePage(1, id);
  195. }
  196. void handleOff() {
  197. String id_string = server.arg("id");
  198. int id = id_string.toInt();
  199. if ((id >= 0) && (id < RELAIS_COUNT)) {
  200. relais_set(id, 0);
  201. relais_state[id] = false;
  202. } else {
  203. for (int i = 0; i < RELAIS_COUNT; i++) {
  204. relais_set(i, 0);
  205. relais_state[i] = false;
  206. }
  207. }
  208. // only reset to default after 15min
  209. last_timing_check_time = millis();
  210. handlePage(0, id);
  211. }
  212. void handleRoot() {
  213. handlePage();
  214. }
  215. #ifdef ENABLE_MQTT
  216. void mqttCallback(char* topic, byte* payload, unsigned int length) {
  217. int state = 0;
  218. int id = 0;
  219. // TODO check topic matches
  220. if (((char)payload[0] == 't')
  221. && ((char)payload[1] == 'u')
  222. && ((char)payload[2] == 'r')
  223. && ((char)payload[3] == 'n')
  224. && ((char)payload[4] == ' ')
  225. && ((char)payload[5] == 'o')) {
  226. if (((char)payload[6] == 'n')
  227. && ((char)payload[7] == ' ')) {
  228. // turn on
  229. state = 1;
  230. id = payload[8];
  231. } else if (((char)payload[6] == 'f')
  232. && ((char)payload[7] == 'f')
  233. && ((char)payload[8] == ' ')) {
  234. // turn off
  235. state = 0;
  236. id = payload[9];
  237. } else {
  238. return;
  239. }
  240. } else {
  241. return;
  242. }
  243. relais_set(id - 1, state);
  244. relais_state[id - 1] = state ? true : false;
  245. }
  246. void mqttReconnect() {
  247. // Loop until we're reconnected
  248. //while (!mqtt.connected()) {
  249. // Create a random client ID
  250. String clientId = "ESP8266Client-";
  251. clientId += String(random(0xffff), HEX);
  252. // Attempt to connect
  253. if (mqtt.connect(clientId.c_str())) {
  254. // Once connected, publish an announcement...
  255. //mqtt.publish("outTopic", "hello world");
  256. // ... and resubscribe
  257. mqtt.subscribe(SENSOR_LOCATION);
  258. } else {
  259. // Wait 5 seconds before retrying
  260. delay(5000);
  261. }
  262. //}
  263. }
  264. #endif // ENABLE_MQTT
  265. void setup() {
  266. pinMode(BUILTIN_LED_PIN, OUTPUT);
  267. relais_init();
  268. for (int i = 0; i < RELAIS_COUNT; i++) {
  269. relais_state[i] = false;
  270. }
  271. Serial.println();
  272. Serial.println("Hello World From Relais Test");
  273. // Blink LED for init
  274. for (int i = 0; i < 2; i++) {
  275. digitalWrite(BUILTIN_LED_PIN, LOW); // LED on
  276. delay(LED_INIT_BLINK_INTERVAL);
  277. digitalWrite(BUILTIN_LED_PIN, HIGH); // LED off
  278. delay(LED_INIT_BLINK_INTERVAL);
  279. }
  280. // Build hostname string
  281. String hostname = SENSOR_HOSTNAME_PREFIX;
  282. hostname += SENSOR_LOCATION;
  283. #if defined(ARDUINO_ARCH_ESP8266)
  284. // Connect to WiFi AP
  285. Serial.print("Connecting to WiFi ");
  286. WiFi.hostname(hostname);
  287. WiFi.mode(WIFI_STA);
  288. WiFi.begin(WIFI_SSID, WIFI_PASS);
  289. while (WiFi.status() != WL_CONNECTED) {
  290. Serial.print(WiFi.status());
  291. Serial.print(" ");
  292. delay(LED_CONNECT_BLINK_INTERVAL);
  293. digitalWrite(BUILTIN_LED_PIN, !digitalRead(BUILTIN_LED_PIN));
  294. }
  295. Serial.println();
  296. Serial.print("Got local IP ");
  297. Serial.println(WiFi.localIP().toString());
  298. #elif defined(ARDUINO_ARCH_ESP32)
  299. // Set hostname workaround
  300. WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
  301. WiFi.setHostname(hostname.c_str());
  302. // Workaround for WiFi connecting only every 2nd reset
  303. // https://github.com/espressif/arduino-esp32/issues/2501#issuecomment-513602522
  304. WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info) {
  305. if (info.disconnected.reason == 202) {
  306. esp_sleep_enable_timer_wakeup(10);
  307. esp_deep_sleep_start();
  308. delay(100);
  309. }
  310. }, WiFiEvent_t::SYSTEM_EVENT_STA_DISCONNECTED);
  311. // Connect to WiFi AP
  312. Serial.print("Connecting to WiFi");
  313. WiFi.mode(WIFI_STA);
  314. WiFi.begin(WIFI_SSID, WIFI_PASS);
  315. while (WiFi.status() != WL_CONNECTED) {
  316. Serial.print(".");
  317. delay(LED_CONNECT_BLINK_INTERVAL);
  318. digitalWrite(BUILTIN_LED_PIN, !digitalRead(BUILTIN_LED_PIN));
  319. }
  320. Serial.println();
  321. // Set hostname workaround
  322. WiFi.setHostname(hostname.c_str());
  323. #endif
  324. Serial.println("Seeding");
  325. randomSeed(micros());
  326. #ifdef ENABLE_MQTT
  327. Serial.println("MQTT");
  328. mqtt.setServer(MQTT_HOST, MQTT_PORT);
  329. mqtt.setCallback(mqttCallback);
  330. #endif // ENABLE_MQTT
  331. #ifdef ENABLE_INFLUXDB_LOGGING
  332. // Setup InfluxDB Client
  333. influx.setDb(INFLUXDB_DATABASE);
  334. #endif // ENABLE_INFLUXDB_LOGGING
  335. #ifdef ENABLE_NTP
  336. timeClient.begin();
  337. #endif // ENABLE_NTP
  338. // Setup HTTP Server
  339. Serial.println("Server");
  340. MDNS.begin(hostname.c_str());
  341. updater.setup(&server);
  342. server.on("/", handleRoot);
  343. server.on("/on", handleOn);
  344. server.on("/off", handleOff);
  345. server.begin();
  346. MDNS.addService("http", "tcp", 80);
  347. Serial.println("Done");
  348. }
  349. void handleServers() {
  350. server.handleClient();
  351. #if defined(ARDUINO_ARCH_ESP8266)
  352. MDNS.update();
  353. #endif
  354. }
  355. #ifdef ENABLE_INFLUXDB_LOGGING
  356. static boolean writeMeasurement(InfluxData &measurement) {
  357. boolean success = influx.write(measurement);
  358. if (!success) {
  359. error_count++;
  360. for (int i = 0; i < 10; i++) {
  361. digitalWrite(BUILTIN_LED_PIN, LOW); // LED on
  362. delay(LED_ERROR_BLINK_INTERVAL);
  363. digitalWrite(BUILTIN_LED_PIN, HIGH); // LED off
  364. delay(LED_ERROR_BLINK_INTERVAL);
  365. }
  366. }
  367. return success;
  368. }
  369. void writeDatabase() {
  370. if (found_bme1) {
  371. InfluxData measurement("environment");
  372. measurement.addTag("location", SENSOR_LOCATION);
  373. measurement.addTag("placement", "1");
  374. measurement.addTag("device", WiFi.macAddress());
  375. measurement.addTag("sensor", "bme280");
  376. measurement.addValue("temperature", bme1_temp());
  377. measurement.addValue("pressure", bme1_pressure());
  378. measurement.addValue("humidity", bme1_humid());
  379. writeMeasurement(measurement);
  380. }
  381. if (found_bme2) {
  382. InfluxData measurement("environment");
  383. measurement.addTag("location", SENSOR_LOCATION);
  384. measurement.addTag("placement", "2");
  385. measurement.addTag("device", WiFi.macAddress());
  386. measurement.addTag("sensor", "bme280");
  387. measurement.addValue("temperature", bme2_temp());
  388. measurement.addValue("pressure", bme2_pressure());
  389. measurement.addValue("humidity", bme2_humid());
  390. writeMeasurement(measurement);
  391. }
  392. if (found_sht) {
  393. InfluxData measurement("environment");
  394. measurement.addTag("location", SENSOR_LOCATION);
  395. measurement.addTag("device", WiFi.macAddress());
  396. measurement.addTag("sensor", "sht21");
  397. measurement.addValue("temperature", sht_temp());
  398. measurement.addValue("humidity", sht_humid());
  399. writeMeasurement(measurement);
  400. }
  401. for (int i = 0; i < moisture_count(); i++) {
  402. int moisture = moisture_read(i);
  403. if (moisture < moisture_max()) {
  404. InfluxData measurement("moisture");
  405. measurement.addTag("location", SENSOR_LOCATION);
  406. measurement.addTag("device", WiFi.macAddress());
  407. measurement.addTag("sensor", String(i + 1));
  408. measurement.addValue("value", moisture);
  409. measurement.addValue("maximum", moisture_max());
  410. writeMeasurement(measurement);
  411. }
  412. }
  413. }
  414. #endif // ENABLE_INFLUXDB_LOGGING
  415. void loop() {
  416. if ((millis() - last_server_handle_time) >= SERVER_HANDLE_INTERVAL) {
  417. last_server_handle_time = millis();
  418. handleServers();
  419. }
  420. #ifdef ENABLE_NTP
  421. timeClient.update();
  422. if (timeClient.isTimeSet()) {
  423. if (((millis() - last_timing_check_time) >= AUTO_TIMING_INTERVAL) || (last_timing_check_time == 0)) {
  424. last_timing_check_time = millis();
  425. handleAutoTimingCheck();
  426. }
  427. }
  428. #endif // ENABLE_NTP
  429. #ifdef ENABLE_MQTT
  430. if (!mqtt.connected()) {
  431. mqttReconnect();
  432. }
  433. mqtt.loop();
  434. #endif // ENABLE_MQTT
  435. #ifdef ENABLE_INFLUXDB_LOGGING
  436. if ((millis() - last_db_write_time) >= DB_WRITE_INTERVAL) {
  437. last_db_write_time = millis();
  438. writeDatabase();
  439. }
  440. #ifdef INFLUX_MAX_ERRORS_RESET
  441. if (error_count >= INFLUX_MAX_ERRORS_RESET) {
  442. ESP.restart();
  443. }
  444. #endif // INFLUX_MAX_ERRORS_RESET
  445. #endif // ENABLE_INFLUXDB_LOGGING
  446. // blink heartbeat LED
  447. if ((millis() - last_led_blink_time) >= LED_BLINK_INTERVAL) {
  448. last_led_blink_time = millis();
  449. digitalWrite(BUILTIN_LED_PIN, !digitalRead(BUILTIN_LED_PIN));
  450. }
  451. // reset ESP every 48h to be safe
  452. if (millis() >= (48 * 60 * 60 * 1000)) {
  453. ESP.restart();
  454. }
  455. }