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.

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