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.

851 lines
34 KiB

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