2222import struct
2323import time
2424
25+ from micropython import const
26+
27+
2528__version__ = "0.0.0+auto.0"
2629__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_NTP.git"
2730
2831NTP_TO_UNIX_EPOCH = 2208988800 # 1970-01-01 00:00:00
32+ PACKET_SIZE = const (48 )
2933
3034
3135class NTP :
@@ -55,7 +59,8 @@ def __init__(
5559 self ._pool = socketpool
5660 self ._server = server
5761 self ._port = port
58- self ._packet = bytearray (48 )
62+ self ._socket_address = None
63+ self ._packet = bytearray (PACKET_SIZE )
5964 self ._tz_offset = int (tz_offset * 60 * 60 )
6065 self ._socket_timeout = socket_timeout
6166
@@ -71,21 +76,27 @@ def datetime(self) -> time.struct_time:
7176 unless there has already been a recent request. Raises OSError exception if no response
7277 is received within socket_timeout seconds"""
7378 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+
7484 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 ):
7686 self ._packet [i ] = 0
7787 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
7890 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 )
8194 # Get the time in the context to minimize the difference between it and receiving
8295 # the packet.
8396 destination = time .monotonic_ns ()
8497 poll = struct .unpack_from ("!B" , self ._packet , offset = 2 )[0 ]
8598 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 ]
89100 self ._monotonic_start = (
90101 seconds
91102 + self ._tz_offset
0 commit comments