@@ -22,12 +22,37 @@ def time():
2222 s = socket .socket (socket .AF_INET , socket .SOCK_DGRAM )
2323 try :
2424 s .settimeout (timeout )
25- res = s .sendto (NTP_QUERY , addr )
25+ s .sendto (NTP_QUERY , addr )
2626 msg = s .recv (48 )
2727 finally :
2828 s .close ()
2929 val = struct .unpack ("!I" , msg [40 :44 ])[0 ]
3030
31+ # 2024-01-01 00:00:00 converted to an NTP timestamp
32+ MIN_NTP_TIMESTAMP = 3913056000
33+
34+ # Y2036 fix
35+ #
36+ # The NTP timestamp has a 32-bit count of seconds, which will wrap back
37+ # to zero on 7 Feb 2036 at 06:28:16.
38+ #
39+ # We know that this software was written during 2024 (or later).
40+ # So we know that timestamps less than MIN_NTP_TIMESTAMP are impossible.
41+ # So if the timestamp is less than MIN_NTP_TIMESTAMP, that probably means
42+ # that the NTP time wrapped at 2^32 seconds. (Or someone set the wrong
43+ # time on their NTP server, but we can't really do anything about that).
44+ #
45+ # So in that case, we need to add in those extra 2^32 seconds, to get the
46+ # correct timestamp.
47+ #
48+ # This means that this code will work until the year 2160. More precisely,
49+ # this code will not work after 7th Feb 2160 at 06:28:15.
50+ #
51+ if val < MIN_NTP_TIMESTAMP :
52+ val += 0x100000000
53+
54+ # Convert timestamp from NTP format to our internal format
55+
3156 EPOCH_YEAR = utime .gmtime (0 )[0 ]
3257 if EPOCH_YEAR == 2000 :
3358 # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
0 commit comments