WiFiThermostat.ino 22 KB

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