@@ -268,7 +268,9 @@ def _connect(self, retry: int, timeout: int | None = None) -> None:
268268
269269 if retry < 1 : # failsafe
270270 self ._stopHelper ()
271- return
271+ raise bluepy .btle .BTLEDisconnectError (
272+ "Failed to connect to peripheral %s" % self ._mac
273+ )
272274
273275 if self ._helper is None :
274276 self ._startHelper (self ._interface )
@@ -277,13 +279,20 @@ def _connect(self, retry: int, timeout: int | None = None) -> None:
277279
278280 rsp = self ._getResp (["stat" , "err" ], timeout )
279281
280- while rsp . get ( "state" ) and rsp ["state" ][0 ] in [
282+ while rsp and rsp ["state" ][0 ] in [
281283 "tryconn" ,
282284 "scan" ,
283- "disc" ,
284285 ]: # Wait for any operations to finish.
285286 rsp = self ._getResp (["stat" , "err" ], timeout )
286287
288+ # If operation in progress, disc is returned.
289+ # Bluepy helper can't handle state. Execute stop, wait and retry.
290+ if rsp and rsp ["state" ][0 ] == "disc" :
291+ _LOGGER .warning ("Bluepy busy, waiting before retry" )
292+ self ._stopHelper ()
293+ time .sleep (self ._scan_timeout )
294+ return self ._connect (retry - 1 , timeout )
295+
287296 if rsp and rsp ["rsp" ][0 ] == "err" :
288297 errcode = rsp ["code" ][0 ]
289298 _LOGGER .debug (
@@ -306,16 +315,16 @@ def _connect(self, retry: int, timeout: int | None = None) -> None:
306315 "Error from bluepy-helper (%s)" % errcode , rsp
307316 )
308317
309- if not rsp or rsp ["state" ][0 ] != "conn" :
310- _LOGGER .warning ("Bluehelper returned unable to connect state: %s" , rsp )
318+ if rsp is None or rsp ["state" ][0 ] != "conn" :
311319 self ._stopHelper ()
312320
313321 if rsp is None :
314- raise bluepy .btle .BTLEDisconnectError (
315- "Timed out while trying to connect to peripheral %s" % self ._mac ,
316- rsp ,
322+ _LOGGER .warning (
323+ "Timed out while trying to connect to peripheral %s" , self ._mac
317324 )
318325
326+ _LOGGER .warning ("Bluehelper returned unable to connect state: %s" , rsp )
327+
319328 raise bluepy .btle .BTLEDisconnectError (
320329 "Failed to connect to peripheral %s, rsp: %s" % (self ._mac , rsp )
321330 )
@@ -383,7 +392,7 @@ def _readkey(self) -> bytes:
383392
384393 return b"\x00 "
385394
386- def _sendcommand (self , key : str , retry : int , timeout : int | None = None ) -> bytes :
395+ def _sendcommand (self , key : str , retry : int , timeout : int | None = 40 ) -> bytes :
387396 command = self ._commandkey (key )
388397 send_success = False
389398 notify_msg = None
0 commit comments