Skip to content

Commit f873a50

Browse files
committed
esp8266/scripts/ntptime: Add simple NTP client.
.time() returns seconds since MicroPython epoch (2000-01-01 00:00UTC), .settime() sends current system time, assuming UTC timezone.
1 parent 5d05993 commit f873a50

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

esp8266/scripts/ntptime.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
try:
2+
import usocket as socket
3+
except:
4+
import socket
5+
try:
6+
import ustruct as struct
7+
except:
8+
import struct
9+
10+
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
11+
NTP_DELTA = 3155673600
12+
13+
def time():
14+
NTP_QUERY = bytearray(48)
15+
NTP_QUERY[0] = 0x1b
16+
addr = socket.getaddrinfo('pool.ntp.org', 123)[0][-1]
17+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
18+
s.settimeout(1)
19+
res = s.sendto(NTP_QUERY, addr)
20+
msg = s.recv(48)
21+
s.close()
22+
val = struct.unpack("!I", msg[40:44])[0]
23+
return val - NTP_DELTA
24+
25+
# There's currently no timezone support in MicroPython, so
26+
# utime.localtime() will return UTC time (as if it was .gmtime())
27+
def settime():
28+
t = time()
29+
import machine
30+
import utime
31+
tm = utime.localtime(t)
32+
tm = tm[0:3] + (0,) + tm[3:6] + (0,)
33+
machine.RTC().datetime(tm)
34+
print(utime.localtime())

0 commit comments

Comments
 (0)