WiFiThermostat.ino 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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.1.2"
  7. #define COPYRIGHT " by Flo Kra"
  8. // default values, can later be overridden via configuration
  9. #define DEVICE_NAME "WiFi-Thermostat-1"
  10. #define MQTT_SERVER "10.1.1.11"
  11. #define MQTT_PORT 1883
  12. #define MQTT_TOPIC_IN "Test/Thermostat/cmd"
  13. #define MQTT_TOPIC_OUT "Test/Thermostat/status"
  14. #define BUTTON_DEBOUNCE_TIME 120
  15. #define BUTTON_HOLD_TIME 750
  16. #define DOMOTICZ_IN_TOPIC "domoticz/in"
  17. #define DOMOTICZ_OUT_TOPIC "domoticz/out"
  18. #define OUTTEMP_TOPIC_IN "wetter/atemp"
  19. #define OUTHUM_TOPIC_IN "wetter/ahum"
  20. #define CLEARCONF_TOKEN "TUES"
  21. // pin assignments and I2C addresses
  22. #define PIN_DHTSENSOR 13
  23. #define PIN_RELAIS 16
  24. #define PIN_BUTTON_PLUS 2
  25. #define PIN_BUTTON_MINUS 0
  26. #define PIN_BUTTON_MODE 14
  27. #define PIN_PIRSENSOR 12
  28. #define DHTTYPE DHT22 // DHT sensor type
  29. #define LCDADDR 0x27 // I2C address LCD
  30. #define LCDCOLS 16
  31. #define LCDLINES 2
  32. // default logic levels
  33. #define RELAISONSTATE LOW
  34. #define BUTTONONSTATE LOW
  35. #include "PersWiFiManager.h"
  36. #include <ArduinoJson.h>
  37. #include <ESP8266WiFi.h>
  38. #include <WiFiClient.h>
  39. #include <ESP8266WebServer.h>
  40. #include <ESP8266mDNS.h>
  41. #include <ESP8266HTTPUpdateServer.h>
  42. #include "PubSubClient.h"
  43. #include <DNSServer.h>
  44. #include <FS.h>
  45. #include <Wire.h>
  46. #include "LiquidCrystal_I2C.h"
  47. #include "DHT.h"
  48. #ifndef MESSZ
  49. #define MESSZ 405 // Max number of characters in JSON message string (4 x DS18x20 sensors)
  50. #endif
  51. // Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength)
  52. #if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MESSZ // If the max message size is too small, throw an error at compile time
  53. // See pubsubclient.c line 359
  54. #error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 512"
  55. #endif
  56. // config variables - do not change here!
  57. //conf
  58. char deviceName[31]; // device name - just for web interface
  59. char http_user[31];
  60. char http_pass[31];
  61. char mqtt_server[41];
  62. int mqtt_port = MQTT_PORT;
  63. char mqtt_user[31];
  64. char mqtt_pass[31];
  65. char mqtt_topic_in[51]; // MQTT in topic for commands
  66. char mqtt_topic_out[51]; // MQTT out base topic, will be extended by various value names
  67. boolean mqtt_outRetain = false; // send MQTT out with retain flag
  68. char mqtt_willTopic[51]; // MQTT Last Will topic
  69. int mqtt_willQos = 2; // MQTT Last Will topic QOS
  70. boolean mqtt_willRetain = false; // MQTT Last Will retain
  71. char mqtt_willMsg[31]; // MQTT Last Will payload
  72. char domoticz_out_topic[55]; // domoticz out topic to subscribe to (only applicable if domoticzIdx_Thermostat and/or domoticzIdx_ThermostatMode is set to >0)
  73. //conf2
  74. int domoticzIdx_Thermostat = 0;
  75. int domoticzIdx_ThermostatMode = 0;
  76. int domoticzIdx_TempHumSensor = 0;
  77. int domoticzIdx_PIR = 0;
  78. char outTemp_topic_in[51];
  79. char outHum_topic_in[51];
  80. boolean autoSaveSetTemp = true;
  81. boolean autoSaveHeatingMode = true;
  82. int heatingMinOffTime = 10; // minimal time the heating keeps turned off in s
  83. float setTempMin = 14.0; // minimal temperature that can be set
  84. float setTempMax = 29.0; // maximal temperature that can be set
  85. float setTempLow = 18.0; // set temperature in night/low mode
  86. float hysteresis = 0.5;
  87. float tempCorrVal = 0.0; // correction value for temperature sensor reading
  88. int humCorrVal = 0; // correction value for humidity sensor reading
  89. int measureInterval = 15; // interval for temp/hum measurement
  90. int displayInterval = 5; //
  91. int displayTimeout = 120;
  92. //set values
  93. float setTemp = 21.5;
  94. byte heatingMode = 1; // 0 = off, 1 = normal/day, 2 = night/reduction
  95. float setTempSaved;
  96. byte heatingModeSaved; // 0 = off, 1 = normal/day, 2 = night/reduction
  97. // not changeable via configuration
  98. float setTempLowMin = 14.0;
  99. float setTempLowMax = 19.0;
  100. boolean debug = true;
  101. int debounceTime = BUTTON_DEBOUNCE_TIME;
  102. int buttonHoldTime = BUTTON_HOLD_TIME;
  103. // global variables
  104. float currTemp; // last reading from DHT sensor
  105. float currTemp_raw; // last reading from DHT sensor
  106. int currHum; // last reading from DHT sensor
  107. int currHum_raw; // last reading from DHT sensor
  108. bool turnHeatingOn = false; // true if heating is active (relais switched on)
  109. unsigned long heatingLastOnMillis; // last time heating was switched on
  110. unsigned long heatingLastOffMillis; // last time heating was switched off
  111. float outTemp; // outside temp (via MQTT if enabled and in-topic configured)
  112. int outHum; // outside temp (via MQTT if enabled and in-topic configured)
  113. long outTempHumLastUpdate; // last reading from out temp/hum source
  114. 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
  115. unsigned long lastMeasure = 0; // millis of last temp/hum measurement
  116. unsigned long lastDisplayUpdate = 0; // millis of last display update
  117. unsigned long lastDisplayToggle = 0; // millis of last display toggle
  118. unsigned long lastTempUpdate = 0; // last update time of DHT reading
  119. char msg[50]; // buffer MQTT in payload
  120. char topic[50]; // buffer MQTT in topic
  121. 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
  122. unsigned long heatingOnTime, heatingOffTime;
  123. boolean useDomoticz = false; // will be set to true in setup() if idx-values other than 0 are configured
  124. boolean domoticzOutParseData = false; // indicates that domoticz/out json data is buffered, will then be parsed in next loop() run
  125. boolean domoticzOutParserBusy = false; // indicates that domoticz/out json data is currently processed - no futher data will be accepted until finished
  126. char domoticzOutPayload[450]; // buffer for domoticz/out data
  127. int dismissUpdateFromDomoticzTimeout = 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
  128. 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
  129. 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
  130. bool lastUpdateFromDomoticz_setTemp = false;
  131. bool lastUpdateFromDomoticz_heatingMode = false;
  132. int domoticzUpdateInterval = 30; // interval in min to force update of domoticz devices
  133. char cmdPayload[101]; // buffer for commands
  134. boolean cmdInQueue = false; // command is queued and will be processed next loop() run
  135. bool saveConfigToFlash = false; // conf is saved in next loop() run
  136. bool saveConfig2ToFlash = false; // conf2 is saved in next loop() run
  137. unsigned int saveValuesTimeout = 5000;
  138. unsigned long lastValueChange; // is set to millis() whenever setTemp value and/or heatingMode value is changed. used for autoSave function with hardcoded 5s timeout
  139. bool setTempAlreadySaved = true; // only save if not yet done
  140. bool heatingModeAlreadySaved = true; // only save if not yet done
  141. byte mqttMode = 0;
  142. unsigned long mqttLastReconnectAttempt = 0;
  143. int mqttReconnects = 0;
  144. DHT dht(PIN_DHTSENSOR, DHTTYPE);
  145. LiquidCrystal_I2C lcd(LCDADDR, LCDCOLS, LCDLINES); // set the LCD address to 0x27 for a 16 chars and 2 line display
  146. WiFiClient espClient;
  147. void mqttCallback(char* topic, byte* payload, unsigned int length);
  148. PubSubClient mqttclient(espClient);
  149. ESP8266WebServer httpServer(80);
  150. DNSServer dnsServer;
  151. PersWiFiManager persWM(httpServer, dnsServer);
  152. ESP8266HTTPUpdateServer httpUpdater;
  153. void setup() {
  154. Serial.begin(115200);
  155. delay(500);
  156. Serial.println();
  157. Serial.print(FIRMWARE_NAME);
  158. Serial.print(" v");
  159. Serial.print(VERSION);
  160. Serial.println(COPYRIGHT);
  161. Serial.println("starting...");
  162. pinMode(PIN_RELAIS, OUTPUT);
  163. digitalWrite(PIN_RELAIS, HIGH);
  164. pinMode(PIN_BUTTON_PLUS, INPUT_PULLUP);
  165. pinMode(PIN_BUTTON_MINUS, INPUT_PULLUP);
  166. pinMode(PIN_BUTTON_MODE, INPUT_PULLUP);
  167. strlcpy(deviceName, DEVICE_NAME, 31);
  168. strlcpy(mqtt_server, MQTT_SERVER, 41);
  169. strlcpy(mqtt_topic_in, MQTT_TOPIC_IN, 51);
  170. strlcpy(mqtt_topic_out, MQTT_TOPIC_OUT, 51);
  171. strlcpy(domoticz_out_topic, DOMOTICZ_OUT_TOPIC, 51); // changeable subscription topic, as domoticz supports different flat/hierarchical out-topics
  172. strlcpy(outTemp_topic_in, OUTTEMP_TOPIC_IN, 51);
  173. strlcpy(outHum_topic_in, OUTHUM_TOPIC_IN, 51);
  174. Serial.println("default config values loaded..");
  175. Serial.println("Mounting FS...");
  176. if (!SPIFFS.begin()) {
  177. Serial.println("Failed to mount file system");
  178. return;
  179. }
  180. //SPIFFS.format();
  181. //Serial.print("Format SPIFFS complete.");
  182. if (!SPIFFS.exists("/formatComplete.txt")) {
  183. Serial.println("Please wait 30 secs for SPIFFS to be formatted");
  184. SPIFFS.format();
  185. Serial.println("Spiffs formatted");
  186. File f = SPIFFS.open("/formatComplete.txt", "w");
  187. if (!f) {
  188. Serial.println("file open failed");
  189. } else {
  190. f.println("Format Complete");
  191. }
  192. f.close();
  193. } else {
  194. Serial.println("SPIFFS is formatted. Moving along...");
  195. }
  196. // // load config from SPIFFS if files exist
  197. if (!loadConfig()) {
  198. Serial.println("Failed to load conf.json");
  199. } else {
  200. Serial.println("conf.json loaded");
  201. }
  202. if (!loadConfig2()) {
  203. Serial.println("Failed to load conf2.json");
  204. } else {
  205. Serial.println("conf2.json loaded");
  206. }
  207. if (!loadSetTemp()) {
  208. Serial.println("Failed to load file 'setTemp'");
  209. } else {
  210. Serial.println("file 'setTemp' loaded");
  211. }
  212. if (!loadHeatingMode()) {
  213. Serial.println("Failed to load file 'heatingMode'");
  214. } else {
  215. Serial.println("file 'heatingMode' loaded");
  216. }
  217. setTempSaved = setTemp;
  218. heatingModeSaved = heatingMode;
  219. // initialize DHT11/22 temp/hum sensor
  220. dht.begin();
  221. checkUseDomoticz();
  222. delay(500);
  223. //optional code handlers to run everytime wifi is connected...
  224. persWM.onConnect([]() {
  225. Serial.println("wifi connected");
  226. Serial.println(WiFi.SSID());
  227. Serial.println(WiFi.localIP());
  228. });
  229. //...or AP mode is started
  230. persWM.onAp([]() {
  231. Serial.println("AP MODE");
  232. Serial.println(persWM.getApSsid());
  233. });
  234. //sets network name for AP mode
  235. persWM.setApCredentials(DEVICE_NAME);
  236. //persWM.setApCredentials(DEVICE_NAME, "password"); optional password
  237. //make connecting/disconnecting non-blocking
  238. persWM.setConnectNonBlock(true);
  239. //in non-blocking mode, program will continue past this point without waiting
  240. persWM.begin();
  241. delay(500);
  242. httpServerInit();
  243. mqttPrepareConnection();
  244. mqttClientInit();
  245. initDisplay();
  246. Serial.println("setup complete.");
  247. delay(1000);
  248. } //void setup
  249. void loop() {
  250. checkMillis();
  251. persWM.handleWiFi(); //in non-blocking mode, handleWiFi must be called in the main loop
  252. yield();
  253. dnsServer.processNextRequest();
  254. httpServer.handleClient();
  255. mqttHandleConnection();
  256. checkButtonStates();
  257. yield();
  258. evalCmd();
  259. if ( domoticzOutParseData ) {
  260. parseDomoticzOut();
  261. yield();
  262. }
  263. if (Serial.available()) {
  264. serialEvent();
  265. yield();
  266. }
  267. } //void loop