Skip to content

Commit b97a342

Browse files
committed
rp2/modules: Add ntptime module
1 parent e306e2a commit b97a342

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

ports/rp2/modules/ntptime.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Modified from ports/esp8266/modules/ntptime.py (different system epoch)
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+
# (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
13+
NTP_DELTA = 2208988800
14+
15+
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
16+
host = "pool.ntp.org"
17+
18+
19+
def time():
20+
NTP_QUERY = bytearray(48)
21+
NTP_QUERY[0] = 0x1B
22+
addr = socket.getaddrinfo(host, 123)[0][-1]
23+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
24+
try:
25+
s.settimeout(1)
26+
res = s.sendto(NTP_QUERY, addr)
27+
msg = s.recv(48)
28+
finally:
29+
s.close()
30+
val = struct.unpack("!I", msg[40:44])[0]
31+
return val - NTP_DELTA
32+
33+
34+
# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
35+
def settime():
36+
t = time()
37+
import machine
38+
import utime
39+
40+
tm = utime.gmtime(t)
41+
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

0 commit comments

Comments
 (0)