Skip to content

Commit 47131a3

Browse files
Merge pull request #2 from Danielhiversen/beta
keep connection
2 parents 867d514 + f8d5ce2 commit 47131a3

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

switchbot/__init__.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,37 @@ class Switchbot:
2020

2121
def __init__(self, mac) -> None:
2222
self._mac = mac
23+
self._device = None
24+
self._connect()
2325

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
2533
try:
2634
_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)
3046
hand = hand_service.getCharacteristics(HANDLE)[0]
3147
_LOGGER.debug("Sending command, %s", key)
3248
hand.write(binascii.a2b_hex(key))
33-
_LOGGER.debug("Disconnecting")
34-
device.disconnect()
3549
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():
3851
_LOGGER.error("Cannot connect to switchbot.", exc_info=True)
3952
return False
53+
_LOGGER.error("Cannot connect to switchbot. Retrying", exc_info=True)
4054
return self._sendpacket(key, retry-1)
4155
return True
4256

0 commit comments

Comments
 (0)