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.

279 lines
7.4 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. brokerPublish(BROKER_MSG_TYPE_DATETIME, MQTT_TOPIC_TIMESTAMP, String(now()).c_str());
  104. }
  105. }
  106. #endif
  107. void _ntpLoop() {
  108. // Disable ntp sync when softAP is active. This will not crash, but instead spam debug-log with pointless sync failures.
  109. if (!wifiConnected()) return;
  110. if (_ntp_configure) _ntpConfigure();
  111. // NTPClientLib will trigger callback with sync status
  112. // see: NTPw.onNTPSyncEvent([](NTPSyncEvent_t error){ ... }) below
  113. if (_ntp_want_sync) {
  114. _ntp_want_sync = false;
  115. NTPw.getTime();
  116. }
  117. // Print current time whenever configuration changes or after successful sync
  118. if (_ntp_report) _ntpReport();
  119. #if BROKER_SUPPORT
  120. _ntpBroker();
  121. #endif
  122. }
  123. // TODO: remove me!
  124. void _ntpBackwards() {
  125. moveSetting("ntpServer1", "ntpServer");
  126. delSetting("ntpServer2");
  127. delSetting("ntpServer3");
  128. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  129. if (-30 < offset && offset < 30) {
  130. offset *= 60;
  131. setSetting("ntpOffset", offset);
  132. }
  133. }
  134. // -----------------------------------------------------------------------------
  135. bool ntpSynced() {
  136. #if NTP_WAIT_FOR_SYNC
  137. // Has synced at least once
  138. return (NTPw.getFirstSync() > 0);
  139. #else
  140. // TODO: runtime setting?
  141. return true;
  142. #endif
  143. }
  144. String ntpDateTime(time_t t) {
  145. char buffer[20];
  146. snprintf_P(buffer, sizeof(buffer),
  147. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  148. year(t), month(t), day(t), hour(t), minute(t), second(t)
  149. );
  150. return String(buffer);
  151. }
  152. String ntpDateTime() {
  153. if (ntpSynced()) return ntpDateTime(now());
  154. return String();
  155. }
  156. // XXX: returns garbage during DST switch
  157. time_t ntpLocal2UTC(time_t local) {
  158. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  159. if (NTPw.isSummerTime()) offset += 60;
  160. return local - offset * 60;
  161. }
  162. // -----------------------------------------------------------------------------
  163. void ntpSetup() {
  164. _ntpBackwards();
  165. #if TERMINAL_SUPPORT
  166. terminalRegisterCommand(F("NTP"), [](Embedis* e) {
  167. if (ntpSynced()) {
  168. _ntpReport();
  169. terminalOK();
  170. } else {
  171. DEBUG_MSG_P(PSTR("[NTP] Not synced\n"));
  172. }
  173. });
  174. terminalRegisterCommand(F("NTP.SYNC"), [](Embedis* e) {
  175. _ntpWantSync();
  176. terminalOK();
  177. });
  178. #endif
  179. NTPw.onNTPSyncEvent([](NTPSyncEvent_t error) {
  180. if (error) {
  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. #if WEB_SUPPORT
  187. wsPost(_ntpWebSocketOnData);
  188. #endif
  189. } else {
  190. _ntp_report = true;
  191. setTime(NTPw.getLastNTPSync());
  192. }
  193. });
  194. wifiRegister([](justwifi_messages_t code, char * parameter) {
  195. if (code == MESSAGE_CONNECTED) {
  196. if (!ntpSynced()) {
  197. _ntp_defer.once_ms(secureRandom(NTP_START_DELAY, NTP_START_DELAY * 15), _ntpWantSync);
  198. }
  199. }
  200. });
  201. #if WEB_SUPPORT
  202. wsRegister()
  203. .onVisible(_ntpWebSocketOnVisible)
  204. .onConnected(_ntpWebSocketOnConnected)
  205. .onData(_ntpWebSocketOnData)
  206. .onKeyCheck(_ntpWebSocketOnKeyCheck);
  207. #endif
  208. // Main callbacks
  209. espurnaRegisterLoop(_ntpLoop);
  210. espurnaRegisterReload([]() { _ntp_configure = true; });
  211. // Sets up NTP instance, installs ours sync provider
  212. _ntpStart();
  213. }
  214. #endif // NTP_SUPPORT