Skip to content

NTP fix infinite loop #82

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 4 commits into from
Jan 14, 2023
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
26 changes: 16 additions & 10 deletions adafruit_wiznet5k/adafruit_wiznet5k_ntp.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,19 @@ def get_time(self) -> time.struct_time:
:return time.struct_time: The local time.
"""
self._sock.bind((None, 50001))
self._sock.sendto(self._pkt_buf_, (self._ntp_server, 123))
while True:
data = self._sock.recv()
if data:
sec = data[40:44]
int_cal = int.from_bytes(sec, "big")
# UTC offset may be a float as some offsets are half hours so force int.
cal = int(int_cal - 2208988800 + self._utc * 3600)
cal = time.localtime(cal)
return cal
max_retries = 4
for retry in range(max_retries):
self._sock.sendto(self._pkt_buf_, (self._ntp_server, 123))
end_time = time.monotonic() + 0.2 * 2**retry
while time.monotonic() < end_time:
data = self._sock.recv()
if data:
sec = data[40:44]
int_cal = int.from_bytes(sec, "big")
# UTC offset may be a float as some offsets are half hours so force int.
cal = int(int_cal - 2208988800 + self._utc * 3600)
cal = time.localtime(cal)
return cal
raise TimeoutError(
"No reply from NTP server after {} attempts.".format(max_retries)
)