DIY fertilizer mixer and plant watering machine https://www.xythobuz.de/giessomat.html
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.

WifiStuff.cpp 43KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. /*
  2. * Copyright (c) 2021 Thomas Buck <thomas@xythobuz.de>
  3. *
  4. * This file is part of Giess-o-mat.
  5. *
  6. * Giess-o-mat is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Giess-o-mat is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Giess-o-mat. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. #include <Arduino.h>
  20. #ifdef PLATFORM_ESP
  21. #if defined(ARDUINO_ARCH_ESP8266)
  22. #include <ESP8266WiFi.h>
  23. #include <ESP8266WebServer.h>
  24. #include <ESP8266mDNS.h>
  25. #elif defined(ARDUINO_ARCH_ESP32)
  26. #include <WiFi.h>
  27. #include <WebServer.h>
  28. #include <ESPmDNS.h>
  29. #endif
  30. #include <WebSocketsServer.h>
  31. #include "wifi.h"
  32. #include "config.h"
  33. #include "config_pins.h"
  34. #include "Functionality.h"
  35. #include "SimpleUpdater.h"
  36. #include "DebugLog.h"
  37. #include "BoolField.h"
  38. #include "WifiStuff.h"
  39. #ifdef TELEGRAM_TOKEN
  40. #include <WiFiClientSecure.h>
  41. #include <UniversalTelegramBot.h>
  42. //#define TELEGRAM_LOG_TIMINGS
  43. #if defined(ARDUINO_ARCH_ESP8266)
  44. X509List cert(TELEGRAM_CERTIFICATE_ROOT);
  45. #endif
  46. WiFiClientSecure secured_client;
  47. UniversalTelegramBot bot(TELEGRAM_TOKEN, secured_client);
  48. unsigned long last_telegram_time = 0;
  49. String trusted_chat_ids[] = TRUSTED_IDS;
  50. enum telegram_state {
  51. BOT_IDLE,
  52. BOT_ASKED_FERT,
  53. BOT_ASKED_PLANTS,
  54. BOT_ASKED_CONFIRM
  55. };
  56. enum telegram_state bot_state = BOT_IDLE;
  57. String bot_lock = "";
  58. #endif // TELEGRAM_TOKEN
  59. #ifdef MQTT_HOST
  60. #include <PubSubClient.h>
  61. WiFiClient mqttClient;
  62. PubSubClient mqtt(mqttClient);
  63. unsigned long last_mqtt_reconnect_time = 0;
  64. #endif // MQTT_HOST
  65. #if defined(TELEGRAM_TOKEN) || defined(MQTT_HOST)
  66. static BoolField bot_plants(VALVE_COUNT - 1);
  67. static BoolField bot_ferts(PUMP_COUNT);
  68. #endif // TELEGRAM_TOKEN || MQTT_HOST
  69. UPDATE_WEB_SERVER server(80);
  70. WebSocketsServer socket = WebSocketsServer(81);
  71. SimpleUpdater updater;
  72. unsigned long last_server_handle_time = 0;
  73. unsigned long last_websocket_update_time = 0;
  74. int wifi_ok = 0;
  75. String message_buffer_a;
  76. String message_buffer_b;
  77. String message_buffer_c;
  78. String message_buffer_d;
  79. #ifdef ENABLE_GPIO_TEST
  80. static bool runningGpioTest = false;
  81. static bool gpioTestState = false;
  82. unsigned long lastGpioTime = 0;
  83. #endif // ENABLE_GPIO_TEST
  84. #ifdef ENABLE_INFLUXDB_LOGGING
  85. #include <InfluxDb.h>
  86. Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT);
  87. #endif // ENABLE_INFLUXDB_LOGGING
  88. #ifdef ENABLE_GPIO_TEST
  89. void runGpioTest(bool state) {
  90. lastGpioTime = millis();
  91. for (int i = 0; i < VALVE_COUNT; i++) {
  92. get_plants()->getValves()->setPin(i, state);
  93. delay(GPIO_TEST_DELAY);
  94. }
  95. for (int i = 0; i < PUMP_COUNT; i++) {
  96. get_plants()->getPumps()->setPin(i, state);
  97. if (i < (PUMP_COUNT - 1)) {
  98. delay(GPIO_TEST_DELAY);
  99. }
  100. }
  101. }
  102. void handleGpioTest() {
  103. runningGpioTest = !runningGpioTest;
  104. gpioTestState = runningGpioTest;
  105. String message = F("GPIOs turned ");
  106. message += runningGpioTest ? "on" : "off";
  107. server.send(200, "text/html", message);
  108. runGpioTest(gpioTestState);
  109. }
  110. #endif // ENABLE_GPIO_TEST
  111. void wifi_broadcast_state_change(const char *s) {
  112. #ifdef TELEGRAM_TOKEN
  113. for (int n = 0; n < (sizeof(trusted_chat_ids) / sizeof(trusted_chat_ids[0])); n++) {
  114. bot.sendMessage(trusted_chat_ids[n], "New state: " + String(s), "");
  115. }
  116. #endif // TELEGRAM_TOKEN
  117. #ifdef MQTT_HOST
  118. String payload = String("state: ") + s;
  119. mqtt.publish("giessomat", payload.c_str());
  120. #endif // MQTT_HOST
  121. }
  122. #ifdef TELEGRAM_TOKEN
  123. unsigned long telegram_update_interval() {
  124. if (bot_state == BOT_IDLE) {
  125. return TELEGRAM_UPDATE_INTERVAL_SLOW;
  126. } else {
  127. return TELEGRAM_UPDATE_INTERVAL_FAST;
  128. }
  129. }
  130. String telegram_help() {
  131. String s = "Usage:\n";
  132. s += "Send /auto and follow prompts.\n";
  133. s += "Send /abort to cancel menus.\n";
  134. s += "Send /none to skip menus.\n";
  135. s += "Send /begin to confirm menus.";
  136. return s;
  137. }
  138. void telegram_handle_message(int message_id) {
  139. if (!sm_is_idle()) {
  140. debug.println("Telegram: message while machine in use");
  141. if (bot.messages[message_id].text == "/abort") {
  142. sm_bot_abort();
  143. bot.sendMessage(bot.messages[message_id].chat_id, "Aborted current cycle!", "");
  144. } else {
  145. bot.sendMessage(bot.messages[message_id].chat_id, "Machine is already in use.\nPlease try again later.", "");
  146. }
  147. return;
  148. }
  149. if ((bot_state == BOT_IDLE) && (bot_lock == "")) {
  150. bot_lock = bot.messages[message_id].chat_id;
  151. debug.println("Telegram: locked to " + bot_lock);
  152. }
  153. if (bot_lock != bot.messages[message_id].chat_id) {
  154. debug.println("Telegram: bot locked. abort for chat " + bot.messages[message_id].chat_id);
  155. bot.sendMessage(bot.messages[message_id].chat_id, "Bot is already in use.\nPlease try again later.", "");
  156. return;
  157. }
  158. if (bot_state == BOT_IDLE) {
  159. if (bot.messages[message_id].text == "/auto") {
  160. String s = "Please enter fertilizer numbers.\n";
  161. s += "Valid numbers: 1 to " + String(PUMP_COUNT) + "\n";
  162. s += "Send /none to skip.\n";
  163. s += "Send /abort to cancel.";
  164. bot_ferts.clear();
  165. bot_state = BOT_ASKED_FERT;
  166. bot.sendMessage(bot.messages[message_id].chat_id, s, "");
  167. } else if (bot.messages[message_id].text == "/abort") {
  168. bot_lock = "";
  169. bot.sendMessage(bot.messages[message_id].chat_id, "Nothing to abort.", "");
  170. } else {
  171. bot_lock = "";
  172. bot.sendMessage(bot.messages[message_id].chat_id, telegram_help(), "");
  173. }
  174. } else if (bot_state == BOT_ASKED_FERT) {
  175. if (bot.messages[message_id].text == "/abort") {
  176. bot_state = BOT_IDLE;
  177. bot_lock = "";
  178. bot.sendMessage(bot.messages[message_id].chat_id, "Aborted.", "");
  179. return;
  180. } else if (bot.messages[message_id].text != "/none") {
  181. String buff;
  182. for (int i = 0; i < bot.messages[message_id].text.length() + 1; i++) {
  183. if ((i == bot.messages[message_id].text.length()) || (bot.messages[message_id].text[i] == ' ')) {
  184. if (buff.length() > 0) {
  185. int n = buff.toInt() - 1;
  186. buff = "";
  187. bot_ferts.set(n);
  188. }
  189. } else if ((bot.messages[message_id].text[i] >= '0') && (bot.messages[message_id].text[i] <= '9')) {
  190. buff += bot.messages[message_id].text[i];
  191. } else {
  192. bot_state = BOT_IDLE;
  193. bot_lock = "";
  194. bot.sendMessage(bot.messages[message_id].chat_id, "Invalid input.\nAborted.", "");
  195. return;
  196. }
  197. }
  198. }
  199. String s = "Please enter plant numbers.\n";
  200. s += "Valid numbers: 1 to " + String(VALVE_COUNT - 1) + "\n";
  201. s += "Send /abort to cancel.";
  202. bot_plants.clear();
  203. bot_state = BOT_ASKED_PLANTS;
  204. bot.sendMessage(bot.messages[message_id].chat_id, s, "");
  205. } else if (bot_state == BOT_ASKED_PLANTS) {
  206. if (bot.messages[message_id].text == "/abort") {
  207. bot_state = BOT_IDLE;
  208. bot_lock = "";
  209. bot.sendMessage(bot.messages[message_id].chat_id, "Aborted.", "");
  210. return;
  211. }
  212. String buff;
  213. for (int i = 0; i < bot.messages[message_id].text.length() + 1; i++) {
  214. if ((i == bot.messages[message_id].text.length()) || (bot.messages[message_id].text[i] == ' ')) {
  215. if (buff.length() > 0) {
  216. int n = buff.toInt() - 1;
  217. buff = "";
  218. bot_plants.set(n);
  219. }
  220. } else if ((bot.messages[message_id].text[i] >= '0') && (bot.messages[message_id].text[i] <= '9')) {
  221. buff += bot.messages[message_id].text[i];
  222. } else {
  223. bot_state = BOT_IDLE;
  224. bot_lock = "";
  225. bot.sendMessage(bot.messages[message_id].chat_id, "Invalid input.\nAborted.", "");
  226. return;
  227. }
  228. }
  229. if (bot_plants.countSet() <= 0) {
  230. bot_state = BOT_IDLE;
  231. bot_lock = "";
  232. bot.sendMessage(bot.messages[message_id].chat_id, "No plants selected.\nAborted.", "");
  233. return;
  234. }
  235. #ifdef FULLAUTO_MIN_PLANT_COUNT
  236. if (bot_plants.countSet() < FULLAUTO_MIN_PLANT_COUNT) {
  237. bot_state = BOT_IDLE;
  238. bot_lock = "";
  239. bot.sendMessage(bot.messages[message_id].chat_id, "Select at least " + String(FULLAUTO_MIN_PLANT_COUNT) + " plants.\nAborted.", "");
  240. return;
  241. }
  242. #endif
  243. String s = "Input accepted.\nFertilizers:";
  244. for (int i = 0; i < PUMP_COUNT; i++) {
  245. if (bot_ferts.isSet(i)) {
  246. s += " " + String(i + 1);
  247. }
  248. }
  249. s += "\nPlants:";
  250. for (int i = 0; i < (VALVE_COUNT - 1); i++) {
  251. if (bot_plants.isSet(i)) {
  252. s += " " + String(i + 1);
  253. }
  254. }
  255. s += "\nOk? Send /begin to start or /abort to cancel.";
  256. bot_state = BOT_ASKED_CONFIRM;
  257. bot.sendMessage(bot.messages[message_id].chat_id, s, "");
  258. } else if (bot_state == BOT_ASKED_CONFIRM) {
  259. if (bot.messages[message_id].text == "/abort") {
  260. bot_state = BOT_IDLE;
  261. bot_lock = "";
  262. bot.sendMessage(bot.messages[message_id].chat_id, "Aborted.", "");
  263. } else if (bot.messages[message_id].text == "/begin") {
  264. bot_state = BOT_IDLE;
  265. bot_lock = "";
  266. bot.sendMessage(bot.messages[message_id].chat_id, "Auto watering cycle started.", "");
  267. sm_bot_start_auto(bot_ferts, bot_plants);
  268. } else {
  269. bot_state = BOT_IDLE;
  270. bot_lock = "";
  271. bot.sendMessage(bot.messages[message_id].chat_id, "Unknown message.\nAborted.", "");
  272. }
  273. } else {
  274. debug.println("Telegram: invalid state");
  275. bot_state = BOT_IDLE;
  276. bot_lock = "";
  277. bot.sendMessage(bot.messages[message_id].chat_id, "Internal error.\nPlease try again.", "");
  278. }
  279. }
  280. void telegram_handler(int message_id) {
  281. debug.println("Telegram: rx " + bot.messages[message_id].chat_id + " \"" + bot.messages[message_id].text + "\"");
  282. bool found = false;
  283. for (int n = 0; n < (sizeof(trusted_chat_ids) / sizeof(trusted_chat_ids[0])); n++) {
  284. if (trusted_chat_ids[n] == bot.messages[message_id].chat_id) {
  285. found = true;
  286. break;
  287. }
  288. }
  289. if (!found) {
  290. bot.sendMessage(bot.messages[message_id].chat_id, "Sorry, not authorized!", "");
  291. return;
  292. }
  293. telegram_handle_message(message_id);
  294. }
  295. void telegram_poll() {
  296. #ifdef TELEGRAM_LOG_TIMINGS
  297. unsigned long start = millis();
  298. #endif // TELEGRAM_LOG_TIMINGS
  299. while (int count = bot.getUpdates(bot.last_message_received + 1)) {
  300. for (int i = 0; i < count; i++) {
  301. telegram_handler(i);
  302. }
  303. }
  304. #ifdef TELEGRAM_LOG_TIMINGS
  305. unsigned long end = millis();
  306. debug.println("Telegram: took " + String(end - start) + "ms");
  307. #endif // TELEGRAM_LOG_TIMINGS
  308. }
  309. void telegram_hello() {
  310. for (int n = 0; n < (sizeof(trusted_chat_ids) / sizeof(trusted_chat_ids[0])); n++) {
  311. bot.sendMessage(trusted_chat_ids[n], "Giess-o-mat v" FIRMWARE_VERSION " initialized.\nSend /auto to begin.", "");
  312. }
  313. }
  314. #endif // TELEGRAM_TOKEN
  315. #ifdef MQTT_HOST
  316. static void mqttCallback(char* topic, byte* payload, unsigned int length) {
  317. String ts(topic), ps;
  318. for (unsigned int i = 0; i < length; i++) {
  319. char c = payload[i];
  320. ps += c;
  321. }
  322. debug.println("MQTT Rx @ " + ts + ": " + ps);
  323. if (ts != "giessomat") {
  324. debug.println("MQTT: invalid topic");
  325. return;
  326. }
  327. if (ps == "abort") {
  328. if (sm_is_idle()) {
  329. debug.println("MQTT: nothing to abort");
  330. } else {
  331. sm_bot_abort();
  332. debug.println("MQTT: user abort");
  333. }
  334. } else {
  335. if (ps.substring(0, 6) == "state:") {
  336. return;
  337. }
  338. if (ps.substring(0, 4) != "auto") {
  339. debug.println("MQTT: invalid payload");
  340. return;
  341. }
  342. if (!sm_is_idle()) {
  343. debug.println("MQTT: machine is in use");
  344. return;
  345. }
  346. bot_ferts.clear();
  347. bot_plants.clear();
  348. String buff;
  349. bool at_plants = false;
  350. for (int i = 5; i < ps.length() + 1; i++) {
  351. if ((i == ps.length()) || (ps[i] == ' ') || (ps[i] == ',')) {
  352. if (buff != "none") {
  353. int n = buff.toInt() - 1;
  354. if (!at_plants) {
  355. bot_ferts.set(n);
  356. } else {
  357. bot_plants.set(n);
  358. }
  359. }
  360. buff = "";
  361. if ((i < ps.length()) && (ps[i] == ' ')) {
  362. at_plants = true;
  363. }
  364. } else {
  365. buff += ps[i];
  366. }
  367. }
  368. String s = "MQTT: fertilizers:";
  369. for (int i = 0; i < PUMP_COUNT; i++) {
  370. if (bot_ferts.isSet(i)) {
  371. s += " " + String(i + 1);
  372. }
  373. }
  374. debug.println(s);
  375. s = "MQTT: plants:";
  376. for (int i = 0; i < (VALVE_COUNT - 1); i++) {
  377. if (bot_plants.isSet(i)) {
  378. s += " " + String(i + 1);
  379. }
  380. }
  381. debug.println(s);
  382. if (bot_plants.countSet() <= 0) {
  383. debug.println("MQTT: no plants selected");
  384. return;
  385. }
  386. #ifdef FULLAUTO_MIN_PLANT_COUNT
  387. if (bot_plants.countSet() < FULLAUTO_MIN_PLANT_COUNT) {
  388. debug.println("MQTT: not enough plants selected");
  389. return;
  390. }
  391. #endif
  392. sm_bot_start_auto(bot_ferts, bot_plants);
  393. }
  394. }
  395. static void mqttReconnect() {
  396. // Create a random client ID
  397. String clientId = F("giessomat-");
  398. clientId += String(random(0xffff), HEX);
  399. // Attempt to connect
  400. #if defined(MQTT_USER) && defined(MQTT_PASS)
  401. if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) {
  402. #else
  403. if (mqtt.connect(clientId.c_str())) {
  404. #endif
  405. mqtt.subscribe("giessomat");
  406. }
  407. }
  408. #endif // MQTT_HOST
  409. bool wifi_write_database(int duration, const char *type, int id) {
  410. bool success = false;
  411. #ifdef ENABLE_INFLUXDB_LOGGING
  412. // we still want to be locally usable / have a snappy ui
  413. // even when the wifi connection is broken.
  414. if (WiFi.status() != WL_CONNECTED) {
  415. debug.println("Won't attempt db write, no WiFi connection.");
  416. return success;
  417. }
  418. InfluxData measurement(type);
  419. measurement.addTag("version", FIRMWARE_VERSION);
  420. measurement.addTag("device", WiFi.macAddress());
  421. measurement.addTag("id", String(id));
  422. measurement.addValue("duration", duration);
  423. success = influx.write(measurement);
  424. #endif // ENABLE_INFLUXDB_LOGGING
  425. if (!success) {
  426. debug.print("Error writing to InfluxDB ");
  427. debug.print(INFLUXDB_HOST);
  428. debug.print(":");
  429. debug.print(INFLUXDB_PORT);
  430. debug.print("/");
  431. debug.print(INFLUXDB_DATABASE);
  432. debug.print("/");
  433. debug.println(type);
  434. }
  435. return success;
  436. }
  437. void wifi_set_message_buffer(String a, String b, String c, String d) {
  438. message_buffer_a = a;
  439. message_buffer_b = b;
  440. message_buffer_c = c;
  441. message_buffer_d = d;
  442. }
  443. void wifi_schedule_websocket(void) {
  444. last_websocket_update_time = 0;
  445. }
  446. void wifi_send_status_broadcast(void) {
  447. if (WiFi.status() != WL_CONNECTED) {
  448. return;
  449. }
  450. if (socket.connectedClients() <= 0) {
  451. return;
  452. }
  453. String a = message_buffer_a ;
  454. String b = message_buffer_b;
  455. String c = message_buffer_c;
  456. String d = message_buffer_d;
  457. a.replace("\"", "'");
  458. b.replace("\"", "'");
  459. c.replace("\"", "'");
  460. d.replace("\"", "'");
  461. String ws = "{\n";
  462. ws += "\"a\": \"" + a + "\",\n";
  463. ws += "\"b\": \"" + b + "\",\n";
  464. ws += "\"c\": \"" + c + "\",\n";
  465. ws += "\"d\": \"" + d + "\",\n";
  466. ws += "\"state\": \"" + String(control_state_name()) + "\",\n";
  467. ws += F("\"valves\": [ ");
  468. for (int i = 0; i < VALVE_COUNT; i++) {
  469. ws += "\"";
  470. ws += get_plants()->getValves()->getPin(i) ? "1" : "0";
  471. ws += "\"";
  472. if (i < (VALVE_COUNT - 1)) {
  473. ws += ", ";
  474. }
  475. }
  476. ws += " ],\n";
  477. ws += F("\"pumps\": [ ");
  478. for (int i = 0; i < PUMP_COUNT; i++) {
  479. ws += "\"";
  480. ws += get_plants()->getPumps()->getPin(i) ? "1" : "0";
  481. ws += "\"";
  482. if (i < (PUMP_COUNT - 1)) {
  483. ws += ", ";
  484. }
  485. }
  486. ws += " ],\n";
  487. ws += F("\"switches\": [ ");
  488. for (int i = 0; i < SWITCH_COUNT; i++) {
  489. bool v = get_plants()->getSwitches()->getPin(i);
  490. #ifdef INVERT_SENSOR_BOTTOM
  491. if (i == 0) {
  492. v = !v;
  493. }
  494. #endif // INVERT_SENSOR_BOTTOM
  495. #ifdef INVERT_SENSOR_TOP
  496. if (i == 1) {
  497. v = !v;
  498. }
  499. #endif // INVERT_SENSOR_TOP
  500. ws += "\"";
  501. ws += v ? "1" : "0";
  502. ws += "\"";
  503. if (i < (SWITCH_COUNT - 1)) {
  504. ws += ", ";
  505. }
  506. }
  507. ws += " ],\n";
  508. ws += F("\"aux\": [ ");
  509. for (int i = 0; i < AUX_COUNT; i++) {
  510. ws += "\"";
  511. ws += get_plants()->getAux()->getPin(i) ? "1" : "0";
  512. ws += "\"";
  513. if (i < (AUX_COUNT - 1)) {
  514. ws += ", ";
  515. }
  516. }
  517. ws += " ],\n";
  518. ws += F("\"kickstart\": [ ");
  519. for (int i = 0; i < VALVE_COUNT - 1; i++) {
  520. ws += "\"";
  521. ws += get_plants()->getKickstart()->getPin(i) ? "1" : "0";
  522. ws += "\"";
  523. if (i < (VALVE_COUNT - 2)) {
  524. ws += ", ";
  525. }
  526. }
  527. ws += " ],\n";
  528. ws += "\"switchstate\": \"";
  529. Plants::Waterlevel wl = get_plants()->getWaterlevel();
  530. if (wl == Plants::empty) {
  531. ws += F("tank empty");
  532. } else if (wl == Plants::inbetween) {
  533. ws += F("tank half-filled");
  534. } else if (wl == Plants::full) {
  535. ws += F("tank full");
  536. } else {
  537. ws += F("invalid sensor state");
  538. }
  539. ws += "\"\n";
  540. ws += "}";
  541. wifi_send_websocket(ws);
  542. }
  543. void wifi_send_websocket(String s) {
  544. socket.broadcastTXT(s);
  545. }
  546. #ifdef ARDUINO_ARCH_ESP32
  547. #include <rom/rtc.h>
  548. // https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/ResetReason/ResetReason.ino
  549. static const char *str_reset_reason(int reason) {
  550. switch (reason) {
  551. case 1:
  552. return "POWERON_RESET";
  553. case 3:
  554. return "SW_RESET";
  555. case 4:
  556. return "OWDT_RESET";
  557. case 5:
  558. return "DEEPSLEEP_RESET";
  559. case 6:
  560. return "SDIO_RESET";
  561. case 7:
  562. return "TG0WDT_SYS_RESET";
  563. case 8:
  564. return "TG1WDT_SYS_RESET";
  565. case 9:
  566. return "RTCWDT_SYS_RESET";
  567. case 10:
  568. return "INTRUSION_RESET";
  569. case 11:
  570. return "TGWDT_CPU_RESET";
  571. case 12:
  572. return "SW_CPU_RESET";
  573. case 13:
  574. return "RTCWDT_CPU_RESET";
  575. case 14:
  576. return "EXT_CPU_RESET";
  577. case 15:
  578. return "RTCWDT_BROWN_OUT_RESET";
  579. case 16:
  580. return "RTCWDT_RTC_RESET";
  581. default:
  582. return "NO_MEAN";
  583. }
  584. }
  585. #endif // ARDUINO_ARCH_ESP32
  586. void handleRoot() {
  587. String message = F("<!DOCTYPE html>\n");
  588. message += F("<html><head>\n");
  589. message += F("<meta charset='utf-8'/>\n");
  590. message += F("<meta name='viewport' content='width=device-width, initial-scale=1'/>\n");
  591. message += F("<title>Gieß-o-mat</title>\n");
  592. message += F("<style type='text/css'>\n");
  593. message += F(".head {\n");
  594. message += F("text-align: center;\n");
  595. message += F("}\n");
  596. message += F(".container {\n");
  597. message += F("display: flex;\n");
  598. message += F("max-width: 1200px;\n");
  599. message += F("margin: auto;\n");
  600. message += F("}\n");
  601. message += F(".ui {\n");
  602. message += F("width: max-content;\n");
  603. message += F("height: max-content;\n");
  604. message += F("margin-right: 1em;\n");
  605. message += F("padding: 0 1.0em;\n");
  606. message += F("border: 1px dashed black;\n");
  607. message += F("}\n");
  608. message += F(".io {\n");
  609. message += F("width: max-content;\n");
  610. message += F("height: max-content;\n");
  611. message += F("margin-right: 1em;\n");
  612. message += F("padding: 0.8em 1.0em;\n");
  613. message += F("border: 1px dashed black;\n");
  614. message += F("font-family: monospace;\n");
  615. message += F("}\n");
  616. message += F(".ioelem {\n");
  617. message += F("width: max-content;\n");
  618. message += F("border: 1px solid black;\n");
  619. message += F("border-radius: 50%;\n");
  620. message += F("padding: 1em;\n");
  621. message += F("margin: 0.5em;\n");
  622. message += F("}\n");
  623. message += F(".info {\n");
  624. message += F("width: max-content;\n");
  625. message += F("height: max-content;\n");
  626. message += F("padding: 0 1.0em;\n");
  627. message += F("border: 1px dashed black;\n");
  628. message += F("font-family: monospace;\n");
  629. message += F("}\n");
  630. message += F(".log {\n");
  631. message += F("max-height: 300px;\n");
  632. message += F("padding: 0 1.0em;\n");
  633. message += F("max-width: 1200px;\n");
  634. message += F("margin: auto;\n");
  635. message += F("margin-top: 1.5em;\n");
  636. message += F("border: 1px dashed black;\n");
  637. message += F("font-family: monospace;\n");
  638. message += F("overflow-y: scroll;\n");
  639. message += F("word-break: break-all;\n");
  640. message += F("}\n");
  641. message += F("#logbuf {\n");
  642. message += F("white-space: break-spaces;\n");
  643. message += F("}\n");
  644. message += F(".pad {\n");
  645. message += F("background: black;\n");
  646. message += F("border: 3px solid black;\n");
  647. message += F("border-radius: 20px;\n");
  648. message += F("width: max-content;\n");
  649. message += F("padding: 1.5em;\n");
  650. message += F("margin-left: auto;\n");
  651. message += F("margin-right: auto;\n");
  652. message += F("}\n");
  653. message += F(".pad input {\n");
  654. message += F("background: #fff0cf;\n");
  655. message += F("border-radius: 6px;\n");
  656. message += F("font-weight: bold;\n");
  657. message += F("font-family: monospace;\n");
  658. message += F("font-size: 1.2em;\n");
  659. message += F("padding: 0.5em 1em;\n");
  660. message += F("margin: 0.5em;\n");
  661. message += F("}\n");
  662. // https://codepen.io/hawkz/pres/RpPaGK
  663. message += F(".lcd {\n");
  664. //message += F("background: #9ea18c;\n");
  665. message += F("background: #9ed18c;\n");
  666. message += F("border: 5px solid black;\n");
  667. message += F("border-radius: 10px;\n");
  668. message += F("width: max-content;\n");
  669. message += F("padding: 0.65em 1em;\n");
  670. message += F("box-shadow: inset 0 0 5px 5px rgba(0,0,0,.1);\n");
  671. message += F("font-weight: bold;\n");
  672. message += F("font-family: monospace;\n");
  673. message += F("letter-spacing: 0.1em;\n");
  674. message += F("font-size: 1.2em;\n");
  675. message += F("line-height: 160%;\n");
  676. message += F("color: #21230e;\n");
  677. message += F("text-shadow: -1px 2px 1px rgba(0,0,0,.1);\n");
  678. message += F("margin-left: auto;\n");
  679. message += F("margin-right: auto;\n");
  680. message += F("}\n");
  681. message += F("#state {\n");
  682. message += F("text-align: center;\n");
  683. message += F("}\n");
  684. message += F("@media (prefers-color-scheme: dark) {\n");
  685. message += F("body {\n");
  686. message += F("background-color: black;\n");
  687. message += F("color: white;\n");
  688. message += F("}\n");
  689. message += F(".ui {\n");
  690. message += F("border: 1px dashed white;\n");
  691. message += F("}\n");
  692. message += F(".io {\n");
  693. message += F("border: 1px dashed white;\n");
  694. message += F("}\n");
  695. message += F(".ioelem {\n");
  696. message += F("border: 1px solid white;\n");
  697. message += F("}\n");
  698. message += F(".info {\n");
  699. message += F("border: 1px dashed white;\n");
  700. message += F("}\n");
  701. message += F(".log {\n");
  702. message += F("border: 1px dashed white;\n");
  703. message += F("}\n");
  704. message += F(".pad {\n");
  705. message += F("background: #222222;\n");
  706. message += F("border: 3px solid white;\n");
  707. message += F("}\n");
  708. message += F(".lcd {\n");
  709. message += F("border: 5px solid white;\n");
  710. message += F("}\n");
  711. message += F("}\n");
  712. message += F("</style>\n");
  713. message += F("</head><body>\n");
  714. message += F("<h1 class='head'>Gieß-o-mat</h1>\n");
  715. message += F("<div class='container'>\n");
  716. message += F("<div class='ui'>\n");
  717. message += F("<pre class='lcd'>\n");
  718. message += message_buffer_a + '\n';
  719. message += message_buffer_b + '\n';
  720. message += message_buffer_c + '\n';
  721. message += message_buffer_d + '\n';
  722. message += F("</pre>\n");
  723. message += F("<form class='pad'>\n");
  724. message += F("<input type='button' value='1'>");
  725. message += F("<input type='button' value='2'>");
  726. message += F("<input type='button' value='3'>");
  727. message += F("<br>\n");
  728. message += F("<input type='button' value='4'>");
  729. message += F("<input type='button' value='5'>");
  730. message += F("<input type='button' value='6'>");
  731. message += F("<br>\n");
  732. message += F("<input type='button' value='7'>");
  733. message += F("<input type='button' value='8'>");
  734. message += F("<input type='button' value='9'>");
  735. message += F("<br>\n");
  736. message += F("<input type='button' value='*'>");
  737. message += F("<input type='button' value='0'>");
  738. message += F("<input type='button' value='#'>");
  739. message += F("</form>\n");
  740. message += F("<p id='state'>\n");
  741. message += F("State: ");
  742. message += control_state_name();
  743. message += F("</p></div>\n");
  744. message += F("<div class='io'>\n");
  745. message += F("Switches: <span id='switchstate'>");
  746. Plants::Waterlevel wl = get_plants()->getWaterlevel();
  747. if (wl == Plants::empty) {
  748. message += F("tank empty");
  749. } else if (wl == Plants::inbetween) {
  750. message += F("tank half-filled");
  751. } else if (wl == Plants::full) {
  752. message += F("tank full");
  753. } else {
  754. message += F("invalid sensor state");
  755. }
  756. message += F("</span>");
  757. message += F("<div class='container'>\n");
  758. for (int i = 0; i < SWITCH_COUNT; i++) {
  759. message += F("<div class='ioelem switch' style='background-color: ");
  760. bool v = get_plants()->getSwitches()->getPin(i);
  761. #ifdef INVERT_SENSOR_BOTTOM
  762. if (i == 0) {
  763. v = !v;
  764. }
  765. #endif // INVERT_SENSOR_BOTTOM
  766. #ifdef INVERT_SENSOR_TOP
  767. if (i == 1) {
  768. v = !v;
  769. }
  770. #endif // INVERT_SENSOR_TOP
  771. if (v) {
  772. message += F("red");
  773. } else {
  774. message += F("green");
  775. }
  776. message += F(";'>S");
  777. message += String(i + 1);
  778. message += F("</div>");
  779. }
  780. message += F("</div><hr>\n");
  781. message += F("Kickstart:\n");
  782. message += F("<div class='container'>\n");
  783. for (int i = 0; i < VALVE_COUNT - 1; i++) {
  784. message += F("<div class='ioelem kickstart' style='background-color: ");
  785. if (get_plants()->getKickstart()->getPin(i)) {
  786. message += F("red");
  787. } else {
  788. message += F("green");
  789. }
  790. message += F(";'>A");
  791. message += String(i + 1);
  792. message += F("</div>");
  793. }
  794. message += F("</div><hr>\n");
  795. message += F("Valves:\n");
  796. message += F("<div class='container'>\n");
  797. for (int i = 0; i < VALVE_COUNT; i++) {
  798. message += F("<div class='ioelem valve' style='background-color: ");
  799. if (get_plants()->getValves()->getPin(i)) {
  800. message += F("red");
  801. } else {
  802. message += F("green");
  803. }
  804. message += F(";'>V");
  805. message += String(i + 1);
  806. message += F("</div>");
  807. }
  808. message += F("</div><hr>\n");
  809. message += F("Pumps:\n");
  810. message += F("<div class='container'>\n");
  811. for (int i = 0; i < PUMP_COUNT; i++) {
  812. message += F("<div class='ioelem pump' style='background-color: ");
  813. if (get_plants()->getPumps()->getPin(i)) {
  814. message += F("red");
  815. } else {
  816. message += F("green");
  817. }
  818. message += F(";'>P");
  819. message += String(i + 1);
  820. message += F("</div>");
  821. }
  822. message += F("</div><hr>\n");
  823. message += F("Aux:\n");
  824. message += F("<div class='container'>\n");
  825. for (int i = 0; i < AUX_COUNT; i++) {
  826. message += F("<div class='ioelem aux' style='background-color: ");
  827. if (get_plants()->getAux()->getPin(i)) {
  828. message += F("red");
  829. } else {
  830. message += F("green");
  831. }
  832. message += F(";'>A");
  833. message += String(i + 1);
  834. message += F("</div>");
  835. }
  836. message += F("</div><hr>\n");
  837. message += F("Green means valve is closed / pump is off / switch is not submersed.\n");
  838. message += F("<br>\n");
  839. message += F("Red means valve is open / pump is running / switch is submersed.</div>\n");
  840. message += F("<div class='info'><p>\n");
  841. message += F("Version: ");
  842. message += FIRMWARE_VERSION;
  843. message += F("\n<br>\n");
  844. message += F("Build Date: ");
  845. message += __DATE__;
  846. message += F("\n<br>\n");
  847. message += F("Build Time: ");
  848. message += __TIME__;
  849. message += F("\n</p><p>\n");
  850. message += F("MAC: ");
  851. message += WiFi.macAddress();
  852. message += F("\n<br>\n");
  853. message += F("IPv4: ");
  854. message += WiFi.localIP().toString();
  855. message += F("\n</p>\n");
  856. #if defined(ARDUINO_ARCH_ESP8266)
  857. message += F("\n<p>\n");
  858. message += F("Reset reason: ");
  859. message += ESP.getResetReason();
  860. message += F("\n<br>\n");
  861. message += F("Free heap: ");
  862. message += String(ESP.getFreeHeap());
  863. message += F(" (");
  864. message += String(ESP.getHeapFragmentation());
  865. message += F("% fragmentation)");
  866. message += F("\n<br>\n");
  867. message += F("Free sketch space: ");
  868. message += String(ESP.getFreeSketchSpace());
  869. message += F("\n<br>\n");
  870. message += F("Flash chip real size: ");
  871. message += String(ESP.getFlashChipRealSize());
  872. if (ESP.getFlashChipSize() != ESP.getFlashChipRealSize()) {
  873. message += F("\n<br>\n");
  874. message += F("WARNING: sdk chip size (");
  875. message += (ESP.getFlashChipSize());
  876. message += F(") does not match!");
  877. }
  878. message += F("\n</p>\n");
  879. #elif defined(ARDUINO_ARCH_ESP32)
  880. message += F("\n<p>\n");
  881. message += F("Reset reason: ");
  882. message += str_reset_reason(rtc_get_reset_reason(0));
  883. message += F(" ");
  884. message += str_reset_reason(rtc_get_reset_reason(1));
  885. message += F("\n<br>\n");
  886. message += F("Free heap: ");
  887. message += String(ESP.getFreeHeap() / 1024.0);
  888. message += F("k\n<br>\n");
  889. message += F("Free sketch space: ");
  890. message += String(ESP.getFreeSketchSpace() / 1024.0);
  891. message += F("k\n<br>\n");
  892. message += F("Flash chip size: ");
  893. message += String(ESP.getFlashChipSize() / 1024.0);
  894. message += F("k\n</p>\n");
  895. #endif
  896. message += F("<p>\n");
  897. #ifdef TELEGRAM_TOKEN
  898. message += F("Telegram: ");
  899. message += TELEGRAM_UPDATE_INTERVAL_SLOW;
  900. message += F("ms / ");
  901. message += TELEGRAM_UPDATE_INTERVAL_FAST;
  902. message += F("ms\n");
  903. #else
  904. message += F("Telegram bot not enabled!\n");
  905. #endif
  906. message += F("</p>\n");
  907. message += F("<p>\n");
  908. #ifdef MQTT_HOST
  909. message += F("MQTT: ");
  910. message += MQTT_HOST;
  911. message += F(":");
  912. message += String(MQTT_PORT);
  913. message += F("\n");
  914. #else
  915. message += F("MQTT not enabled!\n");
  916. #endif
  917. message += F("</p>\n");
  918. message += F("<p>\n");
  919. #ifdef ENABLE_INFLUXDB_LOGGING
  920. message += F("InfluxDB: ");
  921. message += INFLUXDB_DATABASE;
  922. message += F(" @ ");
  923. message += INFLUXDB_HOST;
  924. message += F(":");
  925. message += String(INFLUXDB_PORT);
  926. message += F("\n");
  927. #else
  928. message += F("InfluxDB logging not enabled!\n");
  929. #endif
  930. message += F("</p>\n");
  931. message += F("<p>Try <a href='/update'>/update</a> for OTA firmware updates!</p>\n");
  932. message += F("<p>Made by <a href='https://xythobuz.de'>xythobuz</a></p>\n");
  933. message += F("<p><a href='https://git.xythobuz.de/thomas/giess-o-mat'>Project Repository</a></p>\n");
  934. #ifdef ENABLE_GPIO_TEST
  935. message += F("<p><a href='/gpiotest'>GPIO Test</a></p>\n");
  936. #endif // ENABLE_GPIO_TEST
  937. message += F("</div></div>\n");
  938. message += F("<div class='log'><pre id='logbuf'>\n");
  939. message += debug.getBuffer();
  940. message += F("</pre></div>\n");
  941. message += F("</body>\n");
  942. message += F("<script type='text/javascript'>\n");
  943. message += F("var socket = new WebSocket('ws://' + window.location.hostname + ':81');\n");
  944. message += F("socket.onmessage = function(e) {\n");
  945. message += F( "if (e.data.startsWith('log:')) {\n");
  946. message += F( "var log = document.getElementById('logbuf');\n");
  947. message += F( "var div = document.getElementsByClassName('log')[0];\n");
  948. message += F( "log.innerHTML += e.data.substring(4);\n");
  949. message += F( "if (log.innerHTML.length > (1024 * 1024)) {\n");
  950. message += F( "log.innerHTML = log.innerHTML.substring(1024 * 1024);\n");
  951. message += F( "}\n");
  952. message += F( "div.scrollTop = div.scrollHeight;\n");
  953. message += F( "return;\n");
  954. message += F( "}\n");
  955. message += F( "var msg = JSON.parse(e.data);\n");
  956. message += F( "var str = msg.a + '\\n' + msg.b + '\\n' + msg.c + '\\n' + msg.d;\n");
  957. //message += F( "console.log(str);\n");
  958. message += F( "var lcd = document.getElementsByClassName('lcd');\n");
  959. message += F( "lcd[0].innerHTML = str;\n");
  960. message += F( "var state = document.getElementById('state');\n");
  961. message += F( "state.innerHTML = \"State: \" + msg.state;\n");
  962. message += F( "for (let i = 0; i < ");
  963. message += String(VALVE_COUNT);
  964. message += F("; i++) {\n");
  965. message += F( "var valves = document.getElementsByClassName('valve');\n");
  966. message += F( "if (msg.valves[i] == '0') {\n");
  967. message += F( "valves[i].style = 'background-color: green;';\n");
  968. message += F( "} else {\n");
  969. message += F( "valves[i].style = 'background-color: red;';\n");
  970. message += F( "}\n");
  971. message += F( "}\n");
  972. message += F( "for (let i = 0; i < ");
  973. message += String(PUMP_COUNT);
  974. message += F("; i++) {\n");
  975. message += F( "var pumps = document.getElementsByClassName('pump');\n");
  976. message += F( "if (msg.pumps[i] == '0') {\n");
  977. message += F( "pumps[i].style = 'background-color: green;';\n");
  978. message += F( "} else {\n");
  979. message += F( "pumps[i].style = 'background-color: red;';\n");
  980. message += F( "}\n");
  981. message += F( "}\n");
  982. message += F( "for (let i = 0; i < ");
  983. message += String(SWITCH_COUNT);
  984. message += F("; i++) {\n");
  985. message += F( "var switches = document.getElementsByClassName('switch');\n");
  986. message += F( "if (msg.switches[i] == '0') {\n");
  987. message += F( "switches[i].style = 'background-color: green;';\n");
  988. message += F( "} else {\n");
  989. message += F( "switches[i].style = 'background-color: red;';\n");
  990. message += F( "}\n");
  991. message += F( "}\n");
  992. message += F( "for (let i = 0; i < ");
  993. message += String(AUX_COUNT);
  994. message += F("; i++) {\n");
  995. message += F( "var aux = document.getElementsByClassName('aux');\n");
  996. message += F( "if (msg.aux[i] == '0') {\n");
  997. message += F( "aux[i].style = 'background-color: green;';\n");
  998. message += F( "} else {\n");
  999. message += F( "aux[i].style = 'background-color: red;';\n");
  1000. message += F( "}\n");
  1001. message += F( "}\n");
  1002. message += F( "for (let i = 0; i < ");
  1003. message += String(VALVE_COUNT - 1);
  1004. message += F("; i++) {\n");
  1005. message += F( "var kickstart = document.getElementsByClassName('kickstart');\n");
  1006. message += F( "if (msg.kickstart[i] == '0') {\n");
  1007. message += F( "kickstart[i].style = 'background-color: green;';\n");
  1008. message += F( "} else {\n");
  1009. message += F( "kickstart[i].style = 'background-color: red;';\n");
  1010. message += F( "}\n");
  1011. message += F( "}\n");
  1012. message += F( "var switchstate = document.getElementById('switchstate');\n");
  1013. message += F( "switchstate.innerHTML = msg.switchstate;\n");
  1014. message += F("};\n");
  1015. message += F("var hist = document.getElementsByClassName('log')[0];\n");
  1016. message += F("hist.scrollTop = hist.scrollHeight;\n");
  1017. message += F("var buttons = document.getElementsByTagName('input');\n");
  1018. message += F("for (let i = 0; i < buttons.length; i++) {\n");
  1019. message += F( "buttons[i].addEventListener('click', updateButton);\n");
  1020. message += F("}\n");
  1021. message += F("function updateButton() {\n");
  1022. message += F( "socket.send(this.value);\n");
  1023. message += F("}\n");
  1024. message += F("</script>\n");
  1025. message += F("</html>\n");
  1026. server.send(200, "text/html", message);
  1027. }
  1028. void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  1029. if ((type != WStype_TEXT) || (length != 1)) {
  1030. debug.println("Websocket: invalid type=" + String(type) + " len=" + String(length) /* + " data=" + String((char *)payload) */ );
  1031. return;
  1032. }
  1033. char c = payload[0];
  1034. if ((c >= '0') && (c <= '9')) {
  1035. control_act_input(c - '0');
  1036. } else if (c == '*') {
  1037. control_act_input(-1);
  1038. } else if (c == '#') {
  1039. control_act_input(-2);
  1040. }
  1041. }
  1042. void wifi_setup() {
  1043. // Build hostname string
  1044. String hostname = "giess-o-mat";
  1045. int ws = 0, connect_attempts = 0;
  1046. #if defined(ARDUINO_ARCH_ESP8266)
  1047. // Connect to WiFi AP
  1048. debug.println("WiFi: initializing");
  1049. WiFi.hostname(hostname);
  1050. WiFi.mode(WIFI_STA);
  1051. debug.print("WiFi: connecting");
  1052. WiFi.begin(WIFI_SSID, WIFI_PW);
  1053. #ifdef TELEGRAM_TOKEN
  1054. secured_client.setTrustAnchors(&cert);
  1055. #endif // TELEGRAM_TOKEN
  1056. while (((ws = WiFi.status()) != WL_CONNECTED) && (connect_attempts < MAX_WIFI_CONNECT_ATTEMPTS)) {
  1057. connect_attempts++;
  1058. debug.print(String(" ") + String(ws));
  1059. delay(LED_CONNECT_BLINK_INTERVAL);
  1060. digitalWrite(BUILTIN_LED_PIN, !digitalRead(BUILTIN_LED_PIN));
  1061. }
  1062. debug.println();
  1063. debug.println(String("WiFi: status=") + String(WiFi.status()));
  1064. #elif defined(ARDUINO_ARCH_ESP32)
  1065. // Set hostname workaround
  1066. debug.println("WiFi: set hostname");
  1067. WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
  1068. WiFi.setHostname(hostname.c_str());
  1069. // Workaround for WiFi connecting only every 2nd reset
  1070. // https://github.com/espressif/arduino-esp32/issues/2501#issuecomment-513602522
  1071. debug.println("WiFi: connection work-around");
  1072. WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info) {
  1073. if (info.disconnected.reason == 202) {
  1074. esp_sleep_enable_timer_wakeup(10);
  1075. esp_deep_sleep_start();
  1076. delay(100);
  1077. }
  1078. }, WiFiEvent_t::SYSTEM_EVENT_STA_DISCONNECTED);
  1079. // Connect to WiFi AP
  1080. debug.println("WiFi: SSID=" WIFI_SSID);
  1081. debug.print("WiFi: connecting");
  1082. WiFi.mode(WIFI_STA);
  1083. WiFi.begin(WIFI_SSID, WIFI_PW);
  1084. #ifdef TELEGRAM_TOKEN
  1085. secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
  1086. #endif // TELEGRAM_TOKEN
  1087. while (((ws = WiFi.status()) != WL_CONNECTED) && (connect_attempts < MAX_WIFI_CONNECT_ATTEMPTS)) {
  1088. connect_attempts++;
  1089. debug.print(String(" ") + String(ws));
  1090. delay(LED_CONNECT_BLINK_INTERVAL);
  1091. digitalWrite(BUILTIN_LED_PIN, !digitalRead(BUILTIN_LED_PIN));
  1092. }
  1093. debug.println();
  1094. debug.println(String("WiFi: status=") + String(WiFi.status()));
  1095. // Set hostname workaround
  1096. debug.println("WiFi: set hostname work-around");
  1097. WiFi.setHostname(hostname.c_str());
  1098. #endif
  1099. if ((connect_attempts >= MAX_WIFI_CONNECT_ATTEMPTS)
  1100. || (WiFi.status() != WL_CONNECTED)) {
  1101. debug.println("WiFi: init failed!");
  1102. wifi_ok = 0;
  1103. return;
  1104. }
  1105. wifi_ok = 1;
  1106. debug.print("WiFi: got IPv4: ");
  1107. debug.println(WiFi.localIP().toString());
  1108. #ifdef ENABLE_INFLUXDB_LOGGING
  1109. // Setup InfluxDB Client
  1110. debug.println("WiFi: set InfluxDB database");
  1111. influx.setDb(INFLUXDB_DATABASE);
  1112. #endif // ENABLE_INFLUXDB_LOGGING
  1113. // Setup HTTP Server
  1114. debug.println("WiFi: initializing HTTP server");
  1115. MDNS.begin(hostname.c_str());
  1116. updater.setup(&server);
  1117. server.on("/", handleRoot);
  1118. #ifdef ENABLE_GPIO_TEST
  1119. server.on("/gpiotest", handleGpioTest);
  1120. #endif // ENABLE_GPIO_TEST
  1121. #ifdef TELEGRAM_TOKEN
  1122. debug.print("WiFi: getting NTP time");
  1123. configTime(0, 0, "pool.ntp.org");
  1124. time_t now = time(nullptr);
  1125. while (now < 24 * 60 * 60) {
  1126. debug.print(".");
  1127. delay(100);
  1128. now = time(nullptr);
  1129. }
  1130. debug.println(" done!");
  1131. debug.println("WiFi: time is " + String(now));
  1132. debug.println("WiFi: initializing Telegram");
  1133. const String commands = F("["
  1134. "{\"command\":\"auto\", \"description\":\"Start automatic watering cycle\"},"
  1135. "{\"command\":\"confirm\", \"description\":\"Proceed with any menu inputs\"},"
  1136. "{\"command\":\"none\", \"description\":\"Proceed without menu input\"},"
  1137. "{\"command\":\"abort\", \"description\":\"Cancel any menu inputs\"}"
  1138. "]");
  1139. bot.setMyCommands(commands);
  1140. telegram_hello();
  1141. #endif // TELEGRAM_TOKEN
  1142. #ifdef MQTT_HOST
  1143. debug.println("WiFi: initializing MQTT");
  1144. mqtt.setServer(MQTT_HOST, MQTT_PORT);
  1145. mqtt.setCallback(mqttCallback);
  1146. #endif // MQTT_HOST
  1147. server.begin();
  1148. MDNS.addService("http", "tcp", 80);
  1149. MDNS.addService("http", "tcp", 81);
  1150. socket.begin();
  1151. socket.onEvent(webSocketEvent);
  1152. debug.println("WiFi: setup done");
  1153. }
  1154. void wifi_run() {
  1155. if (!wifi_ok) {
  1156. // nothing to handle
  1157. return;
  1158. }
  1159. if ((millis() - last_server_handle_time) >= SERVER_HANDLE_INTERVAL) {
  1160. last_server_handle_time = millis();
  1161. server.handleClient();
  1162. socket.loop();
  1163. #ifdef ARDUINO_ARCH_ESP8266
  1164. MDNS.update();
  1165. #endif // ARDUINO_ARCH_ESP8266
  1166. }
  1167. if ((millis() - last_websocket_update_time) >= WEBSOCKET_UPDATE_INTERVAL) {
  1168. last_websocket_update_time = millis();
  1169. wifi_send_status_broadcast();
  1170. }
  1171. #ifdef ENABLE_GPIO_TEST
  1172. if (runningGpioTest && ((millis() - lastGpioTime) >= GPIO_TEST_INTERVAL)) {
  1173. gpioTestState = !gpioTestState;
  1174. runGpioTest(gpioTestState);
  1175. }
  1176. #endif // ENABLE_GPIO_TEST
  1177. #ifdef TELEGRAM_TOKEN
  1178. if ((millis() - last_telegram_time) >= telegram_update_interval()) {
  1179. telegram_poll();
  1180. last_telegram_time = millis();
  1181. }
  1182. #endif // TELEGRAM_TOKEN
  1183. #ifdef MQTT_HOST
  1184. if (!mqtt.connected() && ((millis() - last_mqtt_reconnect_time) >= MQTT_RECONNECT_INTERVAL)) {
  1185. last_mqtt_reconnect_time = millis();
  1186. mqttReconnect();
  1187. }
  1188. mqtt.loop();
  1189. #endif // MQTT_HOST
  1190. }
  1191. #endif // PLATFORM_ESP