1212UUID = "cba20d00-224d-11e6-9fb8-0002a5d5c51b"
1313HANDLE = "cba20002-224d-11e6-9fb8-0002a5d5c51b"
1414
15+ KEY_PASSWORD_PREFIX = "5711"
16+
1517PRESS_KEY = "570100"
1618ON_KEY = "570101"
1719OFF_KEY = "570102"
1820
21+ ON_KEY_SUFFIX = "01"
22+ OFF_KEY_SUFFIX = "02"
23+ PRESS_KEY_SUFFIX = "00"
24+
1925_LOGGER = logging .getLogger (__name__ )
2026
2127
2228class Switchbot :
2329 """Representation of a Switchbot."""
2430
25- def __init__ (self , mac , retry_count = DEFAULT_RETRY_COUNT ) -> None :
31+ def __init__ (self , mac , retry_count = DEFAULT_RETRY_COUNT , password = None ) -> None :
2632 self ._mac = mac
2733 self ._device = None
2834 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 )
2939
3040 def _connect (self ) -> None :
3141 if self ._device is not None :
@@ -51,6 +61,16 @@ def _disconnect(self) -> None:
5161 finally :
5262 self ._device = None
5363
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+
5474 def _writekey (self , key ) -> bool :
5575 _LOGGER .debug ("Prepare to send" )
5676 hand_service = self ._device .getServiceByUUID (UUID )
@@ -66,9 +86,11 @@ def _writekey(self, key) -> bool:
6686
6787 def _sendcommand (self , key , retry ) -> bool :
6888 send_success = False
89+ command = self ._commandkey (key )
90+ _LOGGER .debug ("Sending command to switchbot %s" , command )
6991 try :
7092 self ._connect ()
71- send_success = self ._writekey (key )
93+ send_success = self ._writekey (command )
7294 except bluepy .btle .BTLEException :
7395 _LOGGER .warning ("Error talking to Switchbot." , exc_info = True )
7496 finally :
0 commit comments