-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathntp.h
More file actions
69 lines (52 loc) · 1.8 KB
/
ntp.h
File metadata and controls
69 lines (52 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#pragma once
#include <Arduino.h>
#include <Udp.h>
#define NTP_DEFAULT_LOCAL_PORT 9876
#define NTP_PACKET_SIZE 48
#define NTP_TIMESTAMP_DIFFERENCE 2208988800UL // Difference between 1900-01-01 and 1970-01-01
#define NTP_DEFAULT_TIMEOUT_MS 1000 // Default timeout for update()
typedef struct
{
uint8_t day;
uint8_t month;
uint16_t year;
uint8_t hour;
uint8_t minute;
uint8_t second;
} ntp_datetime_t;
class NTP
{
public:
// Use an existing UDP instance (WiFiUDP, EthernetUDP, ...).
explicit NTP(UDP &udp);
NTP(UDP &udp, const char *address);
// Start listening on the given local port (default: 9876)
void begin(uint16_t port = NTP_DEFAULT_LOCAL_PORT);
// Stop using the UDP socket
void end();
// Change NTP server at runtime
void setServer(const char *address);
// Timezone offset in seconds (e.g. 3600 for UTC+1)
void setTimeOffset(int32_t timeOffsetSeconds);
// Query server and update internal time.
// Returns true on success, false on timeout / invalid packet.
bool update(uint16_t timeoutMs = NTP_DEFAULT_TIMEOUT_MS);
// Whether we ever successfully synced at least once
bool isValid() const;
// Seconds since 1970-01-01 00:00:00 UTC (advances using millis())
uint32_t getTimestamp() const;
// Seconds since 1970-01-01 00:00:00 with timeOffset applied (local time)
uint32_t getEpochTime() const;
// Local date/time based on getEpochTime()
ntp_datetime_t getDateTime() const;
private:
UDP &_sock;
const char *_address;
int32_t _timeOffset = 0; // seconds
uint32_t _timestamp = 0; // last synced UTC timestamp (s since 1970-01-01)
uint32_t _lastSyncMillis = 0; // millis() at last sync
bool _valid = false;
uint8_t _buffer[NTP_PACKET_SIZE];
// Internal: current UTC time based on last sync + millis()
uint32_t _nowUtc() const;
};