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.

328 lines
10 KiB

6 years ago
6 years ago
  1. /*
  2. SCHEDULER MODULE
  3. Copyright (C) 2017 by faina09
  4. Adapted by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #include "scheduler.h"
  7. #if SCHEDULER_SUPPORT
  8. #include "broker.h"
  9. #include "light.h"
  10. #include "ntp.h"
  11. #include "relay.h"
  12. #include "ws.h"
  13. constexpr const int SchedulerDummySwitchId = 0xff;
  14. int _sch_restore = 0;
  15. // -----------------------------------------------------------------------------
  16. #if WEB_SUPPORT
  17. bool _schWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  18. return (strncmp(key, "sch", 3) == 0);
  19. }
  20. void _schWebSocketOnVisible(JsonObject& root) {
  21. if (!relayCount()) return;
  22. root["schVisible"] = 1;
  23. }
  24. void _schWebSocketOnConnected(JsonObject &root){
  25. if (!relayCount()) return;
  26. JsonObject &schedules = root.createNestedObject("schedules");
  27. schedules["max"] = SCHEDULER_MAX_SCHEDULES;
  28. JsonArray& enabled = schedules.createNestedArray("schEnabled");
  29. JsonArray& switch_ = schedules.createNestedArray("schSwitch");
  30. JsonArray& action = schedules.createNestedArray("schAction");
  31. JsonArray& type = schedules.createNestedArray("schType");
  32. JsonArray& hour = schedules.createNestedArray("schHour");
  33. JsonArray& minute = schedules.createNestedArray("schMinute");
  34. JsonArray& utc = schedules.createNestedArray("schUTC");
  35. JsonArray& weekdays = schedules.createNestedArray("schWDs");
  36. uint8_t size = 0;
  37. for (unsigned char i = 0; i < SCHEDULER_MAX_SCHEDULES; i++) {
  38. if (!getSetting({"schSwitch", i}).length()) break;
  39. ++size;
  40. enabled.add(getSetting({"schEnabled", i}, false) ? 1 : 0);
  41. utc.add(getSetting({"schUTC", i}, 0));
  42. switch_.add(getSetting({"schSwitch", i}, 0));
  43. action.add(getSetting({"schAction", i}, 0));
  44. type.add(getSetting({"schType", i}, SCHEDULER_TYPE_SWITCH));
  45. hour.add(getSetting({"schHour", i}, 0));
  46. minute.add(getSetting({"schMinute", i}, 0));
  47. weekdays.add(getSetting({"schWDs", i}, SCHEDULER_WEEKDAYS));
  48. }
  49. schedules["size"] = size;
  50. schedules["start"] = 0;
  51. }
  52. #endif // WEB_SUPPORT
  53. // -----------------------------------------------------------------------------
  54. void _schConfigure() {
  55. bool delete_flag = false;
  56. for (unsigned char i = 0; i < SCHEDULER_MAX_SCHEDULES; i++) {
  57. int sch_switch = getSetting({"schSwitch", i}, SchedulerDummySwitchId);
  58. if (sch_switch == SchedulerDummySwitchId) delete_flag = true;
  59. if (delete_flag) {
  60. delSetting({"schEnabled", i});
  61. delSetting({"schSwitch", i});
  62. delSetting({"schAction", i});
  63. delSetting({"schHour", i});
  64. delSetting({"schMinute", i});
  65. delSetting({"schWDs", i});
  66. delSetting({"schType", i});
  67. delSetting({"schUTC", i});
  68. } else {
  69. #if DEBUG_SUPPORT
  70. bool sch_enabled = getSetting({"schEnabled", i}, false);
  71. int sch_action = getSetting({"schAction", i}, 0);
  72. int sch_hour = getSetting({"schHour", i}, 0);
  73. int sch_minute = getSetting({"schMinute", i}, 0);
  74. bool sch_utc = getSetting({"schUTC", i}, false);
  75. String sch_weekdays = getSetting({"schWDs", i}, SCHEDULER_WEEKDAYS);
  76. int sch_type = getSetting({"schType", i}, SCHEDULER_TYPE_SWITCH);
  77. DEBUG_MSG_P(
  78. PSTR("[SCH] Schedule #%d: %s #%d to %d at %02d:%02d %s on %s%s\n"),
  79. i, SCHEDULER_TYPE_SWITCH == sch_type ? "switch" : "channel", sch_switch,
  80. sch_action, sch_hour, sch_minute, sch_utc ? "UTC" : "local time",
  81. (char *) sch_weekdays.c_str(),
  82. sch_enabled ? "" : " (disabled)"
  83. );
  84. #endif // DEBUG_SUPPORT
  85. }
  86. }
  87. }
  88. bool _schIsThisWeekday(int day, const String& weekdays){
  89. // Convert from Sunday to Monday as day 1
  90. int w = day - 1;
  91. if (0 == w) w = 7;
  92. char pch;
  93. char * p = (char *) weekdays.c_str();
  94. unsigned char position = 0;
  95. while ((pch = p[position++])) {
  96. if ((pch - '0') == w) return true;
  97. }
  98. return false;
  99. }
  100. int _schMinutesLeft(int current_hour, int current_minute, int schedule_hour, int schedule_minute) {
  101. return (schedule_hour - current_hour) * 60 + schedule_minute - current_minute;
  102. }
  103. void _schAction(unsigned char sch_id, int sch_action, int sch_switch) {
  104. const auto sch_type = getSetting({"schType", sch_id}, SCHEDULER_TYPE_SWITCH);
  105. if (SCHEDULER_TYPE_SWITCH == sch_type) {
  106. DEBUG_MSG_P(PSTR("[SCH] Switching switch %d to %d\n"), sch_switch, sch_action);
  107. if (sch_action == 2) {
  108. relayToggle(sch_switch);
  109. } else {
  110. relayStatus(sch_switch, sch_action);
  111. }
  112. }
  113. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  114. if (SCHEDULER_TYPE_DIM == sch_type) {
  115. DEBUG_MSG_P(PSTR("[SCH] Set channel %d value to %d\n"), sch_switch, sch_action);
  116. lightChannel(sch_switch, sch_action);
  117. lightUpdate(true, true);
  118. }
  119. #endif
  120. }
  121. #if NTP_LEGACY_SUPPORT
  122. NtpCalendarWeekday _schGetWeekday(time_t timestamp, int daybefore) {
  123. if (daybefore > 0) {
  124. timestamp = timestamp - ((hour(timestamp) * SECS_PER_HOUR) + ((minute(timestamp) + 1) * SECS_PER_MIN) + second(timestamp) + (daybefore * SECS_PER_DAY));
  125. }
  126. // XXX: no
  127. time_t utc_timestamp = ntpLocal2UTC(timestamp);
  128. return NtpCalendarWeekday {
  129. weekday(timestamp), hour(timestamp), minute(timestamp),
  130. weekday(utc_timestamp), hour(utc_timestamp), minute(utc_timestamp)
  131. };
  132. }
  133. #else
  134. NtpCalendarWeekday _schGetWeekday(time_t timestamp, int daybefore) {
  135. tm utc_time;
  136. tm local_time;
  137. gmtime_r(&timestamp, &utc_time);
  138. if (daybefore > 0) {
  139. timestamp = timestamp - ((utc_time.tm_hour * secondsPerHour) + ((utc_time.tm_min + 1) * secondsPerMinute) + utc_time.tm_sec + (daybefore * secondsPerDay));
  140. gmtime_r(&timestamp, &utc_time);
  141. localtime_r(&timestamp, &local_time);
  142. } else {
  143. localtime_r(&timestamp, &local_time);
  144. }
  145. // TimeLib sunday is 1 instead of 0
  146. return NtpCalendarWeekday {
  147. local_time.tm_wday + 1, local_time.tm_hour, local_time.tm_min,
  148. utc_time.tm_wday + 1, utc_time.tm_hour, utc_time.tm_min
  149. };
  150. }
  151. #endif
  152. // If daybefore and relay is -1, check with current timestamp
  153. // Otherwise, modify it by moving 'daybefore' days back and only use the 'relay' id
  154. void _schCheck(int relay, int daybefore) {
  155. time_t timestamp = now();
  156. auto calendar_weekday = _schGetWeekday(timestamp, daybefore);
  157. int minimum_restore_time = -(60 * 24);
  158. int saved_action = -1;
  159. int saved_sch = -1;
  160. // Check schedules
  161. for (unsigned char i = 0; i < SCHEDULER_MAX_SCHEDULES; i++) {
  162. int sch_switch = getSetting({"schSwitch", i}, SchedulerDummySwitchId);
  163. if (sch_switch == SchedulerDummySwitchId) break;
  164. // Skip disabled schedules
  165. if (!getSetting({"schEnabled", i}, false)) continue;
  166. // Get the datetime used for the calculation
  167. const bool sch_utc = getSetting({"schUTC", i}, false);
  168. String sch_weekdays = getSetting({"schWDs", i}, SCHEDULER_WEEKDAYS);
  169. if (_schIsThisWeekday(sch_utc ? calendar_weekday.utc_wday : calendar_weekday.local_wday, sch_weekdays)) {
  170. int sch_hour = getSetting({"schHour", i}, 0);
  171. int sch_minute = getSetting({"schMinute", i}, 0);
  172. int sch_action = getSetting({"schAction", i}, 0);
  173. int sch_type = getSetting({"schType", i}, SCHEDULER_TYPE_SWITCH);
  174. int minutes_to_trigger = _schMinutesLeft(
  175. sch_utc ? calendar_weekday.utc_hour : calendar_weekday.local_hour,
  176. sch_utc ? calendar_weekday.utc_minute : calendar_weekday.local_minute,
  177. sch_hour, sch_minute
  178. );
  179. if (sch_type == SCHEDULER_TYPE_SWITCH && sch_switch == relay && sch_action != 2 && minutes_to_trigger < 0 && minutes_to_trigger > minimum_restore_time) {
  180. minimum_restore_time = minutes_to_trigger;
  181. saved_action = sch_action;
  182. saved_sch = i;
  183. }
  184. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  185. if (SCHEDULER_TYPE_DIM == sch_type && sch_switch == relay && minutes_to_trigger < 0 && minutes_to_trigger > minimum_restore_time) {
  186. minimum_restore_time = minutes_to_trigger;
  187. saved_action = sch_action;
  188. saved_sch = i;
  189. }
  190. #endif
  191. if (minutes_to_trigger == 0 && relay == -1) {
  192. _schAction(i, sch_action, sch_switch);
  193. DEBUG_MSG_P(PSTR("[SCH] Schedule #%d TRIGGERED!!\n"), i);
  194. // Show minutes to trigger every 15 minutes
  195. // or every minute if less than 15 minutes to scheduled time.
  196. // This only works for schedules on this same day.
  197. // For instance, if your scheduler is set for 00:01 you will only
  198. // get one notification before the trigger (at 00:00)
  199. } else if (minutes_to_trigger > 0 && relay == -1) {
  200. #if DEBUG_SUPPORT
  201. if ((minutes_to_trigger % 15 == 0) || (minutes_to_trigger < 15)) {
  202. DEBUG_MSG_P(
  203. PSTR("[SCH] %d minutes to trigger schedule #%d\n"),
  204. minutes_to_trigger, i
  205. );
  206. }
  207. #endif
  208. }
  209. }
  210. }
  211. if (daybefore >= 0 && daybefore < 7 && minimum_restore_time == -(60 * 24) && saved_action == -1) {
  212. _schCheck(relay, ++daybefore);
  213. return;
  214. }
  215. if (minimum_restore_time != -(60 * 24) && saved_action != -1 && saved_sch != -1) {
  216. _schAction(saved_sch, saved_action, relay);
  217. }
  218. }
  219. // -----------------------------------------------------------------------------
  220. void schSetup() {
  221. _schConfigure();
  222. #if WEB_SUPPORT
  223. wsRegister()
  224. .onVisible(_schWebSocketOnVisible)
  225. .onConnected(_schWebSocketOnConnected)
  226. .onKeyCheck(_schWebSocketOnKeyCheck);
  227. #endif
  228. NtpBroker::Register([](const NtpTick tick, time_t, const String&) {
  229. if (NtpTick::EveryMinute != tick) return;
  230. static bool restore_once = true;
  231. if (restore_once) {
  232. for (unsigned char i = 0; i < relayCount(); i++) {
  233. if (getSetting({"relayLastSch", i}, 1 == SCHEDULER_RESTORE_LAST_SCHEDULE)) {
  234. _schCheck(i, 0);
  235. }
  236. }
  237. restore_once = false;
  238. }
  239. _schCheck(-1, -1);
  240. });
  241. espurnaRegisterReload(_schConfigure);
  242. }
  243. #endif // SCHEDULER_SUPPORT