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.

194 lines
4.9 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-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if NTP_SUPPORT
  6. #include <TimeLib.h>
  7. #include <NtpClientLib.h>
  8. #include <WiFiClient.h>
  9. #include <Ticker.h>
  10. unsigned long _ntp_start = 0;
  11. bool _ntp_update = false;
  12. bool _ntp_configure = false;
  13. // -----------------------------------------------------------------------------
  14. // NTP
  15. // -----------------------------------------------------------------------------
  16. #if WEB_SUPPORT
  17. bool _ntpWebSocketOnReceive(const char * key, JsonVariant& value) {
  18. return (strncmp(key, "ntp", 3) == 0);
  19. }
  20. void _ntpWebSocketOnSend(JsonObject& root) {
  21. root["ntpVisible"] = 1;
  22. root["ntpStatus"] = (timeStatus() == timeSet);
  23. root["ntpServer"] = getSetting("ntpServer", NTP_SERVER);
  24. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  25. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  26. root["ntpRegion"] = getSetting("ntpRegion", NTP_DST_REGION).toInt();
  27. if (ntpSynced()) root["now"] = now();
  28. }
  29. #endif
  30. void _ntpStart() {
  31. _ntp_start = 0;
  32. NTP.begin(getSetting("ntpServer", NTP_SERVER));
  33. NTP.setInterval(NTP_SYNC_INTERVAL, NTP_UPDATE_INTERVAL);
  34. NTP.setNTPTimeout(NTP_TIMEOUT);
  35. _ntpConfigure();
  36. }
  37. void _ntpConfigure() {
  38. _ntp_configure = false;
  39. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  40. int sign = offset > 0 ? 1 : -1;
  41. offset = abs(offset);
  42. int tz_hours = sign * (offset / 60);
  43. int tz_minutes = sign * (offset % 60);
  44. if (NTP.getTimeZone() != tz_hours || NTP.getTimeZoneMinutes() != tz_minutes) {
  45. NTP.setTimeZone(tz_hours, tz_minutes);
  46. _ntp_update = true;
  47. }
  48. bool daylight = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  49. if (NTP.getDayLight() != daylight) {
  50. NTP.setDayLight(daylight);
  51. _ntp_update = true;
  52. }
  53. String server = getSetting("ntpServer", NTP_SERVER);
  54. if (!NTP.getNtpServerName().equals(server)) {
  55. NTP.setNtpServerName(server);
  56. }
  57. uint8_t dst_region = getSetting("ntpRegion", NTP_DST_REGION).toInt();
  58. NTP.setDSTZone(dst_region);
  59. }
  60. void _ntpUpdate() {
  61. _ntp_update = false;
  62. #if WEB_SUPPORT
  63. wsSend(_ntpWebSocketOnSend);
  64. #endif
  65. if (ntpSynced()) {
  66. time_t t = now();
  67. DEBUG_MSG_P(PSTR("[NTP] UTC Time : %s\n"), (char *) ntpDateTime(ntpLocal2UTC(t)).c_str());
  68. DEBUG_MSG_P(PSTR("[NTP] Local Time: %s\n"), (char *) ntpDateTime(t).c_str());
  69. }
  70. }
  71. void _ntpLoop() {
  72. if (0 < _ntp_start && _ntp_start < millis()) _ntpStart();
  73. if (_ntp_configure) _ntpConfigure();
  74. if (_ntp_update) _ntpUpdate();
  75. now();
  76. #if BROKER_SUPPORT
  77. static unsigned char last_minute = 60;
  78. if (ntpSynced() && (minute() != last_minute)) {
  79. last_minute = minute();
  80. brokerPublish(MQTT_TOPIC_DATETIME, ntpDateTime().c_str());
  81. }
  82. #endif
  83. }
  84. void _ntpBackwards() {
  85. moveSetting("ntpServer1", "ntpServer");
  86. delSetting("ntpServer2");
  87. delSetting("ntpServer3");
  88. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  89. if (-30 < offset && offset < 30) {
  90. offset *= 60;
  91. setSetting("ntpOffset", offset);
  92. }
  93. }
  94. // -----------------------------------------------------------------------------
  95. bool ntpSynced() {
  96. #if NTP_WAIT_FOR_SYNC
  97. return (NTP.getLastNTPSync() > 0);
  98. #else
  99. return true;
  100. #endif
  101. }
  102. String ntpDateTime(time_t t) {
  103. char buffer[20];
  104. snprintf_P(buffer, sizeof(buffer),
  105. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  106. year(t), month(t), day(t), hour(t), minute(t), second(t)
  107. );
  108. return String(buffer);
  109. }
  110. String ntpDateTime() {
  111. if (ntpSynced()) return ntpDateTime(now());
  112. return String();
  113. }
  114. time_t ntpLocal2UTC(time_t local) {
  115. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  116. if (NTP.isSummerTime()) offset += 60;
  117. return local - offset * 60;
  118. }
  119. // -----------------------------------------------------------------------------
  120. void ntpSetup() {
  121. _ntpBackwards();
  122. NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
  123. if (error) {
  124. #if WEB_SUPPORT
  125. wsSend_P(PSTR("{\"ntpStatus\": false}"));
  126. #endif
  127. if (error == noResponse) {
  128. DEBUG_MSG_P(PSTR("[NTP] Error: NTP server not reachable\n"));
  129. } else if (error == invalidAddress) {
  130. DEBUG_MSG_P(PSTR("[NTP] Error: Invalid NTP server address\n"));
  131. }
  132. } else {
  133. _ntp_update = true;
  134. }
  135. });
  136. wifiRegister([](justwifi_messages_t code, char * parameter) {
  137. if (code == MESSAGE_CONNECTED) _ntp_start = millis() + NTP_START_DELAY;
  138. });
  139. #if WEB_SUPPORT
  140. wsOnSendRegister(_ntpWebSocketOnSend);
  141. wsOnReceiveRegister(_ntpWebSocketOnReceive);
  142. #endif
  143. // Main callbacks
  144. espurnaRegisterLoop(_ntpLoop);
  145. espurnaRegisterReload([]() { _ntp_configure = true; });
  146. }
  147. #endif // NTP_SUPPORT