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.

86 lines
2.3 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
8 years ago
  1. /*
  2. NTP MODULE
  3. Copyright (C) 2016-2017 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. WiFiEventHandler _ntp_wifi_onSTA;
  11. Ticker _ntp_delay;
  12. // -----------------------------------------------------------------------------
  13. // NTP
  14. // -----------------------------------------------------------------------------
  15. void _ntpDebug() {
  16. DEBUG_MSG_P(PSTR("[NTP] Time: %s\n"), (char *) ntpDateTime().c_str());
  17. }
  18. void ntpConfigure() {
  19. NTP.begin(
  20. getSetting("ntpServer1", NTP_SERVER),
  21. getSetting("ntpOffset", NTP_TIME_OFFSET).toInt(),
  22. getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1
  23. );
  24. if (getSetting("ntpServer2")) NTP.setNtpServerName(getSetting("ntpServer2"), 1);
  25. if (getSetting("ntpServer3")) NTP.setNtpServerName(getSetting("ntpServer3"), 2);
  26. NTP.setInterval(NTP_UPDATE_INTERVAL);
  27. }
  28. bool ntpConnected() {
  29. return (timeStatus() == timeSet);
  30. }
  31. String ntpDateTime() {
  32. if (!ntpConnected()) return String("Not set");
  33. String value = NTP.getTimeDateString();
  34. int hour = value.substring(0, 2).toInt();
  35. int minute = value.substring(3, 5).toInt();
  36. int second = value.substring(6, 8).toInt();
  37. int day = value.substring(9, 11).toInt();
  38. int month = value.substring(12, 14).toInt();
  39. int year = value.substring(15, 19).toInt();
  40. char buffer[20];
  41. snprintf_P(buffer, sizeof(buffer), PSTR("%04d/%02d/%02d %02d:%02d:%02d"), year, month, day, hour, minute, second);
  42. return String(buffer);
  43. }
  44. void ntpSetup() {
  45. NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
  46. if (error) {
  47. #if WEB_SUPPORT
  48. wsSend_P(PSTR("{\"ntpStatus\": false}"));
  49. #endif
  50. if (error == noResponse) {
  51. DEBUG_MSG_P(PSTR("[NTP] Error: NTP server not reachable\n"));
  52. } else if (error == invalidAddress) {
  53. DEBUG_MSG_P(PSTR("[NTP] Error: Invalid NTP server address\n"));
  54. }
  55. } else {
  56. #if WEB_SUPPORT
  57. wsSend_P(PSTR("{\"ntpStatus\": true}"));
  58. #endif
  59. _ntp_delay.once_ms(100, _ntpDebug);
  60. }
  61. });
  62. _ntp_wifi_onSTA = WiFi.onStationModeGotIP([](WiFiEventStationModeGotIP ipInfo) {
  63. ntpConfigure();
  64. });
  65. }
  66. void ntpLoop() {
  67. now();
  68. }
  69. #endif // NTP_SUPPORT