AllWize Library
ntp.cpp
Go to the documentation of this file.
1 /*
2 
3 NTP MODULE
4 
5 */
6 
7 #include "ntp.h"
8 #include "debug.h"
9 #include "configuration.h"
10 #include "forwarder.h"
11 
12 #include <TimeLib.h>
13 #include <NtpClientLib.h>
14 #include <ESP8266WiFi.h>
15 
16 // -----------------------------------------------------------------------------
17 // Configuration
18 // -----------------------------------------------------------------------------
19 
20 bool ntpSynced() {
21  return (NTP.getLastNTPSync() > 0);
22 }
23 
24 String ntpDateTime(time_t t) {
25  char buffer[30];
26  snprintf_P(buffer, sizeof(buffer),
27  PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
28  year(t), month(t), day(t), hour(t), minute(t), second(t)
29  );
30  return String(buffer);
31 }
32 
33 String ntpDateTime() {
34  if (ntpSynced()) return ntpDateTime(now());
35  return String();
36 }
37 
38 void ntpConnect() {
39  NTP.begin(NTP_SERVER);
40  NTP.setInterval(NTP_SYNC_INTERVAL, NTP_UPDATE_INTERVAL);
41 }
42 
43 void ntpSetup() {
44 
45  NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
46  if (error) {
47  if (error == noResponse) {
48  DEBUG_MSG("[NTP] Warning: NTP server not reachable\n");
49  } else if (error == invalidAddress) {
50  DEBUG_MSG("[NTP] Error: Invalid NTP server address\n");
51  }
52  } else {
53  DEBUG_MSG("[NTP] Current time: %s\n", NTP.getTimeDateString(NTP.getFirstSync()).c_str());
54  forwarderPing();
55  }
56  });
57 
58 }
59 
60 void ntpLoop() {
61  now();
62 }
void ntpLoop()
Definition: ntp.cpp:60
bool ntpSynced()
Definition: ntp.cpp:20
#define DEBUG_MSG(...)
Definition: debug.h:12
void ntpConnect()
Definition: ntp.cpp:38
#define NTP_UPDATE_INTERVAL
Definition: configuration.h:57
void ntpSetup()
Definition: ntp.cpp:43
String ntpDateTime(time_t t)
Definition: ntp.cpp:24
#define NTP_SYNC_INTERVAL
Definition: configuration.h:56
void forwarderPing()
Definition: forwarder.cpp:55
#define NTP_SERVER
Definition: configuration.h:55