Skip to content

Commit c84fac4

Browse files
committed
Move the socket create+connect into _poll_server()
The previous code would never actually reconnect after any error. Also switch to using asyncio.wait_for().
1 parent 072966f commit c84fac4

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

ntpclient.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,19 @@ def __init__(self, host = 'pool.ntp.org', poll = MAX_POLL,
6363
asyncio.create_task(self._adj_task())
6464

6565
async def _poll_server(self):
66+
# We try to stay with the same server as long as possible. Only
67+
# lookup the address on startup or after errors.
68+
if self.sock is None:
69+
self.addr = socket.getaddrinfo(self.host, 123)[0][-1]
70+
if self.debug:
71+
print("ntpclient: new server address:", self.addr)
72+
73+
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
74+
self.sock.connect(self.addr)
75+
76+
self.rstr = asyncio.StreamReader(self.sock)
77+
self.wstr = asyncio.StreamWriter(self.sock)
78+
6679
# Send the NTP v3 request to the server
6780
wbuf = bytearray(48)
6881
wbuf[0] = 0b00011011
@@ -72,7 +85,10 @@ async def _poll_server(self):
7285
del wbuf
7386

7487
# Get the server reply
75-
rbuf = await self.rstr.read(48)
88+
try:
89+
rbuf = await asyncio.wait_for(self.rstr.read(48), 0.5)
90+
except asyncio.TimeoutError:
91+
raise Exception("Timeout receiving from server")
7692

7793
# Record the microseconds it took for this NTP round trip
7894
roundtrip_us = utime.ticks_diff(utime.ticks_us(), start_ticks)
@@ -105,20 +121,6 @@ async def _poll_server(self):
105121
return (delay, time_diff_us(tnow, t2), t2)
106122

107123
async def _poll_task(self):
108-
# We try to stay with the same server as long as possible. Only
109-
# lookup the address on startup or after errors.
110-
if self.sock is None:
111-
self.addr = socket.getaddrinfo(self.host, 123)[0][-1]
112-
if self.debug:
113-
print("ntpclient: new server address:", self.addr)
114-
115-
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
116-
self.sock.settimeout(0.2)
117-
self.sock.connect(self.addr)
118-
119-
self.rstr = asyncio.StreamReader(self.sock)
120-
self.wstr = asyncio.StreamWriter(self.sock)
121-
122124
# Try to get a first server reading
123125
while True:
124126
try:
@@ -128,7 +130,7 @@ async def _poll_task(self):
128130
self.sock.close()
129131
self.sock = None
130132
self.addr = None
131-
await asyncio.sleep(10)
133+
await asyncio.sleep(4)
132134
continue
133135
break
134136

0 commit comments

Comments
 (0)