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.

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