added option for persistant connection

This commit is contained in:
Patrick762 committed 2023-08-26 15:25:14 +02:00
1 parent ed10127a90
commit 15216e1268
5 files changed
+44 -13

No files matched your search

+8 -2
View File
@@ -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)
+1 -1
View File
@@ -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__)
+33 -8
View File
@@ -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
@@ -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)"
}
}
}
@@ -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)"
}
}
}