-
Notifications
You must be signed in to change notification settings - Fork 25
/
ntptime.py
45 lines (37 loc) · 1.2 KB
/
ntptime.py
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
try:
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
# This is the setting from the module published for the ESP8266:
# https://github.com/micropython/micropython/blob/master/ports/esp8266/modules/ntptime.py
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
#NTP_DELTA = 3155673600
# The Pico seems to be based off of 1 Jan 1970
# (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 2208988800
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org"
def time():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(1)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
finally:
s.close()
val = struct.unpack("!I", msg[40:44])[0]
return val - NTP_DELTA
# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
def settime():
t = time()
import machine
import utime
tm = utime.gmtime(t)
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))