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