Skip to content

Commit 9e9ecb8

Browse files
committed
Use async bleak for writing settings
1 parent cd3fa62 commit 9e9ecb8

File tree

2 files changed

+42
-23
lines changed

2 files changed

+42
-23
lines changed

tion_btle/s3.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ async def process_mode(mode_code: int) -> str:
107107
finally:
108108
return result
109109

110+
result: dict = {}
111+
110112
try:
111113
await self._do_action(self._connect)
112114
await self._enable_notifications()
@@ -133,19 +135,19 @@ async def process_mode(mode_code: int) -> str:
133135
except TionException as e:
134136
_LOGGER.error(str(e))
135137
result = {"code": 400, "error": "Got exception " + str(e)}
136-
finally:
137138
await self._disconnect()
138139

139-
return result
140+
if not keep_connection:
141+
await self._disconnect()
140142

141-
def set(self, request: dict, keep_connection=False):
142-
raise NotImplementedError()
143+
return result
143144

144-
def encode_request(request: dict) -> bytearray:
145-
def encode_mode(mode: str) -> int:
145+
async def set(self, request: dict, keep_connection=False):
146+
async def encode_request(request: dict) -> bytearray:
147+
async def encode_mode(mode: str) -> int:
146148
return self.modes.index(mode) if mode in self.modes else 2
147149

148-
def encode_status(status: str) -> int:
150+
async def encode_status(status: str) -> int:
149151
return self.statuses.index(status) if status in self.statuses else 0
150152

151153
try:
@@ -155,18 +157,20 @@ def encode_status(status: str) -> int:
155157
except KeyError:
156158
pass
157159

158-
settings = {**self.get(True), **request}
159-
new_settings = self.create_command(self.command_SET_PARAMS)
160+
current_settings = await self.get(True)
161+
_LOGGER.debug("set: got '%s' settings" % current_settings)
162+
settings = {**current_settings, **request}
163+
new_settings = await self.create_command(self.command_SET_PARAMS)
160164
new_settings[2] = int(settings["fan_speed"])
161165
new_settings[3] = int(settings["heater_temp"])
162-
new_settings[4] = encode_mode(settings["mode"])
163-
new_settings[5] = encode_status(settings["heater"]) | (encode_status(settings["status"]) << 1) | (
164-
encode_status(settings["sound"]) << 3)
166+
new_settings[4] = await encode_mode(settings["mode"])
167+
new_settings[5] = await encode_status(settings["heater"]) | (await encode_status(settings["status"]) << 1) | (
168+
await encode_status(settings["sound"]) << 3)
165169
return new_settings
166170
try:
167-
self._do_action(self._connect)
168-
self._do_action(self._try_write, request=encode_request(request))
171+
await self._do_action(self._connect)
172+
await self._do_action(self._try_write, request=await encode_request(request))
169173
except TionException as e:
170174
_LOGGER.error(str(e))
171175
finally:
172-
self._disconnect()
176+
await self._disconnect()

tion_btle/tion.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import abc
22
import logging
33
import time
4+
import bleak
45
import asyncio
56
from typing import Callable
67
from bleak import BleakClient
@@ -47,7 +48,7 @@ def __init__(self, mac: str):
4748
self._fan_speed = 0
4849

4950
@abc.abstractmethod
50-
def _send_request(self, request: bytearray) -> bytearray:
51+
async def _send_request(self, request: bytearray) -> bytearray:
5152
""" Send request to device
5253
5354
Args:
@@ -69,7 +70,7 @@ def _decode_response(self, response: bytearray) -> dict:
6970
pass
7071

7172
@abc.abstractmethod
72-
def _encode_request(self, request: dict) -> bytearray:
73+
async def _encode_request(self, request: dict) -> bytearray:
7374
""" Encode dictionary of request to byte array
7475
7576
Args:
@@ -80,7 +81,7 @@ def _encode_request(self, request: dict) -> bytearray:
8081
pass
8182

8283
@abc.abstractmethod
83-
def get(self, keep_connection: bool = False) -> dict:
84+
async def get(self, keep_connection: bool = False) -> dict:
8485
""" Get device information
8586
Returns:
8687
dictionay with device paramters
@@ -115,7 +116,9 @@ async def _process_status(self, code: int) -> str:
115116

116117
@property
117118
async def connection_status(self):
118-
return "connected" if await self._btle.is_connected() else "disc"
119+
status = "connected" if await self._btle.is_connected() else "disc"
120+
_LOGGER.debug("connection_status is %s" % status)
121+
return status
119122

120123
async def _connect(self):
121124
if self.mac == "dummy":
@@ -125,15 +128,22 @@ async def _connect(self):
125128
if await self.connection_status == "disc":
126129
try:
127130
await self._btle.connect()
131+
await self._btle.get_services()
128132
except exc.BleakError as e:
129133
_LOGGER.warning("Got %s exception", str(e))
130134
time.sleep(2)
131135
raise e
136+
else:
137+
_LOGGER.debug("Already connected!")
132138

133139
async def _disconnect(self):
134-
if await self.connection_status != "disc":
135-
if self.mac != "dummy":
136-
await self._btle.disconnect()
140+
try:
141+
if await self.connection_status != "disc":
142+
if self.mac != "dummy":
143+
await self._btle.disconnect()
144+
finally:
145+
# re-init client
146+
self._btle = BleakClient(self.mac)
137147

138148
async def _try_write(self, request: bytearray):
139149
if self.mac != "dummy":
@@ -177,7 +187,12 @@ async def _do_action(self, action: Callable, max_tries: int = 3, *args, **kwargs
177187

178188
async def _enable_notifications(self):
179189
_LOGGER.debug("Enabling notification")
180-
return await self._btle.start_notify(self.uuid_notify, self._delegation.handleNotification)
190+
try:
191+
result = await self._btle.start_notify(self.uuid_notify, self._delegation.handleNotification)
192+
except bleak.exc.BleakError as e:
193+
_LOGGER.critical("Got exception %s while enabling notifications!" % str(e))
194+
raise e
195+
return result
181196

182197
@property
183198
def fan_speed(self):

0 commit comments

Comments
 (0)