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 42KB

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