diff options
| author | Ian Davies <git@iandavies.org> | 2022-07-06 16:22:57 +0100 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2022-08-06 00:08:32 +1000 |
| commit | fbe9417b90474dd1a08749b3a79311a8007a98fb (patch) | |
| tree | d18a5804b85b0bceae2e53297702336c1d188c73 /extmod/ntptime.py | |
| parent | b560b9fe715e293caef80533d61d8c3b179b0339 (diff) | |
extmod/ntptime: Factor out ntptime module from esp8266 port.
The ntptime module was previously only included in the ESP8266 port. This
commit factors that module out into the extmod directory, makes it support
different epochs, and includes it in the rp2 port.
Diffstat (limited to 'extmod/ntptime.py')
| -rw-r--r-- | extmod/ntptime.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/extmod/ntptime.py b/extmod/ntptime.py new file mode 100644 index 000000000..05d7e9717 --- /dev/null +++ b/extmod/ntptime.py @@ -0,0 +1,48 @@ +import utime + +try: + import usocket as socket +except: + import socket +try: + import ustruct as struct +except: + import struct + +# 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] + + EPOCH_YEAR = utime.gmtime(0)[0] + if EPOCH_YEAR == 2000: + # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 + NTP_DELTA = 3155673600 + elif EPOCH_YEAR == 1970: + # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60 + NTP_DELTA = 2208988800 + else: + raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR)) + + 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 + + tm = utime.gmtime(t) + machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0)) |
