@@ -63,6 +63,19 @@ def __init__(self, host = 'pool.ntp.org', poll = MAX_POLL,
63
63
asyncio .create_task (self ._adj_task ())
64
64
65
65
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
+
66
79
# Send the NTP v3 request to the server
67
80
wbuf = bytearray (48 )
68
81
wbuf [0 ] = 0b00011011
@@ -72,7 +85,10 @@ async def _poll_server(self):
72
85
del wbuf
73
86
74
87
# 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" )
76
92
77
93
# Record the microseconds it took for this NTP round trip
78
94
roundtrip_us = utime .ticks_diff (utime .ticks_us (), start_ticks )
@@ -105,20 +121,6 @@ async def _poll_server(self):
105
121
return (delay , time_diff_us (tnow , t2 ), t2 )
106
122
107
123
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
-
122
124
# Try to get a first server reading
123
125
while True :
124
126
try :
@@ -128,7 +130,7 @@ async def _poll_task(self):
128
130
self .sock .close ()
129
131
self .sock = None
130
132
self .addr = None
131
- await asyncio .sleep (10 )
133
+ await asyncio .sleep (4 )
132
134
continue
133
135
break
134
136
0 commit comments