@@ -20,23 +20,37 @@ class Switchbot:
20
20
21
21
def __init__ (self , mac ) -> None :
22
22
self ._mac = mac
23
+ self ._device = None
24
+ self ._connect ()
23
25
24
- def _sendpacket (self , key , retry = 2 ) -> bool :
26
+ def _connect (self ) -> bool :
27
+ if self ._device is not None :
28
+ _LOGGER .debug ("Disconnecting" )
29
+ try :
30
+ self ._device .disconnect ()
31
+ except bluepy .btle .BTLEException :
32
+ pass
25
33
try :
26
34
_LOGGER .debug ("Connecting" )
27
- device = bluepy .btle .Peripheral (self ._mac ,
28
- bluepy .btle .ADDR_TYPE_RANDOM )
29
- hand_service = device .getServiceByUUID (UUID )
35
+ self ._device = bluepy .btle .Peripheral (self ._mac ,
36
+ bluepy .btle .ADDR_TYPE_RANDOM )
37
+ except bluepy .btle .BTLEException :
38
+ _LOGGER .error ("Failed to connect to switchmate" , exc_info = True )
39
+ return False
40
+ return True
41
+
42
+ def _sendpacket (self , key , retry = 2 ) -> bool :
43
+ try :
44
+ _LOGGER .debug ("Prepare to send" )
45
+ hand_service = self ._device .getServiceByUUID (UUID )
30
46
hand = hand_service .getCharacteristics (HANDLE )[0 ]
31
47
_LOGGER .debug ("Sending command, %s" , key )
32
48
hand .write (binascii .a2b_hex (key ))
33
- _LOGGER .debug ("Disconnecting" )
34
- device .disconnect ()
35
49
except bluepy .btle .BTLEException :
36
- _LOGGER .error ("Cannot connect to switchbot. Retrying" , exc_info = True )
37
- if retry < 1 :
50
+ if retry < 1 or not self ._connect ():
38
51
_LOGGER .error ("Cannot connect to switchbot." , exc_info = True )
39
52
return False
53
+ _LOGGER .error ("Cannot connect to switchbot. Retrying" , exc_info = True )
40
54
return self ._sendpacket (key , retry - 1 )
41
55
return True
42
56
0 commit comments