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.

843 lines
33 KiB

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