Skip to content

Commit

Permalink
Merge pull request #82 from BiffoBear/NTP_fix_infinite_loop
Browse files Browse the repository at this point in the history
NTP fix infinite loop
  • Loading branch information
FoamyGuy authored Jan 14, 2023
2 parents 73bb5b6 + d13efef commit abdec8a
Showing 1 changed file with 16 additions and 10 deletions.
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)
)

0 comments on commit abdec8a

Please sign in to comment.