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.

190 lines
4.8 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. return (year() > 2017);
  97. }
  98. String ntpDateTime(time_t t) {
  99. char buffer[20];
  100. snprintf_P(buffer, sizeof(buffer),
  101. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  102. year(t), month(t), day(t), hour(t), minute(t), second(t)
  103. );
  104. return String(buffer);
  105. }
  106. String ntpDateTime() {
  107. if (ntpSynced()) return ntpDateTime(now());
  108. return String();
  109. }
  110. time_t ntpLocal2UTC(time_t local) {
  111. int offset = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  112. if (NTP.isSummerTime()) offset += 60;
  113. return local - offset * 60;
  114. }
  115. // -----------------------------------------------------------------------------
  116. void ntpSetup() {
  117. _ntpBackwards();
  118. NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
  119. if (error) {
  120. #if WEB_SUPPORT
  121. wsSend_P(PSTR("{\"ntpStatus\": false}"));
  122. #endif
  123. if (error == noResponse) {
  124. DEBUG_MSG_P(PSTR("[NTP] Error: NTP server not reachable\n"));
  125. } else if (error == invalidAddress) {
  126. DEBUG_MSG_P(PSTR("[NTP] Error: Invalid NTP server address\n"));
  127. }
  128. } else {
  129. _ntp_update = true;
  130. }
  131. });
  132. wifiRegister([](justwifi_messages_t code, char * parameter) {
  133. if (code == MESSAGE_CONNECTED) _ntp_start = millis() + NTP_START_DELAY;
  134. });
  135. #if WEB_SUPPORT
  136. wsOnSendRegister(_ntpWebSocketOnSend);
  137. wsOnReceiveRegister(_ntpWebSocketOnReceive);
  138. #endif
  139. // Main callbacks
  140. espurnaRegisterLoop(_ntpLoop);
  141. espurnaRegisterReload([]() { _ntp_configure = true; });
  142. }
  143. #endif // NTP_SUPPORT