Skip to content

Commit 58f8bec

Browse files
committed
micropython/net: Add "ntptime" client from main repo.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
1 parent cc2cdeb commit 58f8bec

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

micropython/net/ntptime/manifest.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module("ntptime.py", opt=3)

micropython/net/ntptime/ntptime.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import utime
2+
3+
try:
4+
import usocket as socket
5+
except:
6+
import socket
7+
try:
8+
import ustruct as struct
9+
except:
10+
import struct
11+
12+
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
13+
host = "pool.ntp.org"
14+
15+
16+
def time():
17+
NTP_QUERY = bytearray(48)
18+
NTP_QUERY[0] = 0x1B
19+
addr = socket.getaddrinfo(host, 123)[0][-1]
20+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
21+
try:
22+
s.settimeout(1)
23+
res = s.sendto(NTP_QUERY, addr)
24+
msg = s.recv(48)
25+
finally:
26+
s.close()
27+
val = struct.unpack("!I", msg[40:44])[0]
28+
29+
EPOCH_YEAR = utime.gmtime(0)[0]
30+
if EPOCH_YEAR == 2000:
31+
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
32+
NTP_DELTA = 3155673600
33+
elif EPOCH_YEAR == 1970:
34+
# (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
35+
NTP_DELTA = 2208988800
36+
else:
37+
raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
38+
39+
return val - NTP_DELTA
40+
41+
42+
# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
43+
def settime():
44+
t = time()
45+
import machine
46+
47+
tm = utime.gmtime(t)
48+
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

0 commit comments

Comments
 (0)