Skip to content

Commit 888cdca

Browse files
authored
Merge pull request #22 from regulatre/main
Fixed hanging by adding socket_timeout parameter with a default timeout of 10s
2 parents d443241 + 9acf52c commit 888cdca

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

adafruit_ntp.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ def __init__(
4141
server: str = "0.adafruit.pool.ntp.org",
4242
port: int = 123,
4343
tz_offset: int = 0,
44+
socket_timeout: int = 10,
4445
) -> None:
4546
"""
4647
:param object socketpool: A socket provider such as CPython's `socket` module.
@@ -49,12 +50,14 @@ def __init__(
4950
:param float tz_offset: Timezone offset in hours from UTC. Only useful for timezone ignorant
5051
CircuitPython. CPython will determine timezone automatically and adjust (so don't use
5152
this.) For example, Pacific daylight savings time is -7.
53+
:param int socket_timeout: UDP socket timeout, in seconds.
5254
"""
5355
self._pool = socketpool
5456
self._server = server
5557
self._port = port
5658
self._packet = bytearray(48)
5759
self._tz_offset = tz_offset * 60 * 60
60+
self._socket_timeout = socket_timeout
5861

5962
# This is our estimated start time for the monotonic clock. We adjust it based on the ntp
6063
# responses.
@@ -70,6 +73,7 @@ def datetime(self) -> time.struct_time:
7073
for i in range(1, len(self._packet)):
7174
self._packet[i] = 0
7275
with self._pool.socket(self._pool.AF_INET, self._pool.SOCK_DGRAM) as sock:
76+
sock.settimeout(self._socket_timeout)
7377
sock.sendto(self._packet, (self._server, self._port))
7478
sock.recvfrom_into(self._packet)
7579
# Get the time in the context to minimize the difference between it and receiving

0 commit comments

Comments
 (0)