Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

828 lines
33 KiB

  1. /*
  2. THERMOSTAT MODULE
  3. Copyright (C) 2017 by Dmitry Blinov <dblinov76 at gmail dot com>
  4. */
  5. #if THERMOSTAT_SUPPORT
  6. #include "relay.h"
  7. #include <ArduinoJson.h>
  8. #include <float.h>
  9. bool _thermostat_enabled = true;
  10. bool _thermostat_mode_cooler = false;
  11. const char* NAME_THERMOSTAT_ENABLED = "thermostatEnabled";
  12. const char* NAME_THERMOSTAT_MODE = "thermostatMode";
  13. const char* NAME_TEMP_RANGE_MIN = "tempRangeMin";
  14. const char* NAME_TEMP_RANGE_MAX = "tempRangeMax";
  15. const char* NAME_REMOTE_SENSOR_NAME = "remoteSensorName";
  16. const char* NAME_REMOTE_TEMP_MAX_WAIT = "remoteTempMaxWait";
  17. const char* NAME_ALONE_ON_TIME = "aloneOnTime";
  18. const char* NAME_ALONE_OFF_TIME = "aloneOffTime";
  19. const char* NAME_MAX_ON_TIME = "maxOnTime";
  20. const char* NAME_MIN_OFF_TIME = "minOffTime";
  21. const char* NAME_BURN_TOTAL = "burnTotal";
  22. const char* NAME_BURN_TODAY = "burnToday";
  23. const char* NAME_BURN_YESTERDAY = "burnYesterday";
  24. const char* NAME_BURN_THIS_MONTH = "burnThisMonth";
  25. const char* NAME_BURN_PREV_MONTH = "burnPrevMonth";
  26. const char* NAME_BURN_DAY = "burnDay";
  27. const char* NAME_BURN_MONTH = "burnMonth";
  28. const char* NAME_OPERATION_MODE = "thermostatOperationMode";
  29. #define ASK_TEMP_RANGE_INTERVAL_INITIAL 15000 // ask initially once per every 15 seconds
  30. #define ASK_TEMP_RANGE_INTERVAL_REGULAR 60000 // ask every minute to be sure
  31. #define MILLIS_IN_SEC 1000
  32. #define MILLIS_IN_MIN 60000
  33. #define THERMOSTAT_STATE_UPDATE_INTERVAL 60000 // 1 min
  34. #define THERMOSTAT_RELAY 0 // use relay 0
  35. #define THERMOSTAT_TEMP_RANGE_MIN 10 // grad. Celsius
  36. #define THERMOSTAT_TEMP_RANGE_MIN_MIN 3 // grad. Celsius
  37. #define THERMOSTAT_TEMP_RANGE_MIN_MAX 30 // grad. Celsius
  38. #define THERMOSTAT_TEMP_RANGE_MAX 20 // grad. Celsius
  39. #define THERMOSTAT_TEMP_RANGE_MAX_MIN 8 // grad. Celsius
  40. #define THERMOSTAT_TEMP_RANGE_MAX_MAX 35 // grad. Celsius
  41. #define THERMOSTAT_ALONE_ON_TIME 5 // 5 min
  42. #define THERMOSTAT_ALONE_OFF_TIME 55 // 55 min
  43. #define THERMOSTAT_MAX_ON_TIME 30 // 30 min
  44. #define THERMOSTAT_MIN_OFF_TIME 10 // 10 min
  45. unsigned long _thermostat_remote_temp_max_wait = THERMOSTAT_REMOTE_TEMP_MAX_WAIT * MILLIS_IN_SEC;
  46. unsigned long _thermostat_alone_on_time = THERMOSTAT_ALONE_ON_TIME * MILLIS_IN_MIN;
  47. unsigned long _thermostat_alone_off_time = THERMOSTAT_ALONE_OFF_TIME * MILLIS_IN_MIN;
  48. unsigned long _thermostat_max_on_time = THERMOSTAT_MAX_ON_TIME * MILLIS_IN_MIN;
  49. unsigned long _thermostat_min_off_time = THERMOSTAT_MIN_OFF_TIME * MILLIS_IN_MIN;
  50. unsigned int _thermostat_on_time_for_day = 0;
  51. unsigned int _thermostat_burn_total = 0;
  52. unsigned int _thermostat_burn_today = 0;
  53. unsigned int _thermostat_burn_yesterday = 0;
  54. unsigned int _thermostat_burn_this_month = 0;
  55. unsigned int _thermostat_burn_prev_month = 0;
  56. unsigned int _thermostat_burn_day = 0;
  57. unsigned int _thermostat_burn_month = 0;
  58. struct temp_t {
  59. float temp;
  60. unsigned long last_update = 0;
  61. bool need_display_update = false;
  62. };
  63. temp_t _remote_temp;
  64. struct temp_range_t {
  65. int min = THERMOSTAT_TEMP_RANGE_MIN;
  66. int max = THERMOSTAT_TEMP_RANGE_MAX;
  67. unsigned long last_update = 0;
  68. unsigned long ask_time = 0;
  69. unsigned int ask_interval = 0;
  70. bool need_display_update = true;
  71. };
  72. temp_range_t _temp_range;
  73. enum temperature_source_t {temp_none, temp_local, temp_remote};
  74. struct thermostat_t {
  75. unsigned long last_update = 0;
  76. unsigned long last_switch = 0;
  77. String remote_sensor_name;
  78. unsigned int temperature_source = temp_none;
  79. };
  80. thermostat_t _thermostat;
  81. enum thermostat_cycle_type {cooling, heating};
  82. unsigned int _thermostat_cycle = heating;
  83. String thermostat_remote_sensor_topic;
  84. //------------------------------------------------------------------------------
  85. void thermostatEnabled(bool enabled) {
  86. _thermostat_enabled = enabled;
  87. }
  88. //------------------------------------------------------------------------------
  89. bool thermostatEnabled() {
  90. return _thermostat_enabled;
  91. }
  92. //------------------------------------------------------------------------------
  93. void thermostatModeCooler(bool cooler) {
  94. _thermostat_mode_cooler = cooler;
  95. }
  96. //------------------------------------------------------------------------------
  97. bool thermostatModeCooler() {
  98. return _thermostat_mode_cooler;
  99. }
  100. //------------------------------------------------------------------------------
  101. std::vector<thermostat_callback_f> _thermostat_callbacks;
  102. void thermostatRegister(thermostat_callback_f callback) {
  103. _thermostat_callbacks.push_back(callback);
  104. }
  105. //------------------------------------------------------------------------------
  106. void updateOperationMode() {
  107. #if WEB_SUPPORT
  108. String message;
  109. if (_thermostat.temperature_source == temp_remote) {
  110. message = "{\"thermostatVisible\": 1, \"thermostatOperationMode\": \"remote temperature\"}";
  111. updateRemoteTemp(true);
  112. } else if (_thermostat.temperature_source == temp_local) {
  113. message = "{\"thermostatVisible\": 1, \"thermostatOperationMode\": \"local temperature\"}";
  114. updateRemoteTemp(false);
  115. } else {
  116. message = "{\"thermostatVisible\": 1, \"thermostatOperationMode\": \"autonomous\"}";
  117. updateRemoteTemp(false);
  118. }
  119. wsSend(message.c_str());
  120. #endif
  121. }
  122. //------------------------------------------------------------------------------
  123. void updateRemoteTemp(bool remote_temp_actual) {
  124. #if WEB_SUPPORT
  125. char tmp_str[16];
  126. if (remote_temp_actual) {
  127. dtostrf(_remote_temp.temp, 1, 1, tmp_str);
  128. } else {
  129. strcpy(tmp_str, "\"?\"");
  130. }
  131. char buffer[128];
  132. snprintf_P(buffer, sizeof(buffer), PSTR("{\"thermostatVisible\": 1, \"remoteTmp\": %s}"), tmp_str);
  133. wsSend(buffer);
  134. #endif
  135. }
  136. //------------------------------------------------------------------------------
  137. // MQTT
  138. //------------------------------------------------------------------------------
  139. void thermostatMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  140. if (type == MQTT_CONNECT_EVENT) {
  141. mqttSubscribeRaw(thermostat_remote_sensor_topic.c_str());
  142. mqttSubscribe(MQTT_TOPIC_HOLD_TEMP);
  143. _temp_range.ask_interval = ASK_TEMP_RANGE_INTERVAL_INITIAL;
  144. _temp_range.ask_time = millis();
  145. }
  146. if (type == MQTT_MESSAGE_EVENT) {
  147. // Match topic
  148. String t = mqttMagnitude((char *) topic);
  149. if (strcmp(topic, thermostat_remote_sensor_topic.c_str()) != 0
  150. && !t.equals(MQTT_TOPIC_HOLD_TEMP))
  151. return;
  152. // Parse JSON input
  153. DynamicJsonBuffer jsonBuffer;
  154. JsonObject& root = jsonBuffer.parseObject(payload);
  155. if (!root.success()) {
  156. DEBUG_MSG_P(PSTR("[THERMOSTAT] Error parsing data\n"));
  157. return;
  158. }
  159. // Check rempte sensor temperature
  160. if (strcmp(topic, thermostat_remote_sensor_topic.c_str()) == 0) {
  161. if (root.containsKey(magnitudeTopic(MAGNITUDE_TEMPERATURE))) {
  162. String remote_temp = root[magnitudeTopic(MAGNITUDE_TEMPERATURE)];
  163. _remote_temp.temp = remote_temp.toFloat();
  164. _remote_temp.last_update = millis();
  165. _remote_temp.need_display_update = true;
  166. DEBUG_MSG_P(PSTR("[THERMOSTAT] Remote sensor temperature: %s\n"), remote_temp.c_str());
  167. updateRemoteTemp(true);
  168. }
  169. }
  170. // Check temperature range change
  171. if (t.equals(MQTT_TOPIC_HOLD_TEMP)) {
  172. if (root.containsKey(MQTT_TOPIC_HOLD_TEMP_MIN)) {
  173. int t_min = root[MQTT_TOPIC_HOLD_TEMP_MIN];
  174. int t_max = root[MQTT_TOPIC_HOLD_TEMP_MAX];
  175. if (t_min < THERMOSTAT_TEMP_RANGE_MIN_MIN || t_min > THERMOSTAT_TEMP_RANGE_MIN_MAX ||
  176. t_max < THERMOSTAT_TEMP_RANGE_MAX_MIN || t_max > THERMOSTAT_TEMP_RANGE_MAX_MAX) {
  177. DEBUG_MSG_P(PSTR("[THERMOSTAT] Hold temperature range error\n"));
  178. return;
  179. }
  180. _temp_range.min = root[MQTT_TOPIC_HOLD_TEMP_MIN];
  181. _temp_range.max = root[MQTT_TOPIC_HOLD_TEMP_MAX];
  182. setSetting(NAME_TEMP_RANGE_MIN, _temp_range.min);
  183. setSetting(NAME_TEMP_RANGE_MAX, _temp_range.max);
  184. saveSettings();
  185. _temp_range.ask_interval = ASK_TEMP_RANGE_INTERVAL_REGULAR;
  186. _temp_range.last_update = millis();
  187. _temp_range.need_display_update = true;
  188. DEBUG_MSG_P(PSTR("[THERMOSTAT] Hold temperature range: (%d - %d)\n"), _temp_range.min, _temp_range.max);
  189. // Update websocket clients
  190. #if WEB_SUPPORT
  191. char buffer[100];
  192. snprintf_P(buffer, sizeof(buffer), PSTR("{\"thermostatVisible\": 1, \"tempRangeMin\": %d, \"tempRangeMax\": %d}"), _temp_range.min, _temp_range.max);
  193. wsSend(buffer);
  194. #endif
  195. } else {
  196. DEBUG_MSG_P(PSTR("[THERMOSTAT] Error temperature range data\n"));
  197. }
  198. }
  199. }
  200. }
  201. #if MQTT_SUPPORT
  202. //------------------------------------------------------------------------------
  203. void thermostatSetupMQTT() {
  204. mqttRegister(thermostatMQTTCallback);
  205. }
  206. #endif
  207. //------------------------------------------------------------------------------
  208. void notifyRangeChanged(bool min) {
  209. DEBUG_MSG_P(PSTR("[THERMOSTAT] notifyRangeChanged %s = %d\n"), min ? "MIN" : "MAX", min ? _temp_range.min : _temp_range.max);
  210. char tmp_str[6];
  211. sprintf(tmp_str, "%d", min ? _temp_range.min : _temp_range.max);
  212. mqttSend(min ? MQTT_TOPIC_NOTIFY_TEMP_RANGE_MIN : MQTT_TOPIC_NOTIFY_TEMP_RANGE_MAX, tmp_str, true);
  213. }
  214. //------------------------------------------------------------------------------
  215. // Setup
  216. //------------------------------------------------------------------------------
  217. void commonSetup() {
  218. _thermostat_enabled = getSetting(NAME_THERMOSTAT_ENABLED).toInt() == 1;
  219. DEBUG_MSG_P(PSTR("[THERMOSTAT] _thermostat_enabled = %d\n"), _thermostat_enabled);
  220. _thermostat_mode_cooler = getSetting(NAME_THERMOSTAT_MODE).toInt() == 1;
  221. DEBUG_MSG_P(PSTR("[THERMOSTAT] _thermostat_mode_cooler = %d\n"), _thermostat_mode_cooler);
  222. _temp_range.min = getSetting(NAME_TEMP_RANGE_MIN, THERMOSTAT_TEMP_RANGE_MIN).toInt();
  223. _temp_range.max = getSetting(NAME_TEMP_RANGE_MAX, THERMOSTAT_TEMP_RANGE_MAX).toInt();
  224. DEBUG_MSG_P(PSTR("[THERMOSTAT] _temp_range.min = %d\n"), _temp_range.min);
  225. DEBUG_MSG_P(PSTR("[THERMOSTAT] _temp_range.max = %d\n"), _temp_range.max);
  226. _thermostat.remote_sensor_name = getSetting(NAME_REMOTE_SENSOR_NAME);
  227. thermostat_remote_sensor_topic = _thermostat.remote_sensor_name + String("/") + String(MQTT_TOPIC_JSON);
  228. _thermostat_remote_temp_max_wait = getSetting(NAME_REMOTE_TEMP_MAX_WAIT, THERMOSTAT_REMOTE_TEMP_MAX_WAIT).toInt() * MILLIS_IN_SEC;
  229. _thermostat_alone_on_time = getSetting(NAME_ALONE_ON_TIME, THERMOSTAT_ALONE_ON_TIME).toInt() * MILLIS_IN_MIN;
  230. _thermostat_alone_off_time = getSetting(NAME_ALONE_OFF_TIME, THERMOSTAT_ALONE_OFF_TIME).toInt() * MILLIS_IN_MIN;
  231. _thermostat_max_on_time = getSetting(NAME_MAX_ON_TIME, THERMOSTAT_MAX_ON_TIME).toInt() * MILLIS_IN_MIN;
  232. _thermostat_min_off_time = getSetting(NAME_MIN_OFF_TIME, THERMOSTAT_MIN_OFF_TIME).toInt() * MILLIS_IN_MIN;
  233. }
  234. //------------------------------------------------------------------------------
  235. void thermostatConfigure() {
  236. commonSetup();
  237. _thermostat.temperature_source = temp_none;
  238. _thermostat_burn_total = getSetting(NAME_BURN_TOTAL).toInt();
  239. _thermostat_burn_today = getSetting(NAME_BURN_TODAY).toInt();
  240. _thermostat_burn_yesterday = getSetting(NAME_BURN_YESTERDAY).toInt();
  241. _thermostat_burn_this_month = getSetting(NAME_BURN_THIS_MONTH).toInt();
  242. _thermostat_burn_prev_month = getSetting(NAME_BURN_PREV_MONTH).toInt();
  243. _thermostat_burn_day = getSetting(NAME_BURN_DAY).toInt();
  244. _thermostat_burn_month = getSetting(NAME_BURN_MONTH).toInt();
  245. }
  246. //------------------------------------------------------------------------------
  247. void _thermostatReload() {
  248. int prev_temp_range_min = _temp_range.min;
  249. int prev_temp_range_max = _temp_range.max;
  250. commonSetup();
  251. if (_temp_range.min != prev_temp_range_min)
  252. notifyRangeChanged(true);
  253. if (_temp_range.max != prev_temp_range_max)
  254. notifyRangeChanged(false);
  255. }
  256. #if WEB_SUPPORT
  257. //------------------------------------------------------------------------------
  258. void _thermostatWebSocketOnConnected(JsonObject& root) {
  259. root["thermostatEnabled"] = thermostatEnabled();
  260. root["thermostatMode"] = thermostatModeCooler();
  261. root["thermostatVisible"] = 1;
  262. root[NAME_TEMP_RANGE_MIN] = _temp_range.min;
  263. root[NAME_TEMP_RANGE_MAX] = _temp_range.max;
  264. root[NAME_REMOTE_SENSOR_NAME] = _thermostat.remote_sensor_name;
  265. root[NAME_REMOTE_TEMP_MAX_WAIT] = _thermostat_remote_temp_max_wait / MILLIS_IN_SEC;
  266. root[NAME_MAX_ON_TIME] = _thermostat_max_on_time / MILLIS_IN_MIN;
  267. root[NAME_MIN_OFF_TIME] = _thermostat_min_off_time / MILLIS_IN_MIN;
  268. root[NAME_ALONE_ON_TIME] = _thermostat_alone_on_time / MILLIS_IN_MIN;
  269. root[NAME_ALONE_OFF_TIME] = _thermostat_alone_off_time / MILLIS_IN_MIN;
  270. root[NAME_BURN_TODAY] = _thermostat_burn_today;
  271. root[NAME_BURN_YESTERDAY] = _thermostat_burn_yesterday;
  272. root[NAME_BURN_THIS_MONTH] = _thermostat_burn_this_month;
  273. root[NAME_BURN_PREV_MONTH] = _thermostat_burn_prev_month;
  274. root[NAME_BURN_TOTAL] = _thermostat_burn_total;
  275. if (_thermostat.temperature_source == temp_remote) {
  276. root[NAME_OPERATION_MODE] = "remote temperature";
  277. root["remoteTmp"] = _remote_temp.temp;
  278. } else if (_thermostat.temperature_source == temp_local) {
  279. root[NAME_OPERATION_MODE] = "local temperature";
  280. root["remoteTmp"] = "?";
  281. } else {
  282. root[NAME_OPERATION_MODE] = "autonomous";
  283. root["remoteTmp"] = "?";
  284. }
  285. }
  286. //------------------------------------------------------------------------------
  287. bool _thermostatWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  288. if (strncmp(key, NAME_THERMOSTAT_ENABLED, strlen(NAME_THERMOSTAT_ENABLED)) == 0) return true;
  289. if (strncmp(key, NAME_THERMOSTAT_MODE, strlen(NAME_THERMOSTAT_MODE)) == 0) return true;
  290. if (strncmp(key, NAME_TEMP_RANGE_MIN, strlen(NAME_TEMP_RANGE_MIN)) == 0) return true;
  291. if (strncmp(key, NAME_TEMP_RANGE_MAX, strlen(NAME_TEMP_RANGE_MAX)) == 0) return true;
  292. if (strncmp(key, NAME_REMOTE_SENSOR_NAME, strlen(NAME_REMOTE_SENSOR_NAME)) == 0) return true;
  293. if (strncmp(key, NAME_REMOTE_TEMP_MAX_WAIT, strlen(NAME_REMOTE_TEMP_MAX_WAIT)) == 0) return true;
  294. if (strncmp(key, NAME_MAX_ON_TIME, strlen(NAME_MAX_ON_TIME)) == 0) return true;
  295. if (strncmp(key, NAME_MIN_OFF_TIME, strlen(NAME_MIN_OFF_TIME)) == 0) return true;
  296. if (strncmp(key, NAME_ALONE_ON_TIME, strlen(NAME_ALONE_ON_TIME)) == 0) return true;
  297. if (strncmp(key, NAME_ALONE_OFF_TIME, strlen(NAME_ALONE_OFF_TIME)) == 0) return true;
  298. return false;
  299. }
  300. //------------------------------------------------------------------------------
  301. void _thermostatWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  302. if (strcmp(action, "thermostat_reset_counters") == 0) resetBurnCounters();
  303. }
  304. #endif
  305. //------------------------------------------------------------------------------
  306. void thermostatSetup() {
  307. thermostatConfigure();
  308. #if MQTT_SUPPORT
  309. thermostatSetupMQTT();
  310. #endif
  311. // Websockets
  312. #if WEB_SUPPORT
  313. wsRegister()
  314. .onConnected(_thermostatWebSocketOnConnected)
  315. .onKeyCheck(_thermostatWebSocketOnKeyCheck)
  316. .onAction(_thermostatWebSocketOnAction);
  317. #endif
  318. espurnaRegisterLoop(thermostatLoop);
  319. espurnaRegisterReload(_thermostatReload);
  320. }
  321. //------------------------------------------------------------------------------
  322. void sendTempRangeRequest() {
  323. DEBUG_MSG_P(PSTR("[THERMOSTAT] sendTempRangeRequest\n"));
  324. mqttSend(MQTT_TOPIC_ASK_TEMP_RANGE, "", true);
  325. }
  326. //------------------------------------------------------------------------------
  327. void setThermostatState(bool state) {
  328. DEBUG_MSG_P(PSTR("[THERMOSTAT] setThermostatState: %s\n"), state ? "ON" : "OFF");
  329. relayStatus(THERMOSTAT_RELAY, state, mqttForward(), false);
  330. _thermostat.last_switch = millis();
  331. // Send thermostat change state event to subscribers
  332. for (unsigned char i = 0; i < _thermostat_callbacks.size(); i++) {
  333. (_thermostat_callbacks[i])(state);
  334. }
  335. }
  336. //------------------------------------------------------------------------------
  337. void debugPrintSwitch(bool state, double temp) {
  338. char tmp_str[16];
  339. dtostrf(temp, 1, 1, tmp_str);
  340. DEBUG_MSG_P(PSTR("[THERMOSTAT] switch %s, temp: %s, min: %d, max: %d, mode: %s, relay: %s, last switch %d\n"),
  341. state ? "ON" : "OFF", tmp_str, _temp_range.min, _temp_range.max, _thermostat_mode_cooler ? "COOLER" : "HEATER", relayStatus(THERMOSTAT_RELAY) ? "ON" : "OFF", millis() - _thermostat.last_switch);
  342. }
  343. //------------------------------------------------------------------------------
  344. inline bool lastSwitchEarlierThan(unsigned int comparing_time) {
  345. return millis() - _thermostat.last_switch > comparing_time;
  346. }
  347. //------------------------------------------------------------------------------
  348. inline void switchThermostat(bool state, double temp) {
  349. debugPrintSwitch(state, temp);
  350. setThermostatState(state);
  351. }
  352. //------------------------------------------------------------------------------
  353. //----------- Main function that make decision ---------------------------------
  354. //------------------------------------------------------------------------------
  355. void checkTempAndAdjustRelay(double temp) {
  356. if (_thermostat_mode_cooler == false) { // Main operation mode. Thermostat is HEATER.
  357. // if thermostat switched ON and t > max - switch it OFF and start cooling
  358. if (relayStatus(THERMOSTAT_RELAY) && temp > _temp_range.max) {
  359. _thermostat_cycle = cooling;
  360. switchThermostat(false, temp);
  361. // if thermostat switched ON for max time - switch it OFF for rest
  362. } else if (relayStatus(THERMOSTAT_RELAY) && lastSwitchEarlierThan(_thermostat_max_on_time)) {
  363. switchThermostat(false, temp);
  364. // if t < min and thermostat switched OFF for at least minimum time - switch it ON and start
  365. } else if (!relayStatus(THERMOSTAT_RELAY) && temp < _temp_range.min
  366. && (_thermostat.last_switch == 0 || lastSwitchEarlierThan(_thermostat_min_off_time))) {
  367. _thermostat_cycle = heating;
  368. switchThermostat(true, temp);
  369. // if heating cycle and thermostat switchaed OFF for more than min time - switch it ON
  370. // continue heating cycle
  371. } else if (!relayStatus(THERMOSTAT_RELAY) && _thermostat_cycle == heating
  372. && lastSwitchEarlierThan(_thermostat_min_off_time)) {
  373. switchThermostat(true, temp);
  374. }
  375. } else { // Thermostat is COOLER. Inverse logic.
  376. // if thermostat switched ON and t < min - switch it OFF and start heating
  377. if (relayStatus(THERMOSTAT_RELAY) && temp < _temp_range.min) {
  378. _thermostat_cycle = heating;
  379. switchThermostat(false, temp);
  380. // if thermostat switched ON for max time - switch it OFF for rest
  381. } else if (relayStatus(THERMOSTAT_RELAY) && lastSwitchEarlierThan(_thermostat_max_on_time)) {
  382. switchThermostat(false, temp);
  383. // if t > max and thermostat switched OFF for at least minimum time - switch it ON and start
  384. } else if (!relayStatus(THERMOSTAT_RELAY) && temp > _temp_range.max
  385. && (_thermostat.last_switch == 0 || lastSwitchEarlierThan(_thermostat_min_off_time))) {
  386. _thermostat_cycle = cooling;
  387. switchThermostat(true, temp);
  388. // if cooling cycle and thermostat switchaed OFF for more than min time - switch it ON
  389. // continue cooling cycle
  390. } else if (!relayStatus(THERMOSTAT_RELAY) && _thermostat_cycle == cooling
  391. && lastSwitchEarlierThan(_thermostat_min_off_time)) {
  392. switchThermostat(true, temp);
  393. }
  394. }
  395. }
  396. //------------------------------------------------------------------------------
  397. void updateCounters() {
  398. if (relayStatus(THERMOSTAT_RELAY)) {
  399. setSetting(NAME_BURN_TOTAL, ++_thermostat_burn_total);
  400. setSetting(NAME_BURN_TODAY, ++_thermostat_burn_today);
  401. setSetting(NAME_BURN_THIS_MONTH, ++_thermostat_burn_this_month);
  402. }
  403. if (ntpSynced()) {
  404. String value = NTP.getDateStr();
  405. unsigned int day = value.substring(0, 2).toInt();
  406. unsigned int month = value.substring(3, 5).toInt();
  407. if (day != _thermostat_burn_day) {
  408. _thermostat_burn_yesterday = _thermostat_burn_today;
  409. _thermostat_burn_today = 0;
  410. _thermostat_burn_day = day;
  411. setSetting(NAME_BURN_YESTERDAY, _thermostat_burn_yesterday);
  412. setSetting(NAME_BURN_TODAY, _thermostat_burn_today);
  413. setSetting(NAME_BURN_DAY, _thermostat_burn_day);
  414. }
  415. if (month != _thermostat_burn_month) {
  416. _thermostat_burn_prev_month = _thermostat_burn_this_month;
  417. _thermostat_burn_this_month = 0;
  418. _thermostat_burn_month = month;
  419. setSetting(NAME_BURN_PREV_MONTH, _thermostat_burn_prev_month);
  420. setSetting(NAME_BURN_THIS_MONTH, _thermostat_burn_this_month);
  421. setSetting(NAME_BURN_MONTH, _thermostat_burn_month);
  422. }
  423. }
  424. }
  425. //------------------------------------------------------------------------------
  426. double getLocalTemperature() {
  427. #if SENSOR_SUPPORT
  428. for (byte i=0; i<magnitudeCount(); i++) {
  429. if (magnitudeType(i) == MAGNITUDE_TEMPERATURE) {
  430. double temp = magnitudeValue(i);
  431. char tmp_str[16];
  432. dtostrf(temp, 1, 1, tmp_str);
  433. DEBUG_MSG_P(PSTR("[THERMOSTAT] getLocalTemperature temp: %s\n"), tmp_str);
  434. return temp > -0.1 && temp < 0.1 ? DBL_MIN : temp;
  435. }
  436. }
  437. #endif
  438. return DBL_MIN;
  439. }
  440. //------------------------------------------------------------------------------
  441. double getLocalHumidity() {
  442. #if SENSOR_SUPPORT
  443. for (byte i=0; i<magnitudeCount(); i++) {
  444. if (magnitudeType(i) == MAGNITUDE_HUMIDITY) {
  445. double hum = magnitudeValue(i);
  446. char tmp_str[16];
  447. dtostrf(hum, 1, 0, tmp_str);
  448. DEBUG_MSG_P(PSTR("[THERMOSTAT] getLocalHumidity hum: %s\%\n"), tmp_str);
  449. return hum > -0.1 && hum < 0.1 ? DBL_MIN : hum;
  450. }
  451. }
  452. #endif
  453. return DBL_MIN;
  454. }
  455. //------------------------------------------------------------------------------
  456. // Loop
  457. //------------------------------------------------------------------------------
  458. void thermostatLoop(void) {
  459. if (!thermostatEnabled())
  460. return;
  461. // Update temperature range
  462. if (mqttConnected()) {
  463. if (millis() - _temp_range.ask_time > _temp_range.ask_interval) {
  464. _temp_range.ask_time = millis();
  465. sendTempRangeRequest();
  466. }
  467. }
  468. // Update thermostat state
  469. if (millis() - _thermostat.last_update > THERMOSTAT_STATE_UPDATE_INTERVAL) {
  470. _thermostat.last_update = millis();
  471. updateCounters();
  472. unsigned int last_temp_src = _thermostat.temperature_source;
  473. if (_remote_temp.last_update != 0 && millis() - _remote_temp.last_update < _thermostat_remote_temp_max_wait) {
  474. // we have remote temp
  475. _thermostat.temperature_source = temp_remote;
  476. DEBUG_MSG_P(PSTR("[THERMOSTAT] setup thermostat by remote temperature\n"));
  477. checkTempAndAdjustRelay(_remote_temp.temp);
  478. } else if (getLocalTemperature() != DBL_MIN) {
  479. // we have local temp
  480. _thermostat.temperature_source = temp_local;
  481. DEBUG_MSG_P(PSTR("[THERMOSTAT] setup thermostat by local temperature\n"));
  482. checkTempAndAdjustRelay(getLocalTemperature());
  483. // updateRemoteTemp(false);
  484. } else {
  485. // we don't have any temp - switch thermostat on for N minutes every hour
  486. _thermostat.temperature_source = temp_none;
  487. DEBUG_MSG_P(PSTR("[THERMOSTAT] setup thermostat by timeout\n"));
  488. if (relayStatus(THERMOSTAT_RELAY) && millis() - _thermostat.last_switch > _thermostat_alone_on_time) {
  489. setThermostatState(false);
  490. } else if (!relayStatus(THERMOSTAT_RELAY) && millis() - _thermostat.last_switch > _thermostat_alone_off_time) {
  491. setThermostatState(false);
  492. }
  493. }
  494. if (last_temp_src != _thermostat.temperature_source) {
  495. updateOperationMode();
  496. }
  497. }
  498. }
  499. //------------------------------------------------------------------------------
  500. String getBurnTimeStr(unsigned int burn_time) {
  501. char burnTimeStr[18] = { 0 };
  502. if (burn_time < 60) {
  503. sprintf(burnTimeStr, "%d мин.", burn_time);
  504. } else {
  505. sprintf(burnTimeStr, "%d ч. %d мин.", (int)floor(burn_time / 60), burn_time % 60);
  506. }
  507. return String(burnTimeStr);
  508. }
  509. //------------------------------------------------------------------------------
  510. void resetBurnCounters() {
  511. DEBUG_MSG_P(PSTR("[THERMOSTAT] resetBurnCounters\n"));
  512. setSetting(NAME_BURN_TOTAL, 0);
  513. setSetting(NAME_BURN_TODAY, 0);
  514. setSetting(NAME_BURN_YESTERDAY, 0);
  515. setSetting(NAME_BURN_THIS_MONTH, 0);
  516. setSetting(NAME_BURN_PREV_MONTH, 0);
  517. _thermostat_burn_total = 0;
  518. _thermostat_burn_today = 0;
  519. _thermostat_burn_yesterday = 0;
  520. _thermostat_burn_this_month = 0;
  521. _thermostat_burn_prev_month = 0;
  522. }
  523. #endif // THERMOSTAT_SUPPORT
  524. //#######################################################################
  525. // ___ _ _
  526. // | \ (_) ___ _ __ | | __ _ _ _
  527. // | |) || |(_-<| '_ \| |/ _` || || |
  528. // |___/ |_|/__/| .__/|_|\__,_| \_, |
  529. // |_| |__/
  530. //#######################################################################
  531. #if THERMOSTAT_DISPLAY_SUPPORT
  532. #include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
  533. #define wifi_on_width 16
  534. #define wifi_on_height 16
  535. const char wifi_on_bits[] PROGMEM = {
  536. 0x00, 0x00, 0x0E, 0x00, 0x7E, 0x00, 0xFE, 0x01, 0xE0, 0x03, 0x80, 0x07,
  537. 0x02, 0x0F, 0x1E, 0x1E, 0x3E, 0x1C, 0x78, 0x38, 0xE0, 0x38, 0xC0, 0x31,
  538. 0xC6, 0x71, 0x8E, 0x71, 0x8E, 0x73, 0x00, 0x00, };
  539. #define mqtt_width 16
  540. #define mqtt_height 16
  541. const char mqtt_bits[] PROGMEM = {
  542. 0x00, 0x00, 0x00, 0x08, 0x00, 0x18, 0x00, 0x38, 0xEA, 0x7F, 0xEA, 0x7F,
  543. 0x00, 0x38, 0x10, 0x18, 0x18, 0x08, 0x1C, 0x00, 0xFE, 0x57, 0xFE, 0x57,
  544. 0x1C, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, };
  545. #define remote_temp_width 16
  546. #define remote_temp_height 16
  547. const char remote_temp_bits[] PROGMEM = {
  548. 0x00, 0x00, 0xE0, 0x18, 0x10, 0x25, 0x10, 0x25, 0x90, 0x19, 0x50, 0x01,
  549. 0x50, 0x01, 0xD0, 0x01, 0x50, 0x01, 0x50, 0x01, 0xD0, 0x01, 0x50, 0x01,
  550. 0xE0, 0x00, 0xE0, 0x00, 0xE0, 0x00, 0x00, 0x00, };
  551. #define server_width 16
  552. #define server_height 16
  553. const char server_bits[] PROGMEM = {
  554. 0x00, 0x00, 0xF8, 0x1F, 0xFC, 0x3F, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30,
  555. 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0xF8, 0x1F, 0xFC, 0x3F, 0xFE, 0x7F,
  556. 0x1E, 0x78, 0xFE, 0x7F, 0xFC, 0x3F, 0x00, 0x00, };
  557. #define LOCAL_TEMP_UPDATE_INTERVAL 60000
  558. #define LOCAL_HUM_UPDATE_INTERVAL 61000
  559. SSD1306 display(0x3c, 1, 3);
  560. unsigned long _local_temp_last_update = 0xFFFF;
  561. unsigned long _local_hum_last_update = 0xFFFF;
  562. bool _display_wifi_status = true;
  563. bool _display_mqtt_status = true;
  564. bool _display_server_status = true;
  565. bool _display_remote_temp_status = true;
  566. bool _display_need_refresh = false;
  567. bool _temp_range_need_update = true;
  568. //------------------------------------------------------------------------------
  569. void drawIco(int16_t x, int16_t y, const char *ico, bool on = true) {
  570. display.drawIco16x16(x, y, ico, !on);
  571. _display_need_refresh = true;
  572. }
  573. //------------------------------------------------------------------------------
  574. void display_wifi_status(bool on) {
  575. _display_wifi_status = on;
  576. drawIco(0, 0, wifi_on_bits, on);
  577. }
  578. //------------------------------------------------------------------------------
  579. void display_mqtt_status(bool on) {
  580. _display_mqtt_status = on;
  581. drawIco(17, 0, mqtt_bits, on);
  582. }
  583. //------------------------------------------------------------------------------
  584. void display_server_status(bool on) {
  585. _display_server_status = on;
  586. drawIco(34, 0, server_bits, on);
  587. }
  588. //------------------------------------------------------------------------------
  589. void display_remote_temp_status(bool on) {
  590. _display_remote_temp_status = on;
  591. drawIco(51, 0, remote_temp_bits, on);
  592. }
  593. //------------------------------------------------------------------------------
  594. void display_temp_range() {
  595. _temp_range.need_display_update = false;
  596. display.setColor(BLACK);
  597. display.fillRect(68, 0, 60, 16);
  598. display.setColor(WHITE);
  599. display.setTextAlignment(TEXT_ALIGN_RIGHT);
  600. display.setFont(ArialMT_Plain_16);
  601. String temp_range = String(_temp_range.min) + "°- " + String(_temp_range.max) + "°";
  602. display.drawString(128, 0, temp_range);
  603. _display_need_refresh = true;
  604. }
  605. //------------------------------------------------------------------------------
  606. void display_remote_temp() {
  607. _remote_temp.need_display_update = false;
  608. display.setColor(BLACK);
  609. display.fillRect(0, 16, 128, 16);
  610. display.setColor(WHITE);
  611. display.setFont(ArialMT_Plain_16);
  612. display.setTextAlignment(TEXT_ALIGN_LEFT);
  613. String temp_range_title = String("Remote t");
  614. display.drawString(0, 16, temp_range_title);
  615. String temp_range_vol = String("= ") + (_display_remote_temp_status ? String(_remote_temp.temp, 1) : String("?")) + "°";
  616. display.drawString(75, 16, temp_range_vol);
  617. _display_need_refresh = true;
  618. }
  619. //------------------------------------------------------------------------------
  620. void display_local_temp() {
  621. display.setColor(BLACK);
  622. display.fillRect(0, 32, 128, 16);
  623. display.setColor(WHITE);
  624. display.setFont(ArialMT_Plain_16);
  625. display.setTextAlignment(TEXT_ALIGN_LEFT);
  626. String local_temp_title = String("Local t");
  627. display.drawString(0, 32, local_temp_title);
  628. String local_temp_vol = String("= ") + (getLocalTemperature() != DBL_MIN ? String(getLocalTemperature(), 1) : String("?")) + "°";
  629. display.drawString(75, 32, local_temp_vol);
  630. _display_need_refresh = true;
  631. }
  632. //------------------------------------------------------------------------------
  633. void display_local_humidity() {
  634. display.setColor(BLACK);
  635. display.fillRect(0, 48, 128, 16);
  636. display.setColor(WHITE);
  637. display.setFont(ArialMT_Plain_16);
  638. display.setTextAlignment(TEXT_ALIGN_LEFT);
  639. String local_hum_title = String("Local h ");
  640. display.drawString(0, 48, local_hum_title);
  641. String local_hum_vol = String("= ") + (getLocalHumidity() != DBL_MIN ? String(getLocalHumidity(), 0) : String("?")) + "%";
  642. display.drawString(75, 48, local_hum_vol);
  643. _display_need_refresh = true;
  644. }
  645. //------------------------------------------------------------------------------
  646. // Setup
  647. //------------------------------------------------------------------------------
  648. void displaySetup() {
  649. display.init();
  650. display.flipScreenVertically();
  651. // display.setFont(ArialMT_Plain_24);
  652. // display.setTextAlignment(TEXT_ALIGN_CENTER);
  653. // display.drawString(64, 17, "Thermostat");
  654. espurnaRegisterLoop(displayLoop);
  655. }
  656. //------------------------------------------------------------------------------
  657. void displayLoop() {
  658. _display_need_refresh = false;
  659. //------------------------------------------------------------------------------
  660. // Indicators
  661. //------------------------------------------------------------------------------
  662. if (!_display_wifi_status) {
  663. if (wifiConnected() && WiFi.getMode() != WIFI_AP)
  664. display_wifi_status(true);
  665. } else if (!wifiConnected() || WiFi.getMode() == WIFI_AP) {
  666. display_wifi_status(false);
  667. }
  668. if (!_display_mqtt_status) {
  669. if (mqttConnected())
  670. display_mqtt_status(true);
  671. } else if (!mqttConnected()) {
  672. display_mqtt_status(false);
  673. }
  674. if (millis() - _temp_range.last_update < THERMOSTAT_SERVER_LOST_INTERVAL) {
  675. if (!_display_server_status)
  676. display_server_status(true);
  677. } else if (_display_server_status) {
  678. display_server_status(false);
  679. }
  680. if (millis() - _remote_temp.last_update < _thermostat_remote_temp_max_wait) {
  681. if (!_display_remote_temp_status)
  682. display_remote_temp_status(true);
  683. } else if (_display_remote_temp_status) {
  684. display_remote_temp_status(false);
  685. display_remote_temp();
  686. }
  687. //------------------------------------------------------------------------------
  688. // Temp range
  689. //------------------------------------------------------------------------------
  690. if (_temp_range.need_display_update) {
  691. display_temp_range();
  692. }
  693. //------------------------------------------------------------------------------
  694. // Remote temp
  695. //------------------------------------------------------------------------------
  696. if (_remote_temp.need_display_update) {
  697. display_remote_temp();
  698. }
  699. //------------------------------------------------------------------------------
  700. // Local temp
  701. //------------------------------------------------------------------------------
  702. if (millis() - _local_temp_last_update > LOCAL_TEMP_UPDATE_INTERVAL) {
  703. _local_temp_last_update = millis();
  704. display_local_temp();
  705. }
  706. //------------------------------------------------------------------------------
  707. // Local temp
  708. //------------------------------------------------------------------------------
  709. if (millis() - _local_hum_last_update > LOCAL_HUM_UPDATE_INTERVAL) {
  710. _local_hum_last_update = millis();
  711. display_local_humidity();
  712. }
  713. //------------------------------------------------------------------------------
  714. // Display update
  715. //------------------------------------------------------------------------------
  716. if (_display_need_refresh) {
  717. yield();
  718. display.display();
  719. }
  720. }
  721. #endif // THERMOSTAT_DISPLAY_SUPPORT