ESPIoTBase.ino 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. //#include <Arduino.h>
  2. #include "version.h"
  3. #include "firmware_definitions.h"
  4. #include "settings.h"
  5. #include "settings_secrets.h"
  6. // ESP8266 core libs
  7. #include <ESP8266HTTPUpdateServer.h>
  8. #include <ESP8266WebServer.h>
  9. #include <ESP8266WiFi.h>
  10. #include <ESP8266mDNS.h>
  11. #include <EEPROM.h>
  12. #ifdef ENABLE_I2C_INTERFACE
  13. #include <Wire.h>
  14. #endif
  15. #ifdef ENABLE_FEATURE_ARDUINO_OTA
  16. #include <WiFiUdp.h>
  17. #include <ArduinoOTA.h>
  18. #endif
  19. #ifdef ENABLE_FEATURE_NTP_TIME
  20. #include <time.h>
  21. #endif
  22. // cannot be excluded if unused, throws error even if all
  23. // references are inactive by preprocessor
  24. #include <WebSocketsServer.h>
  25. #ifdef USE_MQTT_TLS
  26. #include <WiFiClientSecure.h>
  27. #else
  28. #include <WiFiClient.h>
  29. #endif
  30. // WiFiManager
  31. #include <PersWiFiManagerExt.h>
  32. // DNS server used for captive portal in WiFiManager
  33. #include <DNSServer.h>
  34. // MQTT client
  35. #include <PubSubClient.h>
  36. // File System support - used for config storage (switched from SPIFFS to LittleFS in 12/2021)
  37. #include "LittleFS.h" // LittleFS is declared
  38. FSInfo fs_info; // struct for file system infos
  39. // Json lib - used for web api
  40. #include <ArduinoJson.h>
  41. // I2C LCD display
  42. #ifdef ENABLE_LCD_I2C
  43. #include <LiquidCrystal_I2C.h>
  44. #endif
  45. // DHT22 sensor lib
  46. #ifdef ENABLE_SENSOR_DHT22
  47. //#include <Adafruit_Sensor.h> // not needed for used version of DHT library v1.3.8
  48. #include <DHT.h>
  49. #endif
  50. // Dallas OneWire Temperature Sensors
  51. #ifdef ENABLE_SENSORS_ONEWIRE
  52. #include <OneWire.h>
  53. #include <DallasTemperature.h>
  54. // Setup a oneWire instance to communicate with any OneWire devices
  55. OneWire oneWire(ONE_WIRE_BUS);
  56. // Pass our oneWire reference to Dallas Temperature sensor
  57. DallasTemperature oneWireSensors(&oneWire);
  58. // arrays to hold device addresses
  59. //DeviceAddress oneWireSensor0, oneWireSensor1, oneWireSensor2;
  60. DeviceAddress oneWireSensors_IndexToAddress[ONEWIRE_SENSORS_COUNT];
  61. //DeviceAddress oneWireDevAddress_outside = { 0x28, 0xd7, 0xbd, 0x16, 0x00, 0x00, 0x00, 0xcd };
  62. //DeviceAddress oneWireDevAddress_feed = { 0x28, 0x75, 0xb2, 0x16, 0x00, 0x00, 0x00, 0x90 };
  63. //DeviceAddress oneWireDevAddress_return = { 0x28, 0x1f, 0x7a, 0x17, 0x00, 0x00, 0x00, 0x0f };
  64. //uint8_t oneWireDevAddress_tempFeed[0] = {0x28, 0x75, 0xb2, 0x16, 0x00, 0x00, 0x00, 0x90}; // temp feed
  65. //uint8_t oneWireDevAddress_tempReturn[] = {0x28, 0x1f, 0x7a, 0x17, 0x00, 0x00, 0x00, 0x0f}; // temp return
  66. //uint8_t oneWireDevAddress_tempOutside[] = {0x28, 0xd7, 0xbd, 0x16, 0x00, 0x00, 0x00, 0xcd}; // temp outside
  67. //uint8_t confSens.oneWireDevAddress[ONEWIRE_SENSORS_COUNT][8]; //= {
  68. // {0x28, 0x75, 0xb2, 0x16, 0x00, 0x00, 0x00, 0x90}, // temp feed
  69. // {0x28, 0x1f, 0x7a, 0x17, 0x00, 0x00, 0x00, 0x0f}, // temp return
  70. // {0x28, 0xd7, 0xbd, 0x16, 0x00, 0x00, 0x00, 0xcd} // temp outside
  71. //};
  72. // -> moved to struct confSens
  73. uint8_t oneWireSensor_assignedDevToIndex[ONEWIRE_SENSORS_COUNT] = {255, 255, 255};
  74. //uint8_t oneWireDevAddressToSensor[ONEWIRE_SENSORS_COUNT];
  75. //float tempFeed, tempReturn, tempOutside;
  76. #endif
  77. #ifdef ENABLE_I2C_PORTEXPANDER
  78. #include <PCF8574.h>
  79. PCF8574 pcf8574(PCF8574_I2C_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
  80. #endif
  81. //#ifdef ENABLE_INPUT_BUTTONS
  82. // can not be excluded if unused, throws compile error
  83. // even when all references are also deactivated by preprocessor
  84. #include <Button.h>
  85. #include <PushButton.h>
  86. #include <Bounce2.h>
  87. #include <ButtonEventCallback.h>
  88. //#endif
  89. #ifdef LANG_DE
  90. #include "strings_progmem_DE.h"
  91. #else
  92. #include "strings_progmem.h"
  93. #endif
  94. //---------------------------------------------------------------------------------------------------------------------------------------------
  95. #include "globalVars_conf.h"
  96. #include "globalVars.h"
  97. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  98. #include "globalVars_conf_thermostat.h"
  99. #include "globalVars_thermostat.h"
  100. #endif
  101. #ifdef FIRMWARE_VARIANT_HEATCONTROL
  102. #include "globalVars_heatcontrol.h"
  103. #include "globalVars_conf_heatcontrol.h"
  104. #ifdef LANG_DE
  105. #include "heatcontrol_strings_DE.h"
  106. #else
  107. #include "heatcontrol_strings.h"
  108. #endif
  109. #endif
  110. #ifdef ENABLE_INPUT_BUTTONS
  111. PushButton buttonMode = PushButton(PIN_BUTTON_MODE, ENABLE_INTERNAL_PULLUP);
  112. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  113. PushButton buttonPlus = PushButton(PIN_BUTTON_PLUS, ENABLE_INTERNAL_PULLUP);
  114. PushButton buttonMinus = PushButton(PIN_BUTTON_MINUS, ENABLE_INTERNAL_PULLUP);
  115. #endif
  116. #ifdef ENABLE_SENSOR_PIR
  117. PushButton pirSensor = PushButton(PIN_PIRSENSOR, PRESSED_WHEN_HIGH);
  118. #endif
  119. #endif
  120. #ifdef ENABLE_SENSOR_DHT22
  121. DHT dht(PIN_DHTSENSOR, DHTTYPE);
  122. #endif
  123. #ifdef ENABLE_LCD_I2C
  124. LiquidCrystal_I2C lcd(LCDADDR, LCDCOLS, LCDLINES);
  125. #ifdef LANG_DE
  126. #include "strings_display_DE.h"
  127. #else
  128. #include "strings_display.h"
  129. #endif
  130. #endif
  131. #ifdef USE_MQTT_TLS
  132. //WiFiClientSecure wifiClient;
  133. BearSSL::WiFiClientSecure wifiClient;
  134. #else
  135. WiFiClient wifiClient;
  136. #endif
  137. PubSubClient mqttclient(wifiClient);
  138. ESP8266WebServer httpServer(80);
  139. // WebSockets Console
  140. #ifdef ENABLE_FEATURE_WSCONSOLE
  141. WebSocketsServer webSocket(81);
  142. unsigned long int wsValidSessionId = 0;
  143. #endif
  144. DNSServer dnsServer;
  145. PersWiFiManager persWM(httpServer, dnsServer);
  146. #ifdef ENABLE_FEATURE_HTTP_UPDATER
  147. ESP8266HTTPUpdateServer httpUpdater;
  148. #endif
  149. // FUNCTION PROTOTYPES
  150. #ifdef ENABLE_FEATURE_NTP_TIME
  151. void updateTime();
  152. bool setupTime();
  153. void syncClock(bool force = false);
  154. #endif
  155. char *getUptimeStr(bool includeSeconds = false);
  156. void sendLog(const char *msg, uint8_t loglevel = 1);
  157. void sendLog(const __FlashStringHelper *msg, uint8_t loglevel = 1);
  158. void mqttCallback(char *topic, byte *payload, uint16_t length);
  159. char *getTimeStringFromSeconds(unsigned int inSeconds);
  160. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  161. void thermostat_publishCurrentValues(bool force = false);
  162. #endif
  163. // END - FUNCTION PROTOTYPES
  164. // MAIN FUNCTIONS
  165. void setup()
  166. {
  167. conf_restoreDebugMode();
  168. Serial.begin(SERIAL_BAUDRATE);
  169. delay(50);
  170. if(debug) {
  171. Serial.println();
  172. Serial.print(PGMStr_FIRMWARE_NAME);
  173. Serial.print(F(" v"));
  174. Serial.print(PGMStr_FIRMWARE_VERSION);
  175. Serial.println(F(" starting..."));
  176. Serial.print("DEBUG=");
  177. Serial.println(debug);
  178. }
  179. #ifdef ENABLE_I2C_INTERFACE
  180. Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
  181. #endif
  182. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  183. thermostat_setup();
  184. #endif
  185. #ifdef ENABLE_INPUT_BUTTONS
  186. setupInputsButtons();
  187. #endif
  188. // set conf default values
  189. loadConf_defaults();
  190. if(debug) {
  191. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_conf_defaultsLoaded);
  192. sendLog(logBuf);
  193. }
  194. #ifdef ENABLE_LCD_I2C
  195. display_init();
  196. #endif
  197. // LittleFS
  198. if(debug) {
  199. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_filesystem_mounting);
  200. sendLog(logBuf, LOGLEVEL_ERROR);
  201. }
  202. if (!LittleFS.begin())
  203. {
  204. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_filesystem_mounting_error);
  205. sendLog(logBuf, LOGLEVEL_ERROR);
  206. return;
  207. }
  208. #ifdef FORCE_FILESYSTEM_FORMAT
  209. FS_format();
  210. #endif
  211. FS_formatIfIsnt();
  212. if(debug) {
  213. FS_listFiles();
  214. }
  215. #ifdef ENABLE_FEATURE_SECRETS_ENCRYPTION
  216. confCheckEncrypted();
  217. #endif
  218. loadConf_all();
  219. // if configuration returned empty strings - use the defaults where a values
  220. // is necessary if (strlen(deviceName) < 4) strlcpy(deviceName, DEVICE_NAME,
  221. // 31);
  222. loadConf_restoreDefaultWhenMissing();
  223. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  224. thermostat_loadSavedValues();
  225. thermostat_updateCurrentHeatingModeName();
  226. thermostat_updateCurrentPresetName();
  227. #endif
  228. // initialize DHT11/22 temp/hum sensor
  229. #ifdef ENABLE_SENSOR_DHT22
  230. dht.begin();
  231. #endif
  232. // Start the DS18B20 sensor
  233. #ifdef ENABLE_SENSORS_ONEWIRE
  234. oneWireSensors_setup();
  235. oneWireSensors_loadAssignments();
  236. #endif
  237. #ifdef ENABLE_I2C_PORTEXPANDER
  238. portexpander_setup();
  239. #endif
  240. if (strlen(confDevWiFi.hostName) >= 4)
  241. { // if no hostname is set WiFi manager will create a unique one automatically
  242. // based on MAC address
  243. WiFi.hostname(confDevWiFi.hostName);
  244. }
  245. // optional code handlers to run everytime wifi is connected...
  246. persWM.onConnect([]() {
  247. //Serial.print(F("WiFi: connected to '"));
  248. //Serial.print(WiFi.SSID());
  249. //Serial.print(F("' with IP: "));
  250. //Serial.println(WiFi.localIP());
  251. //char buf[60];
  252. //sprintf(buf, "%s: %s '%s' %s: '%s'", PGMStr_WiFi, PGMStr_connectedTo, WiFi.SSID().c_str(), PGMStr_withIP, WiFi.localIP().toString().c_str());
  253. //sendLog(buf, LOGLEVEL_INFO);
  254. printIpcfg();
  255. WifiInApMode = false;
  256. #ifdef ENABLE_FEATURE_NTP_TIME
  257. if (confTime.ntpEnable) setupTime();
  258. #endif
  259. #ifdef ENABLE_LCD_I2C
  260. display_showWifiConnected();
  261. #endif
  262. });
  263. //...or AP mode is started
  264. persWM.onAp([]() {
  265. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_setup_APmode_started, PGMStr_WiFi, persWM.getApSsid().c_str(), confSecrets.WiFiAPModePassword);
  266. sendLog(logBuf, LOGLEVEL_INFO);
  267. WifiInApMode = true;
  268. WifiApModeStartedAt = millis();
  269. #ifdef ENABLE_LCD_I2C
  270. display_showWifiConnectionError();
  271. #endif
  272. });
  273. persWM.onApOff([]() {
  274. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_setup_APmode_stopped, PGMStr_WiFi);
  275. sendLog(logBuf, LOGLEVEL_INFO);
  276. });
  277. // sets network name and password for AP mode
  278. if (strlen(confDevWiFi.deviceName) >= 8)
  279. strlcpy(confDevWiFi.WiFiAPModeSSID, confDevWiFi.deviceName, sizeof(confDevWiFi.WiFiAPModeSSID));
  280. else
  281. {
  282. byte mac[6];
  283. WiFi.macAddress(mac);
  284. sprintf(confDevWiFi.WiFiAPModeSSID, "%s-%02X%02X", FIRMWARE_SHORTNAME, (uint8_t)mac[4], (uint8_t)mac[5]);
  285. }
  286. if (strlen(confSecrets.WiFiAPModePassword) < 5)
  287. {
  288. persWM.setApCredentials(confDevWiFi.WiFiAPModeSSID);
  289. if(debug>0) {
  290. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_setup_APmode_openNet, PGMStr_WiFi, confDevWiFi.WiFiAPModeSSID);
  291. sendLog(logBuf);
  292. }
  293. }
  294. else
  295. {
  296. persWM.setApCredentials(confDevWiFi.WiFiAPModeSSID, confSecrets.WiFiAPModePassword);
  297. if(debug>0) {
  298. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_setup_APmode_withPassword, PGMStr_WiFi, confDevWiFi.WiFiAPModeSSID, confSecrets.WiFiAPModePassword);
  299. sendLog(logBuf, LOGLEVEL_INFO);
  300. }
  301. }
  302. persWM.setWifi1Credentials(confDevWiFi.WiFiSSID1, confSecrets.WiFiPW1);
  303. persWM.setWifi2Credentials(confDevWiFi.WiFiSSID2, confSecrets.WiFiPW2);
  304. persWM.setHttpCredentials(confSecrets.http_user, confSecrets.http_pass);
  305. persWM.setApTimeout(confDevWiFi.WiFiAPModeTimeout);
  306. persWM.setConnCheckInterval(confDevWiFi.WiFiConnCheckInterval);
  307. persWM.setForceRetryWifi1Interval(confDevWiFi.WiFiRetryInterval);
  308. persWM.setRebootOnNoConnect(confDevWiFi.WiFiRebootOnNoConnect);
  309. // make connecting/disconnecting non-blocking
  310. persWM.setConnectNonBlock(true);
  311. // in non-blocking mode, program will continue past this point without waiting
  312. persWM.begin();
  313. #ifdef USE_MQTT_TLS
  314. //randomSeed(micros());
  315. //wifiClient.setFingerprint(MQTT_TLS_fingerprint);
  316. wifiClient.setInsecure();
  317. wifiClient.allowSelfSignedCerts();
  318. wifiClient.setCiphersLessSecure();
  319. #endif
  320. httpServerInit();
  321. #ifdef ENABLE_FEATURE_ARDUINO_OTA
  322. if(confDevWiFi.enableArduinoOTA) {
  323. ArduinoOTA.setPort(ARDUINO_OTA_PORT);
  324. ArduinoOTA.begin();
  325. }
  326. #endif
  327. #ifdef ENABLE_FEATURE_WSCONSOLE
  328. if (confWeb.wsConsole) {
  329. startWebSocketServer();
  330. }
  331. #endif
  332. if (confMqtt.mqtt_enable)
  333. {
  334. mqttPrepareSubscribeTopics();
  335. mqttClientInit();
  336. }
  337. snprintf_P(logBuf, LOG_BUFFER_SIZE, PGMStr_system_setupComplete);
  338. sendLog(logBuf, LOGLEVEL_INFO);
  339. // get sensor data and do things right on system start
  340. #ifdef ENABLE_SENSORS_ONEWIRE
  341. oneWireSensors_getData();
  342. #endif
  343. #ifdef ENABLE_SENSOR_DHT22
  344. if (confSens.DHT_enable) DHT_measureTempHum();
  345. #endif
  346. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  347. thermostat_mainFunction();
  348. #endif
  349. #ifdef FIRMWARE_VARIANT_HEATCONTROL
  350. heatcontrol_mainFunction();
  351. portexpander_readInputs();
  352. #endif
  353. } // void setup
  354. void loop()
  355. {
  356. scheduler_checkMillis();
  357. persWM.handleWiFi(); // in non-blocking mode, handleWiFi must be called in the main loop
  358. yield();
  359. mqttHandleConnection();
  360. yield();
  361. #ifdef ENABLE_FEATURE_ARDUINO_OTA
  362. if(confDevWiFi.enableArduinoOTA) {
  363. ArduinoOTA.handle();
  364. yield();
  365. }
  366. #endif
  367. outTempHum_updateOnNewValue();
  368. yield();
  369. dnsServer.processNextRequest();
  370. httpServer.handleClient();
  371. #ifdef ENABLE_INPUT_BUTTONS
  372. buttonMode.update();
  373. #ifdef FIRMWARE_VARIANT_THERMOSTAT
  374. buttonPlus.update();
  375. buttonMinus.update();
  376. #endif
  377. #ifdef ENABLE_SENSOR_PIR
  378. pirSensor.update();
  379. #endif
  380. #endif
  381. yield();
  382. evalCmd();
  383. yield();
  384. if (Serial.available())
  385. {
  386. serialEvent();
  387. yield();
  388. }
  389. #ifdef ENABLE_LCD_I2C
  390. if (display_updateImmediately)
  391. {
  392. display_updateImmediately = false;
  393. display_update();
  394. }
  395. #endif
  396. #ifdef ENABLE_FEATURE_WSCONSOLE
  397. if (confWeb.wsConsole)
  398. {
  399. if (WiFi.status() == WL_CONNECTED)
  400. {
  401. webSocket.loop();
  402. }
  403. else
  404. {
  405. webSocket.disconnect();
  406. }
  407. }
  408. #endif
  409. } // void loop
  410. //#ifdef USE_MQTT_TLS
  411. //void verifytls() {
  412. // // Use WiFiClientSecure class to create TLS connection
  413. // Serial.print(F("MQTT: trying TLS connection to "));
  414. // Serial.println(confMqtt.mqtt_server);
  415. // if (!wifiClient.connect(confMqtt.mqtt_server, confMqtt.mqtt_port)) {
  416. // Serial.println("connection failed");
  417. // return;
  418. // }
  419. //
  420. // if (wifiClient.verify(MQTT_TLS_fingerprint, confMqtt.mqtt_server)) {
  421. // Serial.println("certificate matches");
  422. // } else {
  423. // Serial.println("certificate doesn't match");
  424. // }
  425. //}
  426. //#endif