27
27
import usocket as socket
28
28
import ustruct as struct
29
29
import ulogging as logging
30
+ import uselect as select
30
31
except ImportError :
31
32
import socket
32
33
import struct
33
34
import logging
35
+ import select
34
36
from arduino_iot_cloud .ussl import wrap_socket
35
37
36
38
@@ -90,7 +92,7 @@ def set_last_will(self, topic, msg, retain=False, qos=0):
90
92
self .lw_qos = qos
91
93
self .lw_retain = retain
92
94
93
- def connect (self , clean_session = True ):
95
+ def connect (self , clean_session = True , timeout = 5.0 ):
94
96
addr = socket .getaddrinfo (self .server , self .port )[0 ][- 1 ]
95
97
96
98
if self .sock is not None :
@@ -99,11 +101,13 @@ def connect(self, clean_session=True):
99
101
100
102
try :
101
103
self .sock = socket .socket ()
104
+ self .sock .settimeout (timeout )
102
105
self .sock = wrap_socket (self .sock , ** self .ssl_params )
103
106
self .sock .connect (addr )
104
107
except Exception :
105
108
self .sock .close ()
106
109
self .sock = socket .socket ()
110
+ self .sock .settimeout (timeout )
107
111
self .sock .connect (addr )
108
112
self .sock = wrap_socket (self .sock , ** self .ssl_params )
109
113
@@ -214,9 +218,8 @@ def subscribe(self, topic, qos=0):
214
218
# messages processed internally.
215
219
def wait_msg (self ):
216
220
res = self .sock .read (1 )
217
- if res == b"" or res is None :
221
+ if res is None or res == b"" :
218
222
return None
219
- self .sock .setblocking (True )
220
223
if res == b"\xd0 " : # PINGRESP
221
224
sz = self .sock .read (1 )[0 ]
222
225
assert sz == 0
@@ -246,5 +249,6 @@ def wait_msg(self):
246
249
# If not, returns immediately with None. Otherwise, does
247
250
# the same processing as wait_msg.
248
251
def check_msg (self ):
249
- self .sock .setblocking (False )
250
- return self .wait_msg ()
252
+ r , w , e = select .select ([self .sock ], [], [], 0.05 )
253
+ if (len (r )):
254
+ return self .wait_msg ()
0 commit comments