esp8266_p1meter.ino 20 KB

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