Skip to content

Commit e7bd821

Browse files
author
BiffoBear
committed
Added retries and a TimeoutError to NTP.get_time. This avoids an infinite loop if the NTP server reply not received.
1 parent bdd23c7 commit e7bd821

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

adafruit_wiznet5k/adafruit_wiznet5k_ntp.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,19 @@ def get_time(self) -> time.struct_time:
6969
:return time.struct_time: The local time.
7070
"""
7171
self._sock.bind((None, 50001))
72-
self._sock.sendto(self._pkt_buf_, (self._ntp_server, 123))
73-
while True:
74-
data = self._sock.recv()
75-
if data:
76-
sec = data[40:44]
77-
int_cal = int.from_bytes(sec, "big")
78-
# UTC offset may be a float as some offsets are half hours so force int.
79-
cal = int(int_cal - 2208988800 + self._utc * 3600)
80-
cal = time.localtime(cal)
81-
return cal
72+
max_retries = 3
73+
for _ in range(max_retries):
74+
self._sock.sendto(self._pkt_buf_, (self._ntp_server, 123))
75+
end_time = time.monotonic() + 1
76+
while time.monotonic() < end_time:
77+
data = self._sock.recv()
78+
if data:
79+
sec = data[40:44]
80+
int_cal = int.from_bytes(sec, "big")
81+
# UTC offset may be a float as some offsets are half hours so force int.
82+
cal = int(int_cal - 2208988800 + self._utc * 3600)
83+
cal = time.localtime(cal)
84+
return cal
85+
raise TimeoutError(
86+
"No reply from NTP server after {} attempts.".format(max_retries)
87+
)

0 commit comments

Comments
 (0)