WiFiThermostat.ino 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. // pre compiletime config
  2. //#define DEBUG_VERBOSE
  3. #define SPIFFS_DBG
  4. #define SPIFFS_USE_MAGIC
  5. #define FIRMWARE_NAME "WiFiThermostat"
  6. #define VERSION "0.3.2"
  7. // default values, can later be overridden via configuration (conf)
  8. #define DEVICE_NAME "WiFiThermo-1"
  9. #define WIFI_APMODE_PASSWORD "LassMiRein"
  10. #define DEFAULT_HTTP_USER ""
  11. #define DEFAULT_HTTP_PASS ""
  12. #define HTTP_SET_TOKEN "grzbrz"
  13. #define MQTT_SERVER "mqtt.lan"
  14. #define MQTT_PORT 1883
  15. #define MQTT_USER ""
  16. #define MQTT_PASS ""
  17. #define MQTT_TOPIC_IN "Test/Thermostat"
  18. #define MQTT_TOPIC_OUT "Test/Thermostat/stat"
  19. #define MQTT_OUT_RETAIN false
  20. #define MQTT_WILLTOPIC "Test/Thermostat/availability"
  21. #define MQTT_WILLQOS 2
  22. #define MQTT_WILLRETAIN false
  23. #define MQTT_WILLMSG "offline"
  24. #define MQTT_CONNMSG "online"
  25. #define DOMOTICZ_OUT_TOPIC "domoticz/out"
  26. // default values, can later be overridden via configuration (conf2)
  27. #define DOMOTICZ_IDX_THERMOSTAT 0
  28. #define DOMOTICZ_IDX_THERMOSTATMODE 0
  29. #define DOMOTICZ_IDX_TEMPHUMSENSOR 0
  30. #define DOMOTICZ_IDX_HEATING 0
  31. #define DOMOTICZ_IDX_PIR 0
  32. #define OUTTEMP_TOPIC_IN ""
  33. #define OUTHUM_TOPIC_IN ""
  34. #define MQTT_TOPIC_PIR "" // extra publish topic for PIR sensor
  35. #define AUTOSAVE_SETTEMP true
  36. #define AUTOSAVE_SETMODE true
  37. #define DEFAULT_HEATING_MIN_OFFTIME 120 // minimal time the heating keeps turned off in s
  38. #define DEFAULT_SETTEMP_MIN 16.0 // minimal temperature that can be set
  39. #define DEFAULT_SETTEMP_MAX 25.0 // maximal temperature that can be set
  40. #define DEFAULT_SETTEMP_LOW 18.0 // set temperature in night/low mode
  41. #define DEFAULT_SETTEMP_LOW2 20.0 // set temperature in night/low mode
  42. #define DEFAULT_SETTEMP_HEATOFF 3.0 // set temperature in OFF mode (freezing guard > 0)
  43. #define DEFAULT_HYSTERESIS 0.1 // hysteresis, normally 0.1 - 0.5
  44. #define SETTEMP_DECREASE_VALUE 0.0 // decreases the set temp to overcome further temperature rise when the heating is already switched off
  45. #define TEMPSENSOR_CORRECTION_VALUE 0.0 // correction value for temperature sensor reading
  46. #define HUMSENSOR_CORRECTION_VALUE 0 // correction value for humidity sensor reading
  47. #define DEFAULT_MEASURE_INTERVAL 15 // interval for temp/hum measurement
  48. #define DEFAULT_DISPLAY_INTERVAL 5 // interval for display updates (if out-temp is active, display will toggle in this interval)
  49. #define DEFAULT_DISPLAY_TIMEOUT 30 // display timeout after keypress (illumination)
  50. #define DEFAULT_PIR_ENABLES_DISPLAY false
  51. #define INSIDE_TEMP_LABEL "I"
  52. #define OUTSIDE_TEMP_LABEL "O"
  53. #define MODE_NAME_0 "off"
  54. #define MODE_NAME_1 "heat"
  55. #define PRESET_NAME_0 "none"
  56. #define PRESET_NAME_1 "reduction1"
  57. #define PRESET_NAME_2 "reduction2"
  58. // default initial values
  59. #define DEFAULT_SETTEMP 21.5
  60. #define DEFAULT_HEATINGMODE 1
  61. #define DEFAULT_PRESET 1
  62. // default values that can only be configured at compile time / hardware configuration
  63. #define CLEARCONF_TOKEN "DOIT!" // Token used to reset configuration via http call on http://<IP>/delconf?token=<TOKEN> (use when password is forgotten)
  64. #define BUTTON_DEBOUNCE_TIME 120
  65. #define BUTTON_HOLD_TIME 750
  66. #define DOMOTICZ_IN_TOPIC "domoticz/in" // if Domoticz IDXes are configured, updates will be sent to this topic
  67. #define SETTEMP_LOW_MIN 14.0 // minimal configurable temperature for reduction mode
  68. #define SETTEMP_LOW_MAX 20.0 // maximal configurable temperature for reduction mode
  69. #define DOMOTICZ_DISMISSUPDATE_TIMEOUT 2500 // after a value was changed by data from domoticz/out, domoticz/out parsing for this device will be turned off for this time to prevent infinite loops
  70. #define DOMOTICZ_FORCEUPDATE_INTERVAL 15 // interval in min to force update of domoticz devices
  71. #define MQTT_HEARTBEAT_MAXAGE 180000 // interval for MQTT heartbeat message. only applicable if MQTT IN-topic is defined. after this timeout MQTT reconnect is forced
  72. // pin assignments and I2C addresses
  73. #define PIN_DHTSENSOR 13
  74. #define PIN_RELAIS 15 //16
  75. #define PIN_BUTTON_PLUS 2
  76. #define PIN_BUTTON_MINUS 0
  77. #define PIN_BUTTON_MODE 14
  78. #define PIN_PIRSENSOR 12
  79. #define DHTTYPE DHT22 // DHT sensor type
  80. #define LCDADDR 0x27 // I2C address LCD
  81. #define LCDCOLS 16
  82. #define LCDLINES 2
  83. // default logic levels
  84. #define RELAISONSTATE HIGH
  85. #define BUTTONONSTATE LOW
  86. #include <Button.h>
  87. #include <ButtonEventCallback.h>
  88. #include <PushButton.h>
  89. #include <Bounce2.h>
  90. PushButton buttonPlus = PushButton(PIN_BUTTON_PLUS, ENABLE_INTERNAL_PULLUP);
  91. PushButton buttonMinus = PushButton(PIN_BUTTON_MINUS, ENABLE_INTERNAL_PULLUP);
  92. PushButton buttonMode = PushButton(PIN_BUTTON_MODE, ENABLE_INTERNAL_PULLUP);
  93. PushButton pirSensor = PushButton(PIN_PIRSENSOR, PRESSED_WHEN_HIGH);
  94. #include <PersWiFiManager.h>
  95. #include <ArduinoJson.h>
  96. #include <ESP8266WiFi.h>
  97. #include <WiFiClient.h>
  98. #include <ESP8266WebServer.h>
  99. #include <ESP8266mDNS.h>
  100. #include <ESP8266HTTPUpdateServer.h>
  101. #include "PubSubClient.h"
  102. #include <DNSServer.h>
  103. #include <FS.h>
  104. #include <Wire.h>
  105. #include <LiquidCrystal_I2C.h>
  106. #include <DHT.h>
  107. #include <string.h>
  108. #ifndef MESSZ
  109. #define MESSZ 405 // Max number of characters in JSON message string (4 x DS18x20 sensors)
  110. #endif
  111. // Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength)
  112. #if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MESSZ // If the max message size is too small, throw an error at compile time
  113. // See pubsubclient.c line 359
  114. #error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 512"
  115. #endif
  116. boolean serialdebug = true;
  117. boolean mqttdebug = true;
  118. boolean WifiInApMode = false;
  119. unsigned long WifiApModeStartedAt;
  120. // config variables - do not change here!
  121. //conf
  122. char deviceName[31]; // device name - for web interface and AP-Mode SSID
  123. char hostName[31]; // announced hostname on WiFi connection
  124. char wifiAPModePassword[31];
  125. char http_user[31];
  126. char http_pass[31];
  127. char http_token[31];
  128. char mqtt_server[41];
  129. int mqtt_port = MQTT_PORT;
  130. char mqtt_user[31];
  131. char mqtt_pass[31];
  132. char mqtt_topic_in[51]; // MQTT in topic for commands
  133. char mqtt_topic_out[51]; // MQTT out base topic, will be extended by various value names
  134. boolean mqtt_outRetain = MQTT_OUT_RETAIN; // send MQTT out with retain flag
  135. char mqtt_willTopic[51]; // MQTT Last Will topic
  136. int mqtt_willQos = MQTT_WILLQOS; // MQTT Last Will topic QOS
  137. boolean mqtt_willRetain = MQTT_WILLRETAIN; // MQTT Last Will retain
  138. char mqtt_willMsg[31]; // MQTT Last Will payload
  139. char mqtt_connMsg[31];
  140. char domoticz_out_topic[55]; // domoticz out topic to subscribe to (only applicable if domoticzIdx_Thermostat and/or domoticzIdx_ThermostatMode is set to >0)
  141. char mqtt_topic_in_cmd[61];
  142. char mqtt_topic_in_setTemp[61];
  143. char mqtt_topic_in_setMode[61];
  144. char mqtt_topic_in_setPreset[61];
  145. //conf2
  146. int domoticzIdx_Thermostat = DOMOTICZ_IDX_THERMOSTAT;
  147. int domoticzIdx_ThermostatMode = DOMOTICZ_IDX_THERMOSTATMODE;
  148. int domoticzIdx_TempHumSensor = DOMOTICZ_IDX_TEMPHUMSENSOR;
  149. int domoticzIdx_Heating = DOMOTICZ_IDX_HEATING;
  150. int domoticzIdx_PIR = DOMOTICZ_IDX_PIR;
  151. char outTemp_topic_in[51];
  152. char outHum_topic_in[51];
  153. char mqtt_topic_pir[51];
  154. boolean autoSaveSetTemp = AUTOSAVE_SETTEMP;
  155. boolean autoSaveHeatingMode = AUTOSAVE_SETMODE;
  156. int heatingMinOffTime = DEFAULT_HEATING_MIN_OFFTIME; // minimal time the heating keeps turned off in s
  157. float setTempMin = DEFAULT_SETTEMP_MIN; // minimal temperature that can be set
  158. float setTempMax = DEFAULT_SETTEMP_MAX; // maximal temperature that can be set
  159. float setTempLow = DEFAULT_SETTEMP_LOW; // set temperature in night/low mode
  160. float setTempLow2 = DEFAULT_SETTEMP_LOW2; // set temperature in night/low mode
  161. float hysteresis = DEFAULT_HYSTERESIS; // hysteresis, normally 0.1 - 0.5
  162. float setTempDecreaseVal = SETTEMP_DECREASE_VALUE; // decreases the set temp to overcome further temperature rise when the heating is already switched off
  163. float tempCorrVal = TEMPSENSOR_CORRECTION_VALUE; // correction value for temperature sensor reading
  164. int humCorrVal = HUMSENSOR_CORRECTION_VALUE; // correction value for humidity sensor reading
  165. int measureInterval = DEFAULT_MEASURE_INTERVAL; // interval for temp/hum measurement
  166. int displayInterval = DEFAULT_DISPLAY_INTERVAL; // interval for display updates (if out-temp is active, display will toggle in this interval)
  167. int displayInterval_saved = DEFAULT_DISPLAY_INTERVAL;
  168. int displayTimeout = DEFAULT_DISPLAY_TIMEOUT; // display timeout after keypress (illumination)
  169. boolean PIR_enablesDisplay = DEFAULT_PIR_ENABLES_DISPLAY; // PIR sensor enables display illumination
  170. char modename0[15];
  171. char modename1[15];
  172. char psetname0[15];
  173. char psetname1[15];
  174. char psetname2[15];
  175. char offMessage[15];
  176. char itemplab[2];
  177. char otemplab[2];
  178. //set values
  179. float setTemp = DEFAULT_SETTEMP;
  180. float currSetTemp = DEFAULT_SETTEMP;
  181. byte heatingMode = DEFAULT_HEATINGMODE; // 0 = off, 1 = heat
  182. byte preset = DEFAULT_PRESET; // 0 = normal/day, 1 = night/reduction 1, 2 = reduction 2 (long term leave)
  183. float setTempSaved;
  184. byte heatingModeSaved; // 0 = off, 1 = heat/on
  185. byte presetSaved; // 0 = normal/day, 1 = night/reduction 1, 2 = reduction 2
  186. // not changeable via configuration
  187. float setTempLowMin = SETTEMP_LOW_MIN;
  188. float setTempLowMax = SETTEMP_LOW_MAX;
  189. boolean debug = true;
  190. int debounceTime = BUTTON_DEBOUNCE_TIME;
  191. int buttonHoldTime = BUTTON_HOLD_TIME;
  192. // global variables
  193. float currTemp; // last reading from DHT sensor
  194. float currTemp_raw; // last reading from DHT sensor
  195. int currHum; // last reading from DHT sensor
  196. int currHum_raw; // last reading from DHT sensor
  197. boolean turnHeatingOn = false; // true if heating is active (relais switched on)
  198. unsigned long heatingLastOnMillis; // last time heating was switched on
  199. unsigned long heatingLastOffMillis; // last time heating was switched off
  200. float outTemp; // outside temp (via MQTT if enabled and in-topic configured)
  201. int outHum; // outside temp (via MQTT if enabled and in-topic configured)
  202. long outTempHumLastUpdate; // last reading from out temp/hum source
  203. char outTemp_newValue[6];
  204. boolean outTemp_parseNewValue;
  205. char outHum_newValue[4];
  206. boolean outHum_parseNewValue;
  207. char currentModeName[15];
  208. char currentPresetName[15];
  209. byte whichTempToDisplay; // 1=temp inside (from DHT sensor), 2= temp outside (via MQTT) - if out temp/hum available this value and the displayed value pair toggles with every displayInterval
  210. unsigned long lastMeasure = 0; // millis of last temp/hum measurement
  211. unsigned long lastDisplayUpdate = 0; // millis of last display update
  212. unsigned long lastDisplayToggle = 0; // millis of last display toggle
  213. unsigned long lastTempUpdate = 0; // last update time of DHT reading
  214. char msg[50]; // buffer MQTT in payload
  215. char topic[50]; // buffer MQTT in topic
  216. boolean displayActive = false; // gets true when button is pressed. display light gets switched on until timeout. button actions are only performed while display is active
  217. boolean PIRSensorOn = false;
  218. unsigned long heatingOnTime, heatingOffTime;
  219. boolean useDomoticz = false; // will be set to true in setup() if idx-values other than 0 are configured
  220. boolean domoticzOutParseData = false; // indicates that domoticz/out json data is buffered, will then be parsed in next loop() run
  221. boolean domoticzOutParserBusy = false; // indicates that domoticz/out json data is currently processed - no futher data will be accepted until finished
  222. char domoticzOutPayload[450]; // buffer for domoticz/out data
  223. int dismissUpdateFromDomoticzTimeout = DOMOTICZ_DISMISSUPDATE_TIMEOUT; // after a value was changed by data from domoticz/out, domoticz/out parsing for this device will be turned off for this time to prevent infinite loops
  224. unsigned long lastUpdate_setTemp = 0; // set to millis() every time setTemp value is changed. next update from domoticz/out will be rejected for dismissUpdateFromDomoticzTimeout in this case
  225. unsigned long lastUpdate_heatingMode = 0; // set to millis() every time heatingMode value is changed. next update from domoticz/out will be rejected for dismissUpdateFromDomoticzTimeout in this case
  226. unsigned long lastUpdate_preset = 0; // set to millis() every time preset value is changed. next update from domoticz/out will be rejected for dismissUpdateFromDomoticzTimeout in this case
  227. boolean lastUpdateFromDomoticz_setTemp = false;
  228. boolean lastUpdateFromDomoticz_heatingMode = false;
  229. int domoticzUpdateInterval = DOMOTICZ_FORCEUPDATE_INTERVAL; // interval in min to force update of domoticz devices
  230. char cmdPayload[101]; // buffer for commands
  231. boolean cmdInQueue = false; // command is queued and will be processed next loop() run
  232. boolean saveConfigToFlash = false; // conf is saved in next loop() run
  233. boolean saveConfig2ToFlash = false; // conf2 is saved in next loop() run
  234. unsigned int saveValuesTimeout = 5000;
  235. unsigned long lastValueChange; // is set to millis() whenever setTemp value and/or heatingMode value is changed. used for autoSave function with hardcoded 5s timeout
  236. boolean setTempAlreadySaved = true; // only save if not yet done
  237. boolean heatingModeAlreadySaved = true; // only save if not yet done
  238. boolean presetAlreadySaved = true; // only save if not yet done
  239. unsigned long lastRun = 0;
  240. int count100ms = 0;
  241. int countSeconds = 0;
  242. int countMeasureInterval = 0;
  243. int countDisplayInterval = 0;
  244. int displayOverlayMsgTimeout = 2;
  245. boolean togglingTempHumAIDisplay = false;
  246. byte mqttMode = 0;
  247. unsigned long mqttLastReconnectAttempt = 0;
  248. int mqttReconnectAttempts = 0;
  249. int mqttReconnects = 0;
  250. boolean mqttConnected = false;
  251. unsigned long mqttLastHeartbeat;
  252. boolean mqttInTopicSubscribed = false;
  253. boolean pendingRestart = false;
  254. boolean doRestart = false;
  255. unsigned long pendingRestart_lastMillis = 0;
  256. boolean displayShowFullscreenMsg = false;
  257. //unsigned long displayShowFullscreenMsg_lastMillis = 0;
  258. boolean pendingPresetToggle = false;
  259. boolean updateDisplayImmediately = false;
  260. int pendingPreset;
  261. char pendingPresetName[15];
  262. //unsigned long pendingPreset_millis = 0;
  263. //int pendingPreset_timeout = 2000;
  264. boolean displayShowLine2OverlayMsg = false;
  265. DHT dht(PIN_DHTSENSOR, DHTTYPE);
  266. LiquidCrystal_I2C lcd(LCDADDR, LCDCOLS, LCDLINES); // set the LCD address to 0x27 for a 16 chars and 2 line display
  267. WiFiClient espClient;
  268. void mqttCallback(char* topic, byte* payload, unsigned int length);
  269. PubSubClient mqttclient(espClient);
  270. ESP8266WebServer httpServer(80);
  271. DNSServer dnsServer;
  272. PersWiFiManager persWM(httpServer, dnsServer);
  273. ESP8266HTTPUpdateServer httpUpdater;
  274. void setup() {
  275. Serial.begin(115200);
  276. delay(500);
  277. Serial.println();
  278. Serial.print(FIRMWARE_NAME);
  279. Serial.print(" v");
  280. Serial.print(VERSION);
  281. Serial.println("starting...");
  282. pinMode(PIN_RELAIS, OUTPUT);
  283. digitalWrite(PIN_RELAIS, !RELAISONSTATE);
  284. pinMode(PIN_PIRSENSOR, INPUT);
  285. buttonPlus.configureButton(configurePushButton);
  286. //buttonPlus.onPress(onButtonPressed); // When the button is first pressed, call the function onButtonPressed (further down the page)
  287. buttonPlus.onHoldRepeat(1000, 350, onButtonHeld); // Once the button has been held for 1 second (1000ms) call onButtonHeld. Call it again every 350ms until it is let go
  288. buttonPlus.onRelease(50, 500, onButtonReleased); // When the button is held >50ms and released after <500ms, call onButtonReleased
  289. buttonMinus.configureButton(configurePushButton);
  290. //buttonMinus.onPress(onButtonPressed); // When the button is first pressed, call the function onButtonPressed (further down the page)
  291. buttonMinus.onHoldRepeat(1000, 350, onButtonHeld); // Once the button has been held for 1 second (1000ms) call onButtonHeld. Call it again every 350ms until it is let go
  292. buttonMinus.onRelease(50, 500, onButtonReleased); // When the button is held >50ms and released after <500ms, call onButtonReleased
  293. buttonMode.configureButton(configurePushButton);
  294. //buttonMode.onPress(onButtonPressed); // When the button is first pressed, call the function onButtonPressed (further down the page)
  295. //buttonMode.onHold(1000, onButtonHeldNoRepeat); // Once the button has been held for 1 second (1000ms) call onButtonHeld
  296. buttonMode.onHoldRepeat(1000, 1000, onButtonHeld); // Once the button has been held for 1 second (1000ms) call onButtonHeld
  297. buttonMode.onRelease(50, 500, onButtonReleased); // When the button is held >50ms and released after <500ms, call onButtonReleased
  298. pirSensor.configureButton(configurePushButton);
  299. //pirSensor.onPress(onButtonPressed); // When the button is first pressed, call the function onButtonPressed (further down the page)
  300. pirSensor.onHold(500, onButtonHeldNoRepeat); // Once the button has been held for 1 second (1000ms) call onButtonHeld
  301. pirSensor.onRelease(500, onButtonReleased); // When the button is held >50ms and released after <500ms, call onButtonReleased
  302. //set conf default values (bool, int and float variables are set at declaration)
  303. strlcpy(deviceName, DEVICE_NAME, 31);
  304. strlcpy(wifiAPModePassword, WIFI_APMODE_PASSWORD, 31);
  305. strlcpy(http_user, DEFAULT_HTTP_USER, 31);
  306. strlcpy(http_pass, DEFAULT_HTTP_PASS, 31);
  307. strlcpy(http_token, HTTP_SET_TOKEN, 31);
  308. strlcpy(mqtt_server, MQTT_SERVER, 41);
  309. strlcpy(mqtt_user, MQTT_USER, 31);
  310. strlcpy(mqtt_pass, MQTT_PASS, 31);
  311. strlcpy(mqtt_topic_in, MQTT_TOPIC_IN, 51);
  312. strlcpy(mqtt_topic_out, MQTT_TOPIC_OUT, 51);
  313. strlcpy(mqtt_willTopic, MQTT_WILLTOPIC, 51);
  314. strlcpy(mqtt_willMsg, MQTT_WILLMSG, 31);
  315. strlcpy(mqtt_connMsg, MQTT_CONNMSG, 31);
  316. strlcpy(domoticz_out_topic, DOMOTICZ_OUT_TOPIC, 51); // changeable subscription topic, as domoticz supports different flat/hierarchical out-topics
  317. //set conf2 default values (bool, int and float variables are set at declaration)
  318. strlcpy(outTemp_topic_in, OUTTEMP_TOPIC_IN, 51);
  319. strlcpy(outHum_topic_in, OUTHUM_TOPIC_IN, 51);
  320. strlcpy(mqtt_topic_pir, MQTT_TOPIC_PIR, 51);
  321. strlcpy(modename0, MODE_NAME_0, 15);
  322. strlcpy(modename1, MODE_NAME_1, 15);
  323. strlcpy(psetname0, PRESET_NAME_0, 15);
  324. strlcpy(psetname1, PRESET_NAME_1, 15);
  325. strlcpy(psetname2, PRESET_NAME_2, 15);
  326. strlcpy(itemplab, INSIDE_TEMP_LABEL, 2);
  327. strlcpy(otemplab, OUTSIDE_TEMP_LABEL, 2);
  328. Serial.println("default config values loaded..");
  329. Serial.println("Mounting FS...");
  330. if (!SPIFFS.begin()) {
  331. Serial.println("Failed to mount file system");
  332. return;
  333. }
  334. //uncomment for initial SPIFFS format
  335. //SPIFFS.format();
  336. //Serial.print("Format SPIFFS complete.");
  337. if (!SPIFFS.exists("/formatComplete.txt")) {
  338. Serial.println("Please wait 30 secs for SPIFFS to be formatted");
  339. SPIFFS.format();
  340. Serial.println("Spiffs formatted");
  341. File f = SPIFFS.open("/formatComplete.txt", "w");
  342. if (!f) {
  343. Serial.println("file open failed");
  344. } else {
  345. f.println("Format Complete");
  346. }
  347. f.close();
  348. } else {
  349. Serial.println("SPIFFS is formatted. Moving along...");
  350. }
  351. // // load config from SPIFFS if files exist
  352. if (!loadConfig()) {
  353. Serial.println("Failed to load conf.json");
  354. } else {
  355. Serial.println("conf.json loaded");
  356. }
  357. if (!loadConfig2()) {
  358. Serial.println("Failed to load conf2.json");
  359. } else {
  360. Serial.println("conf2.json loaded");
  361. }
  362. if (!loadSetTemp()) {
  363. Serial.println("Failed to load file 'setTemp'");
  364. } else {
  365. Serial.println("file 'setTemp' loaded");
  366. }
  367. if (!loadHeatingMode()) {
  368. Serial.println("Failed to load file 'heatingMode'");
  369. } else {
  370. Serial.println("file 'heatingMode' loaded");
  371. }
  372. if (!loadPreset()) {
  373. Serial.println("Failed to load file 'preset'");
  374. } else {
  375. Serial.println("file 'preset' loaded");
  376. }
  377. //if configuration returns empty strings - use the default from source
  378. if (strlen(deviceName) < 4) strlcpy(deviceName, DEVICE_NAME, 31);
  379. if (modename0[0] == '\0') strlcpy(modename0, MODE_NAME_0, 15);
  380. if (modename1[0] == '\0') strlcpy(modename1, MODE_NAME_1, 15);
  381. if (psetname0[0] == '\0') strlcpy(psetname0, PRESET_NAME_0, 15);
  382. if (psetname1[0] == '\0') strlcpy(psetname1, PRESET_NAME_1, 15);
  383. if (psetname2[0] == '\0') strlcpy(psetname2, PRESET_NAME_2, 15);
  384. if (itemplab[0] == '\0') strlcpy(itemplab, INSIDE_TEMP_LABEL, 2);
  385. if (otemplab[0] == '\0') strlcpy(otemplab, OUTSIDE_TEMP_LABEL, 2);
  386. setTempSaved = setTemp;
  387. heatingModeSaved = heatingMode;
  388. presetSaved = preset;
  389. updateCurrentHeatingModeName();
  390. updateCurrentPresetName();
  391. // initialize DHT11/22 temp/hum sensor
  392. dht.begin();
  393. if (strlen(hostName) >= 4) { // if no hostname is set WiFi manager will create a unique one automatically based on MAC address
  394. WiFi.hostname(hostName);
  395. }
  396. mqttPrepareSubscribeTopics();
  397. checkUseDomoticz();
  398. //optional code handlers to run everytime wifi is connected...
  399. persWM.onConnect([]() {
  400. Serial.println("wifi connected");
  401. Serial.println(WiFi.SSID());
  402. Serial.println(WiFi.localIP());
  403. WifiInApMode = false;
  404. displayShowWifiConnected();
  405. });
  406. //...or AP mode is started
  407. persWM.onAp([]() {
  408. Serial.println("AP MODE");
  409. Serial.println(persWM.getApSsid());
  410. WifiInApMode = true;
  411. WifiApModeStartedAt = millis();
  412. displayShowWifiConnectionError();
  413. });
  414. // sets network name and password for AP mode
  415. if (strlen(wifiAPModePassword) < 8) {
  416. strlcpy(wifiAPModePassword, WIFI_APMODE_PASSWORD, 31);
  417. }
  418. persWM.setApCredentials(deviceName, wifiAPModePassword);
  419. // persWM.setApCredentials(DEVICE_NAME);
  420. //make connecting/disconnecting non-blocking
  421. persWM.setConnectNonBlock(true);
  422. //in non-blocking mode, program will continue past this point without waiting
  423. persWM.begin();
  424. delay(500);
  425. httpServerInit();
  426. mqttPrepareConnection();
  427. mqttClientInit();
  428. initDisplay();
  429. Serial.println("setup complete.");
  430. //delay(1000);
  431. } //void setup
  432. void loop() {
  433. checkMillis();
  434. persWM.handleWiFi(); //in non-blocking mode, handleWiFi must be called in the main loop
  435. yield();
  436. mqttHandleConnection();
  437. yield();
  438. outTempHum_updateOnNewValue();
  439. yield();
  440. dnsServer.processNextRequest();
  441. httpServer.handleClient();
  442. buttonPlus.update();
  443. buttonMinus.update();
  444. buttonMode.update();
  445. pirSensor.update();
  446. yield();
  447. evalCmd();
  448. yield();
  449. if ( domoticzOutParseData ) {
  450. parseDomoticzOut();
  451. yield();
  452. }
  453. if (Serial.available()) {
  454. serialEvent();
  455. yield();
  456. }
  457. if (updateDisplayImmediately) {
  458. updateDisplayImmediately = false;
  459. updateDisplay();
  460. }
  461. } //void loop