Allow switches with persistent_conn and add mutex to guard polling

This commit is contained in:
SupaFlav committed 2023-09-03 23:33:26 -04:00
1 parent d38c30011c
commit c3afdcfe89
3 files changed
+16 -20

No files matched your search

-5
View File
@@ -28,11 +28,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
polling_interval = entry.data.get(CONF_POLLING_INTERVAL, 20) polling_interval = entry.data.get(CONF_POLLING_INTERVAL, 20)
persistent_conn = entry.data.get(CONF_PERSISTENT_CONN, False) persistent_conn = entry.data.get(CONF_PERSISTENT_CONN, False)
# Prevent persistant connection and controls at same time
if use_controls is True and persistent_conn is True:
_LOGGER.warning("Enabling controls and persistant connection at the same time is currently not supported. Disabled persistant connection")
persistent_conn = False
if address is None: if address is None:
return False return False
+5 -1
View File
@@ -167,6 +167,9 @@ class PollingCoordinator(DataUpdateCoordinator):
return None return None
self.client = BleakClient(device) self.client = BleakClient(device)
# polling mutex to guard against switches
self.polling_lock = asyncio.Lock()
async def _async_update_data(self): async def _async_update_data(self):
"""Fetch data from API endpoint. """Fetch data from API endpoint.
@@ -183,6 +186,7 @@ class PollingCoordinator(DataUpdateCoordinator):
parsed_data: dict = {} parsed_data: dict = {}
async with self.polling_lock:
try: try:
async with async_timeout.timeout(30): async with async_timeout.timeout(30):
@@ -265,7 +269,7 @@ class PollingCoordinator(DataUpdateCoordinator):
self.notify_response = bytearray() self.notify_response = bytearray()
# Make request # Make request
self.logger.debug("Requesting %s (%s)", command) self.logger.debug("Requesting %s", command)
await self.client.write_gatt_char( await self.client.write_gatt_char(
BluetoothClient.WRITE_UUID, bytes(command) BluetoothClient.WRITE_UUID, bytes(command)
) )
+11 -14
View File
@@ -99,6 +99,9 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
super().__init__(coordinator) super().__init__(coordinator)
self._bluetti_device = bluetti_device self._bluetti_device = bluetti_device
self._coordinator = coordinator
self._client = coordinator.client
self._polling_lock = coordinator.polling_lock
e_name = f"{device_info.get('name')} {name}" e_name = f"{device_info.get('name')} {name}"
self._address = address self._address = address
self._response_key = response_key self._response_key = response_key
@@ -156,25 +159,17 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
async def write_to_device(self, state: bool): async def write_to_device(self, state: bool):
"""Write to device.""" """Write to device."""
device = bluetooth.async_ble_device_from_address(self.hass, self._address)
if device is None:
_LOGGER.error("Device %s not available", mac_loggable(self._address))
return
command = self._bluetti_device.build_setter_command(self._response_key, state) command = self._bluetti_device.build_setter_command(self._response_key, state)
# Wait until polling is done async with self._polling_lock:
while self.hass.data[DOMAIN][self._entry_id][DATA_POLLING_RUNNING] is True:
_LOGGER.debug("Waiting for polling to finish...")
asyncio.sleep(1)
client = BleakClient(device)
try: try:
async with async_timeout.timeout(15): async with async_timeout.timeout(15):
await client.connect() if not self._client.is_connected:
await self._client.connect()
# Send command # Send command
await client.write_gatt_char( _LOGGER.debug("Requesting %s (%s,%s)", command, self._response_key, state)
await self._client.write_gatt_char(
BluetoothClient.WRITE_UUID, bytes(command) BluetoothClient.WRITE_UUID, bytes(command)
) )
@@ -188,6 +183,8 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
_LOGGER.error("Bleak error: %s", err) _LOGGER.error("Bleak error: %s", err)
return None return None
finally: finally:
await client.disconnect() # Disconnect if connection not persistant
if not self._coordinator.persistent_conn:
await self._client.disconnect()
await self.coordinator.async_request_refresh() await self.coordinator.async_request_refresh()