12
12
UUID = "cba20d00-224d-11e6-9fb8-0002a5d5c51b"
13
13
HANDLE = "cba20002-224d-11e6-9fb8-0002a5d5c51b"
14
14
15
+ KEY_PASSWORD_PREFIX = "5711"
16
+
15
17
PRESS_KEY = "570100"
16
18
ON_KEY = "570101"
17
19
OFF_KEY = "570102"
18
20
21
+ ON_KEY_SUFFIX = "01"
22
+ OFF_KEY_SUFFIX = "02"
23
+ PRESS_KEY_SUFFIX = "00"
24
+
19
25
_LOGGER = logging .getLogger (__name__ )
20
26
21
27
22
28
class Switchbot :
23
29
"""Representation of a Switchbot."""
24
30
25
- def __init__ (self , mac , retry_count = DEFAULT_RETRY_COUNT ) -> None :
31
+ def __init__ (self , mac , retry_count = DEFAULT_RETRY_COUNT , password = None ) -> None :
26
32
self ._mac = mac
27
33
self ._device = None
28
34
self ._retry_count = retry_count
35
+ if password is None or password == "" :
36
+ self ._password_encoded = None
37
+ else :
38
+ self ._password_encoded = '%x' % (binascii .crc32 (password .encode ('ascii' )) & 0xffffffff )
29
39
30
40
def _connect (self ) -> None :
31
41
if self ._device is not None :
@@ -51,6 +61,16 @@ def _disconnect(self) -> None:
51
61
finally :
52
62
self ._device = None
53
63
64
+ def _commandkey (self , key ) -> str :
65
+ if self ._password_encoded is None :
66
+ return key
67
+ key_suffix = PRESS_KEY_SUFFIX
68
+ if key == ON_KEY :
69
+ key_suffix = ON_KEY_SUFFIX
70
+ elif key == OFF_KEY :
71
+ key_suffix = OFF_KEY_SUFFIX
72
+ return KEY_PASSWORD_PREFIX + self ._password_encoded + key_suffix
73
+
54
74
def _writekey (self , key ) -> bool :
55
75
_LOGGER .debug ("Prepare to send" )
56
76
hand_service = self ._device .getServiceByUUID (UUID )
@@ -66,9 +86,11 @@ def _writekey(self, key) -> bool:
66
86
67
87
def _sendcommand (self , key , retry ) -> bool :
68
88
send_success = False
89
+ command = self ._commandkey (key )
90
+ _LOGGER .debug ("Sending command to switchbot %s" , command )
69
91
try :
70
92
self ._connect ()
71
- send_success = self ._writekey (key )
93
+ send_success = self ._writekey (command )
72
94
except bluepy .btle .BTLEException :
73
95
_LOGGER .warning ("Error talking to Switchbot." , exc_info = True )
74
96
finally :
0 commit comments