WiFiThermostat.ino 18 KB

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