2016-05-03 09:45:12 -04:00
|
|
|
try:
|
|
|
|
import usocket as socket
|
|
|
|
except:
|
|
|
|
import socket
|
|
|
|
try:
|
|
|
|
import ustruct as struct
|
|
|
|
except:
|
|
|
|
import struct
|
|
|
|
|
|
|
|
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
|
|
|
|
NTP_DELTA = 3155673600
|
|
|
|
|
2020-01-31 07:54:11 -05:00
|
|
|
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
|
2016-05-30 12:16:05 -04:00
|
|
|
host = "pool.ntp.org"
|
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
|
2016-05-03 09:45:12 -04:00
|
|
|
def time():
|
|
|
|
NTP_QUERY = bytearray(48)
|
2020-02-26 23:36:53 -05:00
|
|
|
NTP_QUERY[0] = 0x1B
|
2016-05-30 12:16:05 -04:00
|
|
|
addr = socket.getaddrinfo(host, 123)[0][-1]
|
2016-05-03 09:45:12 -04:00
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
2019-10-10 03:05:56 -04:00
|
|
|
try:
|
|
|
|
s.settimeout(1)
|
|
|
|
res = s.sendto(NTP_QUERY, addr)
|
|
|
|
msg = s.recv(48)
|
|
|
|
finally:
|
|
|
|
s.close()
|
2016-05-03 09:45:12 -04:00
|
|
|
val = struct.unpack("!I", msg[40:44])[0]
|
|
|
|
return val - NTP_DELTA
|
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
|
2020-09-13 10:07:12 -04:00
|
|
|
# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
|
2016-05-03 09:45:12 -04:00
|
|
|
def settime():
|
|
|
|
t = time()
|
|
|
|
import machine
|
|
|
|
import utime
|
2020-02-26 23:36:53 -05:00
|
|
|
|
2020-09-13 10:07:12 -04:00
|
|
|
tm = utime.gmtime(t)
|
2019-10-10 03:05:56 -04:00
|
|
|
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
|