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.

278 lines
7.3 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
  1. /*
  2. NTP MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if NTP_SUPPORT
  6. #include <TimeLib.h>
  7. #include <WiFiClient.h>
  8. #include <Ticker.h>
  9. #include "libs/NtpClientWrap.h"
  10. Ticker _ntp_defer;
  11. bool _ntp_report = false;
  12. bool _ntp_configure = false;
  13. bool _ntp_want_sync = false;
  14. // -----------------------------------------------------------------------------
  15. // NTP
  16. // -----------------------------------------------------------------------------
  17. #if WEB_SUPPORT
  18. bool _ntpWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  19. return (strncmp(key, "ntp", 3) == 0);
  20. }
  21. void _ntpWebSocketOnVisible(JsonObject& root) {
  22. root["ntpVisible"] = 1;
  23. }
  24. void _ntpWebSocketOnData(JsonObject& root) {
  25. root["ntpStatus"] = (timeStatus() == timeSet);
  26. }
  27. void _ntpWebSocketOnConnected(JsonObject& root) {
  28. root["ntpServer"] = getSetting("ntpServer", NTP_SERVER);
  29. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  30. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  31. root["ntpRegion"] = getSetting("ntpRegion", NTP_DST_REGION).toInt();
  32. }
  33. #endif
  34. time_t _ntpSyncProvider() {
  35. _ntp_want_sync = true;
  36. return 0;
  37. }
  38. void _ntpWantSync() {
  39. _ntp_want_sync = true;
  40. }
  41. // Randomized in time to avoid clogging the server with simultaious requests from multiple devices
  42. // (for example, when multiple devices start up at the same time)
  43. int inline _ntpSyncInterval() {
  44. return secureRandom(NTP_SYNC_INTERVAL, NTP_SYNC_INTERVAL * 2);
  45. }
  46. int inline _ntpUpdateInterval() {
  47. return secureRandom(NTP_UPDATE_INTERVAL, NTP_UPDATE_INTERVAL * 2);
  48. }
  49. void _ntpStart() {
  50. _ntpConfigure();
  51. // short (initial) and long (after sync) intervals
  52. NTPw.setInterval(_ntpSyncInterval(), _ntpUpdateInterval());
  53. DEBUG_MSG_P(PSTR("[NTP] Update intervals: %us / %us\n"),
  54. NTPw.getShortInterval(), NTPw.getLongInterval());
  55. // setSyncProvider will immediatly call given function by setting next sync time to the current time.
  56. // Avoid triggering sync immediatly by canceling sync provider flag and resetting sync interval again
  57. setSyncProvider(_ntpSyncProvider);
  58. _ntp_want_sync = false;
  59. setSyncInterval(NTPw.getShortInterval());
  60. }
  61. void _ntpConfigure() {
  62. _ntp_configure = false;
  63. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  64. int sign = offset > 0 ? 1 : -1;
  65. offset = abs(offset);
  66. int tz_hours = sign * (offset / 60);
  67. int tz_minutes = sign * (offset % 60);
  68. if (NTPw.getTimeZone() != tz_hours || NTPw.getTimeZoneMinutes() != tz_minutes) {
  69. NTPw.setTimeZone(tz_hours, tz_minutes);
  70. _ntp_report = true;
  71. }
  72. bool daylight = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  73. if (NTPw.getDayLight() != daylight) {
  74. NTPw.setDayLight(daylight);
  75. _ntp_report = true;
  76. }
  77. String server = getSetting("ntpServer", NTP_SERVER);
  78. if (!NTPw.getNtpServerName().equals(server)) {
  79. NTPw.setNtpServerName(server);
  80. }
  81. uint8_t dst_region = getSetting("ntpRegion", NTP_DST_REGION).toInt();
  82. NTPw.setDSTZone(dst_region);
  83. // Some remote servers can be slow to respond, increase accordingly
  84. // TODO does this need upper constrain?
  85. NTPw.setNTPTimeout(getSetting("ntpTimeout", NTP_TIMEOUT).toInt());
  86. }
  87. void _ntpReport() {
  88. _ntp_report = false;
  89. #if DEBUG_SUPPORT
  90. if (ntpSynced()) {
  91. time_t t = now();
  92. DEBUG_MSG_P(PSTR("[NTP] UTC Time : %s\n"), ntpDateTime(ntpLocal2UTC(t)).c_str());
  93. DEBUG_MSG_P(PSTR("[NTP] Local Time: %s\n"), ntpDateTime(t).c_str());
  94. }
  95. #endif
  96. }
  97. #if BROKER_SUPPORT
  98. void inline _ntpBroker() {
  99. static unsigned char last_minute = 60;
  100. if (ntpSynced() && (minute() != last_minute)) {
  101. last_minute = minute();
  102. brokerPublish(BROKER_MSG_TYPE_DATETIME, MQTT_TOPIC_DATETIME, ntpDateTime().c_str());
  103. }
  104. }
  105. #endif
  106. void _ntpLoop() {
  107. // Disable ntp sync when softAP is active. This will not crash, but instead spam debug-log with pointless sync failures.
  108. if (!wifiConnected()) return;
  109. if (_ntp_configure) _ntpConfigure();
  110. // NTPClientLib will trigger callback with sync status
  111. // see: NTPw.onNTPSyncEvent([](NTPSyncEvent_t error){ ... }) below
  112. if (_ntp_want_sync) {
  113. _ntp_want_sync = false;
  114. NTPw.getTime();
  115. }
  116. // Print current time whenever configuration changes or after successful sync
  117. if (_ntp_report) _ntpReport();
  118. #if BROKER_SUPPORT
  119. _ntpBroker();
  120. #endif
  121. }
  122. // TODO: remove me!
  123. void _ntpBackwards() {
  124. moveSetting("ntpServer1", "ntpServer");
  125. delSetting("ntpServer2");
  126. delSetting("ntpServer3");
  127. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  128. if (-30 < offset && offset < 30) {
  129. offset *= 60;
  130. setSetting("ntpOffset", offset);
  131. }
  132. }
  133. // -----------------------------------------------------------------------------
  134. bool ntpSynced() {
  135. #if NTP_WAIT_FOR_SYNC
  136. // Has synced at least once
  137. return (NTPw.getFirstSync() > 0);
  138. #else
  139. // TODO: runtime setting?
  140. return true;
  141. #endif
  142. }
  143. String ntpDateTime(time_t t) {
  144. char buffer[20];
  145. snprintf_P(buffer, sizeof(buffer),
  146. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  147. year(t), month(t), day(t), hour(t), minute(t), second(t)
  148. );
  149. return String(buffer);
  150. }
  151. String ntpDateTime() {
  152. if (ntpSynced()) return ntpDateTime(now());
  153. return String();
  154. }
  155. // XXX: returns garbage during DST switch
  156. time_t ntpLocal2UTC(time_t local) {
  157. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  158. if (NTPw.isSummerTime()) offset += 60;
  159. return local - offset * 60;
  160. }
  161. // -----------------------------------------------------------------------------
  162. void ntpSetup() {
  163. _ntpBackwards();
  164. #if TERMINAL_SUPPORT
  165. terminalRegisterCommand(F("NTP"), [](Embedis* e) {
  166. if (ntpSynced()) {
  167. _ntpReport();
  168. terminalOK();
  169. } else {
  170. DEBUG_MSG_P(PSTR("[NTP] Not synced\n"));
  171. }
  172. });
  173. terminalRegisterCommand(F("NTP.SYNC"), [](Embedis* e) {
  174. _ntpWantSync();
  175. terminalOK();
  176. });
  177. #endif
  178. NTPw.onNTPSyncEvent([](NTPSyncEvent_t error) {
  179. if (error) {
  180. if (error == noResponse) {
  181. DEBUG_MSG_P(PSTR("[NTP] Error: NTP server not reachable\n"));
  182. } else if (error == invalidAddress) {
  183. DEBUG_MSG_P(PSTR("[NTP] Error: Invalid NTP server address\n"));
  184. }
  185. #if WEB_SUPPORT
  186. wsPost(_ntpWebSocketOnData);
  187. #endif
  188. } else {
  189. _ntp_report = true;
  190. setTime(NTPw.getLastNTPSync());
  191. }
  192. });
  193. wifiRegister([](justwifi_messages_t code, char * parameter) {
  194. if (code == MESSAGE_CONNECTED) {
  195. if (!ntpSynced()) {
  196. _ntp_defer.once_ms(secureRandom(NTP_START_DELAY, NTP_START_DELAY * 15), _ntpWantSync);
  197. }
  198. }
  199. });
  200. #if WEB_SUPPORT
  201. wsRegister()
  202. .onVisible(_ntpWebSocketOnVisible)
  203. .onConnected(_ntpWebSocketOnConnected)
  204. .onData(_ntpWebSocketOnData)
  205. .onKeyCheck(_ntpWebSocketOnKeyCheck);
  206. #endif
  207. // Main callbacks
  208. espurnaRegisterLoop(_ntpLoop);
  209. espurnaRegisterReload([]() { _ntp_configure = true; });
  210. // Sets up NTP instance, installs ours sync provider
  211. _ntpStart();
  212. }
  213. #endif // NTP_SUPPORT