esp8266_p1meter.ino 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. // Bron: https://github.com/daniel-jong/esp8266_p1meter
  2. #include <FS.h>
  3. #include <EEPROM.h>
  4. #include <DNSServer.h>
  5. #include <ESP8266WiFi.h>
  6. #include <Ticker.h>
  7. #include <WiFiManager.h>
  8. #include <ESP8266mDNS.h>
  9. #include <WiFiUdp.h>
  10. #include <ArduinoOTA.h>
  11. #include <PubSubClient.h>
  12. // * Include settings
  13. #include "settings.h"
  14. // * Initiate led blinker library
  15. Ticker ticker;
  16. // * Initiate WIFI client
  17. WiFiClient espClient;
  18. // * Initiate MQTT client
  19. PubSubClient mqtt_client(espClient);
  20. // **********************************
  21. // * WIFI *
  22. // **********************************
  23. // * Gets called when WiFiManager enters configuration mode
  24. void configModeCallback(WiFiManager *myWiFiManager)
  25. {
  26. Serial.println(F("Entered config mode"));
  27. Serial.println(WiFi.softAPIP());
  28. // * If you used auto generated SSID, print it
  29. Serial.println(myWiFiManager->getConfigPortalSSID());
  30. // * Entered config mode, make led toggle faster
  31. ticker.attach(0.2, tick);
  32. }
  33. // **********************************
  34. // * Ticker (System LED Blinker) *
  35. // **********************************
  36. // * Blink on-board Led
  37. void tick()
  38. {
  39. // * Toggle state
  40. int state = digitalRead(LED_BUILTIN); // * Get the current state of GPIO1 pin
  41. digitalWrite(LED_BUILTIN, !state); // * Set pin to the opposite state
  42. }
  43. // **********************************
  44. // * MQTT *
  45. // **********************************
  46. // * Send a message to a broker topic
  47. void send_mqtt_message(const char *topic, char *payload)
  48. {
  49. Serial.printf("MQTT Outgoing on %s: ", topic);
  50. Serial.println(payload);
  51. bool result = mqtt_client.publish(topic, payload, false);
  52. if (!result)
  53. {
  54. Serial.printf("MQTT publish to topic %s failed\n", topic);
  55. }
  56. }
  57. // * Reconnect to MQTT server and subscribe to in and out topics
  58. bool mqtt_reconnect()
  59. {
  60. // * Loop until we're reconnected
  61. int MQTT_RECONNECT_RETRIES = 0;
  62. while (!mqtt_client.connected() && MQTT_RECONNECT_RETRIES < MQTT_MAX_RECONNECT_TRIES)
  63. {
  64. MQTT_RECONNECT_RETRIES++;
  65. Serial.printf("MQTT connection attempt %d / %d ...\n", MQTT_RECONNECT_RETRIES, MQTT_MAX_RECONNECT_TRIES);
  66. // * Attempt to connect
  67. if (mqtt_client.connect(HOSTNAME, MQTT_USER, MQTT_PASS))
  68. {
  69. Serial.println(F("MQTT connected!"));
  70. // * Once connected, publish an announcement...
  71. char *message = new char[16 + strlen(HOSTNAME) + 1];
  72. strcpy(message, "p1 meter alive: ");
  73. strcat(message, HOSTNAME);
  74. mqtt_client.publish("hass/status", message);
  75. Serial.printf("MQTT root topic: %s\n", MQTT_ROOT_TOPIC);
  76. }
  77. else
  78. {
  79. Serial.print(F("MQTT Connection failed: rc="));
  80. Serial.println(mqtt_client.state());
  81. Serial.println(F(" Retrying in 5 seconds"));
  82. Serial.println("");
  83. // * Wait 5 seconds before retrying
  84. delay(5000);
  85. }
  86. }
  87. if (MQTT_RECONNECT_RETRIES >= MQTT_MAX_RECONNECT_TRIES)
  88. {
  89. Serial.printf("*** MQTT connection failed, giving up after %d tries ...\n", MQTT_RECONNECT_RETRIES);
  90. return false;
  91. }
  92. return true;
  93. }
  94. void send_metric(String name, long metric)
  95. {
  96. Serial.print(F("Sending metric to broker: "));
  97. Serial.print(name);
  98. Serial.print(F("="));
  99. Serial.println(metric);
  100. char output[10];
  101. ltoa(metric, output, sizeof(output));
  102. String topic = String(MQTT_ROOT_TOPIC) + "/" + name;
  103. send_mqtt_message(topic.c_str(), output);
  104. }
  105. void send_data_to_broker()
  106. {
  107. send_metric("consumption_low_tarif", CONSUMPTION_LOW_TARIF);
  108. send_metric("consumption_high_tarif", CONSUMPTION_HIGH_TARIF);
  109. send_metric("returndelivery_low_tarif", RETURNDELIVERY_LOW_TARIF);
  110. send_metric("returndelivery_high_tarif", RETURNDELIVERY_HIGH_TARIF);
  111. send_metric("actual_consumption", ACTUAL_CONSUMPTION);
  112. send_metric("actual_returndelivery", ACTUAL_RETURNDELIVERY);
  113. send_metric("l1_instant_power_usage", L1_INSTANT_POWER_USAGE);
  114. send_metric("l2_instant_power_usage", L2_INSTANT_POWER_USAGE);
  115. send_metric("l3_instant_power_usage", L3_INSTANT_POWER_USAGE);
  116. send_metric("l1_instant_power_current", L1_INSTANT_POWER_CURRENT);
  117. send_metric("l2_instant_power_current", L2_INSTANT_POWER_CURRENT);
  118. send_metric("l3_instant_power_current", L3_INSTANT_POWER_CURRENT);
  119. send_metric("l1_voltage", L1_VOLTAGE);
  120. send_metric("l2_voltage", L2_VOLTAGE);
  121. send_metric("l3_voltage", L3_VOLTAGE);
  122. send_metric("gas_meter_m3", GAS_METER_M3);
  123. send_metric("actual_tarif_group", ACTUAL_TARIF);
  124. send_metric("short_power_outages", SHORT_POWER_OUTAGES);
  125. send_metric("long_power_outages", LONG_POWER_OUTAGES);
  126. send_metric("short_power_drops", SHORT_POWER_DROPS);
  127. send_metric("short_power_peaks", SHORT_POWER_PEAKS);
  128. }
  129. // **********************************
  130. // * P1 *
  131. // **********************************
  132. unsigned int CRC16(unsigned int crc, unsigned char *buf, int len)
  133. {
  134. for (int pos = 0; pos < len; pos++)
  135. {
  136. crc ^= (unsigned int)buf[pos]; // * XOR byte into least sig. byte of crc
  137. // * Loop over each bit
  138. for (int i = 8; i != 0; i--)
  139. {
  140. // * If the LSB is set
  141. if ((crc & 0x0001) != 0)
  142. {
  143. // * Shift right and XOR 0xA001
  144. crc >>= 1;
  145. crc ^= 0xA001;
  146. }
  147. // * Else LSB is not set
  148. else
  149. // * Just shift right
  150. crc >>= 1;
  151. }
  152. }
  153. return crc;
  154. }
  155. bool isNumber(char *res, int len)
  156. {
  157. for (int i = 0; i < len; i++)
  158. {
  159. if (((res[i] < '0') || (res[i] > '9')) && (res[i] != '.' && res[i] != 0))
  160. return false;
  161. }
  162. return true;
  163. }
  164. int FindCharInArrayRev(char array[], char c, int len)
  165. {
  166. for (int i = len - 1; i >= 0; i--)
  167. {
  168. if (array[i] == c)
  169. return i;
  170. }
  171. return -1;
  172. }
  173. long getValue(char *buffer, int maxlen, char startchar, char endchar)
  174. {
  175. int s = FindCharInArrayRev(buffer, startchar, maxlen - 2);
  176. int l = FindCharInArrayRev(buffer, endchar, maxlen - 2) - s - 1;
  177. char res[16];
  178. memset(res, 0, sizeof(res));
  179. if (strncpy(res, buffer + s + 1, l))
  180. {
  181. if (endchar == '*')
  182. {
  183. if (isNumber(res, l))
  184. // * Lazy convert float to long
  185. return (1000 * atof(res));
  186. }
  187. else if (endchar == ')')
  188. {
  189. if (isNumber(res, l))
  190. return atof(res);
  191. }
  192. }
  193. return 0;
  194. }
  195. bool decode_telegram(int len)
  196. {
  197. int startChar = FindCharInArrayRev(telegram, '/', len);
  198. int endChar = FindCharInArrayRev(telegram, '!', len);
  199. bool validCRCFound = false;
  200. for (int cnt = 0; cnt < len; cnt++) {
  201. Serial.print(telegram[cnt]);
  202. }
  203. Serial.print("\n");
  204. if (startChar >= 0)
  205. {
  206. // * Start found. Reset CRC calculation
  207. currentCRC = CRC16(0x0000,(unsigned char *) telegram+startChar, len-startChar);
  208. }
  209. else if (endChar >= 0)
  210. {
  211. // * Add to crc calc
  212. currentCRC = CRC16(currentCRC,(unsigned char*)telegram+endChar, 1);
  213. char messageCRC[5];
  214. strncpy(messageCRC, telegram + endChar + 1, 4);
  215. messageCRC[4] = 0; // * Thanks to HarmOtten (issue 5)
  216. validCRCFound = (strtol(messageCRC, NULL, 16) == currentCRC);
  217. if (validCRCFound)
  218. Serial.println(F("CRC Valid!"));
  219. else
  220. Serial.println(F("CRC Invalid!"));
  221. currentCRC = 0;
  222. }
  223. else
  224. {
  225. currentCRC = CRC16(currentCRC, (unsigned char*) telegram, len);
  226. }
  227. // 1-0:1.8.1(000992.992*kWh)
  228. // 1-0:1.8.1 = Elektra verbruik laag tarief (DSMR v4.0)
  229. if (strncmp(telegram, "1-0:1.8.1", strlen("1-0:1.8.1")) == 0)
  230. {
  231. CONSUMPTION_LOW_TARIF = getValue(telegram, len, '(', '*');
  232. }
  233. // 1-0:1.8.2(000560.157*kWh)
  234. // 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
  235. if (strncmp(telegram, "1-0:1.8.2", strlen("1-0:1.8.2")) == 0)
  236. {
  237. CONSUMPTION_HIGH_TARIF = getValue(telegram, len, '(', '*');
  238. }
  239. // 1-0:2.8.1(000560.157*kWh)
  240. // 1-0:2.8.1 = Elektra teruglevering laag tarief (DSMR v4.0)
  241. if (strncmp(telegram, "1-0:2.8.1", strlen("1-0:2.8.1")) == 0)
  242. {
  243. RETURNDELIVERY_LOW_TARIF = getValue(telegram, len, '(', '*');
  244. }
  245. // 1-0:2.8.2(000560.157*kWh)
  246. // 1-0:2.8.2 = Elektra teruglevering hoog tarief (DSMR v4.0)
  247. if (strncmp(telegram, "1-0:2.8.2", strlen("1-0:2.8.2")) == 0)
  248. {
  249. RETURNDELIVERY_HIGH_TARIF = getValue(telegram, len, '(', '*');
  250. }
  251. // 1-0:1.7.0(00.424*kW) Actueel verbruik
  252. // 1-0:1.7.x = Electricity consumption actual usage (DSMR v4.0)
  253. if (strncmp(telegram, "1-0:1.7.0", strlen("1-0:1.7.0")) == 0)
  254. {
  255. ACTUAL_CONSUMPTION = getValue(telegram, len, '(', '*');
  256. }
  257. // 1-0:2.7.0(00.000*kW) Actuele teruglevering (-P) in 1 Watt resolution
  258. if (strncmp(telegram, "1-0:2.7.0", strlen("1-0:2.7.0")) == 0)
  259. {
  260. ACTUAL_RETURNDELIVERY = getValue(telegram, len, '(', '*');
  261. }
  262. // 1-0:21.7.0(00.378*kW)
  263. // 1-0:21.7.0 = Instantaan vermogen Elektriciteit levering L1
  264. if (strncmp(telegram, "1-0:21.7.0", strlen("1-0:21.7.0")) == 0)
  265. {
  266. L1_INSTANT_POWER_USAGE = getValue(telegram, len, '(', '*');
  267. }
  268. // 1-0:41.7.0(00.378*kW)
  269. // 1-0:41.7.0 = Instantaan vermogen Elektriciteit levering L2
  270. if (strncmp(telegram, "1-0:41.7.0", strlen("1-0:41.7.0")) == 0)
  271. {
  272. L2_INSTANT_POWER_USAGE = getValue(telegram, len, '(', '*');
  273. }
  274. // 1-0:61.7.0(00.378*kW)
  275. // 1-0:61.7.0 = Instantaan vermogen Elektriciteit levering L3
  276. if (strncmp(telegram, "1-0:61.7.0", strlen("1-0:61.7.0")) == 0)
  277. {
  278. L3_INSTANT_POWER_USAGE = getValue(telegram, len, '(', '*');
  279. }
  280. // 1-0:31.7.0(002*A)
  281. // 1-0:31.7.0 = Instantane stroom Elektriciteit L1
  282. if (strncmp(telegram, "1-0:31.7.0", strlen("1-0:31.7.0")) == 0)
  283. {
  284. L1_INSTANT_POWER_CURRENT = getValue(telegram, len, '(', '*');
  285. }
  286. // 1-0:51.7.0(002*A)
  287. // 1-0:51.7.0 = Instantane stroom Elektriciteit L2
  288. if (strncmp(telegram, "1-0:51.7.0", strlen("1-0:51.7.0")) == 0)
  289. {
  290. L2_INSTANT_POWER_CURRENT = getValue(telegram, len, '(', '*');
  291. }
  292. // 1-0:71.7.0(002*A)
  293. // 1-0:71.7.0 = Instantane stroom Elektriciteit L3
  294. if (strncmp(telegram, "1-0:71.7.0", strlen("1-0:71.7.0")) == 0)
  295. {
  296. L3_INSTANT_POWER_CURRENT = getValue(telegram, len, '(', '*');
  297. }
  298. // 1-0:32.7.0(232.0*V)
  299. // 1-0:32.7.0 = Voltage L1
  300. if (strncmp(telegram, "1-0:32.7.0", strlen("1-0:32.7.0")) == 0)
  301. {
  302. L1_VOLTAGE = getValue(telegram, len, '(', '*');
  303. }
  304. // 1-0:52.7.0(232.0*V)
  305. // 1-0:52.7.0 = Voltage L2
  306. if (strncmp(telegram, "1-0:52.7.0", strlen("1-0:52.7.0")) == 0)
  307. {
  308. L2_VOLTAGE = getValue(telegram, len, '(', '*');
  309. }
  310. // 1-0:72.7.0(232.0*V)
  311. // 1-0:72.7.0 = Voltage L3
  312. if (strncmp(telegram, "1-0:72.7.0", strlen("1-0:72.7.0")) == 0)
  313. {
  314. L3_VOLTAGE = getValue(telegram, len, '(', '*');
  315. }
  316. // 0-1:24.2.1(150531200000S)(00811.923*m3)
  317. // 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
  318. if (strncmp(telegram, "0-1:24.2.1", strlen("0-1:24.2.1")) == 0)
  319. {
  320. GAS_METER_M3 = getValue(telegram, len, '(', '*');
  321. }
  322. // 0-0:96.14.0(0001)
  323. // 0-0:96.14.0 = Actual Tarif
  324. if (strncmp(telegram, "0-0:96.14.0", strlen("0-0:96.14.0")) == 0)
  325. {
  326. ACTUAL_TARIF = getValue(telegram, len, '(', ')');
  327. }
  328. // 0-0:96.7.21(00003)
  329. // 0-0:96.7.21 = Aantal onderbrekingen Elektriciteit
  330. if (strncmp(telegram, "0-0:96.7.21", strlen("0-0:96.7.21")) == 0)
  331. {
  332. SHORT_POWER_OUTAGES = getValue(telegram, len, '(', ')');
  333. }
  334. // 0-0:96.7.9(00001)
  335. // 0-0:96.7.9 = Aantal lange onderbrekingen Elektriciteit
  336. if (strncmp(telegram, "0-0:96.7.9", strlen("0-0:96.7.9")) == 0)
  337. {
  338. LONG_POWER_OUTAGES = getValue(telegram, len, '(', ')');
  339. }
  340. // 1-0:32.32.0(00000)
  341. // 1-0:32.32.0 = Aantal korte spanningsdalingen Elektriciteit in fase 1
  342. if (strncmp(telegram, "1-0:32.32.0", strlen("1-0:32.32.0")) == 0)
  343. {
  344. SHORT_POWER_DROPS = getValue(telegram, len, '(', ')');
  345. }
  346. // 1-0:32.36.0(00000)
  347. // 1-0:32.36.0 = Aantal korte spanningsstijgingen Elektriciteit in fase 1
  348. if (strncmp(telegram, "1-0:32.36.0", strlen("1-0:32.36.0")) == 0)
  349. {
  350. SHORT_POWER_PEAKS = getValue(telegram, len, '(', ')');
  351. }
  352. return validCRCFound;
  353. }
  354. void read_p1_hardwareserial()
  355. {
  356. if (Serial.available())
  357. {
  358. memset(telegram, 0, sizeof(telegram));
  359. while (Serial.available())
  360. {
  361. ESP.wdtDisable();
  362. int len = Serial.readBytesUntil('\n', telegram, P1_MAXLINELENGTH);
  363. ESP.wdtEnable(1);
  364. processLine(len);
  365. }
  366. }
  367. }
  368. void processLine(int len) {
  369. telegram[len] = '\n';
  370. telegram[len + 1] = 0;
  371. yield();
  372. bool result = decode_telegram(len + 1);
  373. if (result) {
  374. send_data_to_broker();
  375. LAST_UPDATE_SENT = millis();
  376. }
  377. }
  378. // **********************************
  379. // * EEPROM helpers *
  380. // **********************************
  381. String read_eeprom(int offset, int len)
  382. {
  383. Serial.print(F("read_eeprom()"));
  384. String res = "";
  385. for (int i = 0; i < len; ++i)
  386. {
  387. res += char(EEPROM.read(i + offset));
  388. }
  389. return res;
  390. }
  391. void write_eeprom(int offset, int len, String value)
  392. {
  393. Serial.println(F("write_eeprom()"));
  394. for (int i = 0; i < len; ++i)
  395. {
  396. if ((unsigned)i < value.length())
  397. {
  398. EEPROM.write(i + offset, value[i]);
  399. }
  400. else
  401. {
  402. EEPROM.write(i + offset, 0);
  403. }
  404. }
  405. }
  406. // ******************************************
  407. // * Callback for saving WIFI config *
  408. // ******************************************
  409. bool shouldSaveConfig = false;
  410. // * Callback notifying us of the need to save config
  411. void save_wifi_config_callback ()
  412. {
  413. Serial.println(F("Should save config"));
  414. shouldSaveConfig = true;
  415. }
  416. // **********************************
  417. // * Setup OTA *
  418. // **********************************
  419. void setup_ota()
  420. {
  421. Serial.println(F("Arduino OTA activated."));
  422. // * Port defaults to 8266
  423. ArduinoOTA.setPort(8266);
  424. // * Set hostname for OTA
  425. ArduinoOTA.setHostname(HOSTNAME);
  426. ArduinoOTA.setPassword(OTA_PASSWORD);
  427. ArduinoOTA.onStart([]()
  428. {
  429. Serial.println(F("Arduino OTA: Start"));
  430. });
  431. ArduinoOTA.onEnd([]()
  432. {
  433. Serial.println(F("Arduino OTA: End (Running reboot)"));
  434. });
  435. ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
  436. {
  437. Serial.printf("Arduino OTA Progress: %u%%\r", (progress / (total / 100)));
  438. });
  439. ArduinoOTA.onError([](ota_error_t error)
  440. {
  441. Serial.printf("Arduino OTA Error[%u]: ", error);
  442. if (error == OTA_AUTH_ERROR)
  443. Serial.println(F("Arduino OTA: Auth Failed"));
  444. else if (error == OTA_BEGIN_ERROR)
  445. Serial.println(F("Arduino OTA: Begin Failed"));
  446. else if (error == OTA_CONNECT_ERROR)
  447. Serial.println(F("Arduino OTA: Connect Failed"));
  448. else if (error == OTA_RECEIVE_ERROR)
  449. Serial.println(F("Arduino OTA: Receive Failed"));
  450. else if (error == OTA_END_ERROR)
  451. Serial.println(F("Arduino OTA: End Failed"));
  452. });
  453. ArduinoOTA.begin();
  454. Serial.println(F("Arduino OTA finished"));
  455. }
  456. // **********************************
  457. // * Setup MDNS discovery service *
  458. // **********************************
  459. void setup_mdns()
  460. {
  461. Serial.println(F("Starting MDNS responder service"));
  462. bool mdns_result = MDNS.begin(HOSTNAME);
  463. if (mdns_result)
  464. {
  465. MDNS.addService("http", "tcp", 80);
  466. }
  467. }
  468. // **********************************
  469. // * Setup Main *
  470. // **********************************
  471. void setup()
  472. {
  473. // * Configure EEPROM
  474. EEPROM.begin(512);
  475. // Setup a hw serial connection for communication with the P1 meter and logging (not using inversion)
  476. Serial.begin(BAUD_RATE, SERIAL_8N1, SERIAL_FULL);
  477. Serial.println("");
  478. Serial.println("Swapping UART0 RX to inverted");
  479. Serial.flush();
  480. // Invert the RX serialport by setting a register value, this way the TX might continue normally allowing the serial monitor to read println's
  481. USC0(UART0) = USC0(UART0) | BIT(UCRXI);
  482. Serial.println("Serial port is ready to recieve.");
  483. // * Set led pin as output
  484. pinMode(LED_BUILTIN, OUTPUT);
  485. // * Start ticker with 0.5 because we start in AP mode and try to connect
  486. ticker.attach(0.6, tick);
  487. // * Get MQTT Server settings
  488. String settings_available = read_eeprom(134, 1);
  489. if (settings_available == "1")
  490. {
  491. read_eeprom(0, 64).toCharArray(MQTT_HOST, 64); // * 0-63
  492. read_eeprom(64, 6).toCharArray(MQTT_PORT, 6); // * 64-69
  493. read_eeprom(70, 32).toCharArray(MQTT_USER, 32); // * 70-101
  494. read_eeprom(102, 32).toCharArray(MQTT_PASS, 32); // * 102-133
  495. }
  496. WiFiManagerParameter CUSTOM_MQTT_HOST("host", "MQTT hostname", MQTT_HOST, 64);
  497. WiFiManagerParameter CUSTOM_MQTT_PORT("port", "MQTT port", MQTT_PORT, 6);
  498. WiFiManagerParameter CUSTOM_MQTT_USER("user", "MQTT user", MQTT_USER, 32);
  499. WiFiManagerParameter CUSTOM_MQTT_PASS("pass", "MQTT pass", MQTT_PASS, 32);
  500. // * WiFiManager local initialization. Once its business is done, there is no need to keep it around
  501. WiFiManager wifiManager;
  502. // * Reset settings - uncomment for testing
  503. // wifiManager.resetSettings();
  504. // * Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  505. wifiManager.setAPCallback(configModeCallback);
  506. // * Set timeout
  507. wifiManager.setConfigPortalTimeout(WIFI_TIMEOUT);
  508. // * Set save config callback
  509. wifiManager.setSaveConfigCallback(save_wifi_config_callback);
  510. // * Add all your parameters here
  511. wifiManager.addParameter(&CUSTOM_MQTT_HOST);
  512. wifiManager.addParameter(&CUSTOM_MQTT_PORT);
  513. wifiManager.addParameter(&CUSTOM_MQTT_USER);
  514. wifiManager.addParameter(&CUSTOM_MQTT_PASS);
  515. // * Fetches SSID and pass and tries to connect
  516. // * Reset when no connection after 10 seconds
  517. if (!wifiManager.autoConnect())
  518. {
  519. Serial.println(F("Failed to connect to WIFI and hit timeout"));
  520. // * Reset and try again, or maybe put it to deep sleep
  521. ESP.reset();
  522. delay(WIFI_TIMEOUT);
  523. }
  524. // * Read updated parameters
  525. strcpy(MQTT_HOST, CUSTOM_MQTT_HOST.getValue());
  526. strcpy(MQTT_PORT, CUSTOM_MQTT_PORT.getValue());
  527. strcpy(MQTT_USER, CUSTOM_MQTT_USER.getValue());
  528. strcpy(MQTT_PASS, CUSTOM_MQTT_PASS.getValue());
  529. // * Save the custom parameters to FS
  530. if (shouldSaveConfig)
  531. {
  532. Serial.println(F("Saving WiFiManager config"));
  533. write_eeprom(0, 64, MQTT_HOST); // * 0-63
  534. write_eeprom(64, 6, MQTT_PORT); // * 64-69
  535. write_eeprom(70, 32, MQTT_USER); // * 70-101
  536. write_eeprom(102, 32, MQTT_PASS); // * 102-133
  537. write_eeprom(134, 1, "1"); // * 134 --> always "1"
  538. EEPROM.commit();
  539. }
  540. // * If you get here you have connected to the WiFi
  541. Serial.println(F("Connected to WIFI..."));
  542. // * Keep LED on
  543. ticker.detach();
  544. digitalWrite(LED_BUILTIN, LOW);
  545. // * Configure OTA
  546. setup_ota();
  547. // * Startup MDNS Service
  548. setup_mdns();
  549. // * Setup MQTT
  550. Serial.printf("MQTT connecting to: %s:%s\n", MQTT_HOST, MQTT_PORT);
  551. mqtt_client.setServer(MQTT_HOST, atoi(MQTT_PORT));
  552. }
  553. // **********************************
  554. // * Loop *
  555. // **********************************
  556. void loop()
  557. {
  558. ArduinoOTA.handle();
  559. long now = millis();
  560. if (!mqtt_client.connected())
  561. {
  562. if (now - LAST_RECONNECT_ATTEMPT > 5000)
  563. {
  564. LAST_RECONNECT_ATTEMPT = now;
  565. if (mqtt_reconnect())
  566. {
  567. LAST_RECONNECT_ATTEMPT = 0;
  568. }
  569. }
  570. }
  571. else
  572. {
  573. mqtt_client.loop();
  574. }
  575. if (now - LAST_UPDATE_SENT > UPDATE_INTERVAL) {
  576. read_p1_hardwareserial();
  577. }
  578. }