22
22
import struct
23
23
import time
24
24
25
+ from micropython import const
26
+
27
+
25
28
__version__ = "0.0.0+auto.0"
26
29
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_NTP.git"
27
30
28
31
NTP_TO_UNIX_EPOCH = 2208988800 # 1970-01-01 00:00:00
32
+ PACKET_SIZE = const (48 )
29
33
30
34
31
35
class NTP :
@@ -55,7 +59,8 @@ def __init__(
55
59
self ._pool = socketpool
56
60
self ._server = server
57
61
self ._port = port
58
- self ._packet = bytearray (48 )
62
+ self ._socket_address = None
63
+ self ._packet = bytearray (PACKET_SIZE )
59
64
self ._tz_offset = int (tz_offset * 60 * 60 )
60
65
self ._socket_timeout = socket_timeout
61
66
@@ -71,21 +76,27 @@ def datetime(self) -> time.struct_time:
71
76
unless there has already been a recent request. Raises OSError exception if no response
72
77
is received within socket_timeout seconds"""
73
78
if time .monotonic_ns () > self .next_sync :
79
+ if self ._socket_address is None :
80
+ self ._socket_address = self ._pool .getaddrinfo (self ._server , self ._port )[
81
+ 0
82
+ ][4 ]
83
+
74
84
self ._packet [0 ] = 0b00100011 # Not leap second, NTP version 4, Client mode
75
- for i in range (1 , len ( self . _packet ) ):
85
+ for i in range (1 , PACKET_SIZE ):
76
86
self ._packet [i ] = 0
77
87
with self ._pool .socket (self ._pool .AF_INET , self ._pool .SOCK_DGRAM ) as sock :
88
+ # Since the ESP32SPI doesn't support sendto, we are using
89
+ # connect + send to standardize code
78
90
sock .settimeout (self ._socket_timeout )
79
- sock .sendto (self ._packet , (self ._server , self ._port ))
80
- sock .recvfrom_into (self ._packet )
91
+ sock .connect (self ._socket_address )
92
+ sock .send (self ._packet )
93
+ sock .recv_into (self ._packet )
81
94
# Get the time in the context to minimize the difference between it and receiving
82
95
# the packet.
83
96
destination = time .monotonic_ns ()
84
97
poll = struct .unpack_from ("!B" , self ._packet , offset = 2 )[0 ]
85
98
self .next_sync = destination + (2 ** poll ) * 1_000_000_000
86
- seconds = struct .unpack_from (
87
- "!I" , self ._packet , offset = len (self ._packet ) - 8
88
- )[0 ]
99
+ seconds = struct .unpack_from ("!I" , self ._packet , offset = PACKET_SIZE - 8 )[0 ]
89
100
self ._monotonic_start = (
90
101
seconds
91
102
+ self ._tz_offset
0 commit comments