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.

272 lines
7.3 KiB

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