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.

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