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.

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