WiFiThermostat.ino 17 KB

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