From 15216e1268619329e0372c212aaa010a0637f08f Mon Sep 17 00:00:00 2001 From: Patrick762 Date: Sat, 26 Aug 2023 15:25:14 +0200 Subject: [PATCH] added option for persistant connection --- custom_components/bluetti_bt/__init__.py | 10 ++++- custom_components/bluetti_bt/config_flow.py | 2 +- custom_components/bluetti_bt/coordinator.py | 41 +++++++++++++++---- .../bluetti_bt/translations/de.json | 2 +- .../bluetti_bt/translations/en.json | 2 +- 5 files changed, 44 insertions(+), 13 deletions(-) diff --git a/custom_components/bluetti_bt/__init__.py b/custom_components/bluetti_bt/__init__.py index 5b51176..5e73625 100644 --- a/custom_components/bluetti_bt/__init__.py +++ b/custom_components/bluetti_bt/__init__.py @@ -12,7 +12,7 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.exceptions import ConfigEntryNotReady -from .const import CONF_POLLING_INTERVAL, DATA_COORDINATOR, DOMAIN, MANUFACTURER, CONF_USE_CONTROLS, DATA_POLLING_RUNNING +from .const import CONF_PERSISTANT_CONN, CONF_POLLING_INTERVAL, DATA_COORDINATOR, DOMAIN, MANUFACTURER, CONF_USE_CONTROLS, DATA_POLLING_RUNNING from .coordinator import PollingCoordinator PLATFORMS: [Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR] @@ -26,6 +26,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: device_name = entry.data.get(CONF_NAME) use_controls = entry.data.get(CONF_USE_CONTROLS) polling_interval = entry.data.get(CONF_POLLING_INTERVAL, 20) + persistant_conn = entry.data.get(CONF_PERSISTANT_CONN, False) + + # Prevent persistant connection and controls at same time + if use_controls is True and persistant_conn is True: + _LOGGER.warning("Enabling controls and persistant connection at the same time is currently not supported. Disabled persistant connection") + persistant_conn = False if address is None: return False @@ -39,7 +45,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: hass.data[DOMAIN][entry.entry_id].setdefault(DATA_POLLING_RUNNING, False) # Create coordinator for polling - coordinator = PollingCoordinator(hass, address, device_name, polling_interval) + coordinator = PollingCoordinator(hass, address, device_name, polling_interval, persistant_conn) await coordinator.async_config_entry_first_refresh() hass.data[DOMAIN][entry.entry_id].setdefault(DATA_COORDINATOR, coordinator) diff --git a/custom_components/bluetti_bt/config_flow.py b/custom_components/bluetti_bt/config_flow.py index 98a74ec..6dcb071 100644 --- a/custom_components/bluetti_bt/config_flow.py +++ b/custom_components/bluetti_bt/config_flow.py @@ -17,7 +17,7 @@ from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers import selector from . import get_type_by_bt_name -from .const import CONF_PERSISTANT_CONN, CONF_POLLING_INTERVAL, DOMAIN, CONF_USE_CONTROLS +from .const import CONF_PERSISTANT_CONN, CONF_POLLING_INTERVAL, DATA_COORDINATOR, DOMAIN, CONF_USE_CONTROLS _LOGGER = logging.getLogger(__name__) diff --git a/custom_components/bluetti_bt/coordinator.py b/custom_components/bluetti_bt/coordinator.py index b8e6694..35a5f50 100644 --- a/custom_components/bluetti_bt/coordinator.py +++ b/custom_components/bluetti_bt/coordinator.py @@ -129,7 +129,14 @@ class DummyDevice(BluettiDevice): class PollingCoordinator(DataUpdateCoordinator): """Polling coordinator.""" - def __init__(self, hass: HomeAssistant, address, device_name: str, polling_interval: int): + def __init__( + self, + hass: HomeAssistant, + address: str, + device_name: str, + polling_interval: int, + persistant_conn: bool, + ): """Initialize coordinator.""" super().__init__( hass, @@ -138,10 +145,12 @@ class PollingCoordinator(DataUpdateCoordinator): update_interval=timedelta(seconds=polling_interval), ) self._address = address + self.client = None self.notify_future = None self.current_command = None self.notify_response = bytearray() bluetti_device = build_device(address, device_name) + self.persistant_conn = persistant_conn # Add or modify device fields self.bluetti_device = DummyDevice(bluetti_device) @@ -166,16 +175,30 @@ class PollingCoordinator(DataUpdateCoordinator): return None # Polling - client = BleakClient(device) + self.client = BleakClient(device) parsed_data: dict = {} + # Connect to device + try: + async with async_timeout.timeout(5): + await self.client.connect() + + await self.client.start_notify( + BluetoothClient.NOTIFY_UUID, self._notification_handler + ) + except TimeoutError: + self.logger.warning("Connection timed out for device %s", self._address) + return None + except BleakError as err: + self.logger.warning("Bleak error: %s", err) + return None + try: async with async_timeout.timeout(15): - await client.connect() - await client.start_notify( - BluetoothClient.NOTIFY_UUID, self._notification_handler - ) + # Reconnect if not connected + if not self.client.is_connected: + await self.client.connect() for command in self.bluetti_device.polling_commands: try: @@ -186,7 +209,7 @@ class PollingCoordinator(DataUpdateCoordinator): # Make request self.logger.debug("Requesting %s", command) - await client.write_gatt_char( + await self.client.write_gatt_char( BluetoothClient.WRITE_UUID, bytes(command) ) @@ -229,7 +252,9 @@ class PollingCoordinator(DataUpdateCoordinator): self.logger.warning("Bleak error: %s", err) return None finally: - await client.disconnect() + # Disconnect if connection not persistant + if not self.persistant_conn: + await self.client.disconnect() self.hass.data[DOMAIN][self.config_entry.entry_id][DATA_POLLING_RUNNING] = False diff --git a/custom_components/bluetti_bt/translations/de.json b/custom_components/bluetti_bt/translations/de.json index 850227c..abe7a9e 100644 --- a/custom_components/bluetti_bt/translations/de.json +++ b/custom_components/bluetti_bt/translations/de.json @@ -5,7 +5,7 @@ "data": { "use_controls": "Steuerung aktivieren (auf eigenes Risiko)", "persistant_conn": "Dauerhafte Verbindung", - "polling_interval": "Datenabruf-Intervall" + "polling_interval": "Datenabruf-Intervall in Sekunden (Neustart erforderlich)" } } } diff --git a/custom_components/bluetti_bt/translations/en.json b/custom_components/bluetti_bt/translations/en.json index e622734..5aa6eb7 100644 --- a/custom_components/bluetti_bt/translations/en.json +++ b/custom_components/bluetti_bt/translations/en.json @@ -5,7 +5,7 @@ "data": { "use_controls": "Use controls (use at own risk)", "persistant_conn": "Persistant connection", - "polling_interval": "Polling interval" + "polling_interval": "Polling interval in seconds (restart required)" } } }