Skip to content

Fixed hanging by adding socket_timeout parameter with a default timeout of 10s #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions adafruit_ntp.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def __init__(
server: str = "0.adafruit.pool.ntp.org",
port: int = 123,
tz_offset: int = 0,
socket_timeout: int = 10,
) -> None:
"""
:param object socketpool: A socket provider such as CPython's `socket` module.
Expand All @@ -49,12 +50,14 @@ def __init__(
:param float tz_offset: Timezone offset in hours from UTC. Only useful for timezone ignorant
CircuitPython. CPython will determine timezone automatically and adjust (so don't use
this.) For example, Pacific daylight savings time is -7.
:param int socket_timeout: UDP socket timeout, in seconds.
"""
self._pool = socketpool
self._server = server
self._port = port
self._packet = bytearray(48)
self._tz_offset = tz_offset * 60 * 60
self._socket_timeout = socket_timeout

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