Merge pull request #13 from Patrick762/dev

Config options
This commit is contained in:
Patrick762 authored and GitHub committed 2023-08-26 20:31:22 +02:00
commit 3a662964b8
11 files changed
+128 -43

No files matched your search

+9 -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 DATA_COORDINATOR, DOMAIN, MANUFACTURER, CONF_USE_CONTROLS, DATA_POLLING_RUNNING
from .const import CONF_PERSISTENT_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]
@@ -25,6 +25,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.data.get(CONF_ADDRESS)
device_name = entry.data.get(CONF_NAME)
use_controls = entry.data.get(CONF_USE_CONTROLS)
polling_interval = entry.data.get(CONF_POLLING_INTERVAL, 20)
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:
return False
@@ -38,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)
coordinator = PollingCoordinator(hass, address, device_name, polling_interval, persistent_conn)
await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][entry.entry_id].setdefault(DATA_COORDINATOR, coordinator)
@@ -28,6 +28,7 @@ from bluetti_mqtt.mqtt_client import (
from . import device_info as dev_info, get_unique_id
from .const import DATA_COORDINATOR, DOMAIN, ADDITIONAL_DEVICE_FIELDS
from .coordinator import PollingCoordinator, DummyDevice
from .utils import unique_id_loggable
_LOGGER = logging.getLogger(__name__)
@@ -35,7 +36,7 @@ _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Setup sensor entities."""
"""Setup binary_sensor entities."""
device_name = entry.data.get(CONF_NAME)
address = entry.data.get(CONF_ADDRESS)
@@ -43,7 +44,7 @@ async def async_setup_entry(
_LOGGER.error("Device has no address")
# Generate device info
_LOGGER.info("Creating sensors for device with address %s", address)
_LOGGER.info("Creating binary_sensors for device with address %s", address)
device_info = dev_info(entry)
# Add sensors according to device_info
@@ -103,10 +104,10 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
_LOGGER.debug("Updating state of %s", self._attr_unique_id)
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
if not isinstance(self.coordinator.data, dict):
_LOGGER.error(
"Invalid data from coordinator (sensor.%s)", self._attr_unique_id
_LOGGER.debug(
"Invalid data from coordinator (binary_sensor.%s)", unique_id_loggable(self._attr_unique_id)
)
self._attr_available = False
return
@@ -118,8 +119,8 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
if not isinstance(response_data, bool):
_LOGGER.warning(
"Invalid response data type from coordinator (sensor.%s): %s",
self._attr_unique_id,
"Invalid response data type from coordinator (binary_sensor.%s): %s",
unique_id_loggable(self._attr_unique_id),
response_data,
)
self._attr_available = False
+18 -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 DOMAIN, CONF_USE_CONTROLS
from .const import CONF_PERSISTENT_CONN, CONF_POLLING_INTERVAL, DATA_COORDINATOR, DOMAIN, CONF_USE_CONTROLS
_LOGGER = logging.getLogger(__name__)
@@ -108,12 +108,19 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
) -> FlowResult:
"""Manage the options."""
if user_input is not None:
# Validate update interval
if user_input[CONF_POLLING_INTERVAL] < 5:
return self.async_abort(reason="invalid_interval")
changed = self.hass.config_entries.async_update_entry(
self.config_entry,
data={
**self.config_entry.data,
**{
CONF_USE_CONTROLS: user_input[CONF_USE_CONTROLS],
CONF_PERSISTENT_CONN: user_input[CONF_PERSISTENT_CONN],
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
},
},
)
@@ -126,6 +133,8 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
title="",
data={
CONF_USE_CONTROLS: user_input[CONF_USE_CONTROLS],
CONF_PERSISTENT_CONN: user_input[CONF_PERSISTENT_CONN],
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
},
)
@@ -137,6 +146,14 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
CONF_USE_CONTROLS,
default=self.config_entry.data.get(CONF_USE_CONTROLS, False),
): selector.BooleanSelector(),
vol.Required(
CONF_PERSISTENT_CONN,
default=self.config_entry.data.get(CONF_PERSISTENT_CONN, False),
): selector.BooleanSelector(),
vol.Required(
CONF_POLLING_INTERVAL,
default=self.config_entry.data.get(CONF_POLLING_INTERVAL, 20),
): int,
}
),
)
+2
View File
@@ -7,6 +7,8 @@ MANUFACTURER = "Bluetti"
CONF_OPTIONS = "options"
CONF_USE_CONTROLS = "use_controls"
CONF_PERSISTENT_CONN = "persistent_conn"
CONF_POLLING_INTERVAL = "polling_interval"
DATA_COORDINATOR = "coordinator"
DATA_POLLING_RUNNING = "polling_running"
+51 -17
View File
@@ -27,6 +27,7 @@ from bluetti_mqtt.core.devices.bluetti_device import BluettiDevice
from bluetti_mqtt.core.commands import ReadHoldingRegisters
from .const import DATA_POLLING_RUNNING, DOMAIN
from .utils import mac_loggable
_LOGGER = logging.getLogger(__name__)
@@ -129,23 +130,39 @@ class DummyDevice(BluettiDevice):
class PollingCoordinator(DataUpdateCoordinator):
"""Polling coordinator."""
def __init__(self, hass: HomeAssistant, address, device_name: str):
def __init__(
self,
hass: HomeAssistant,
address: str,
device_name: str,
polling_interval: int,
persistent_conn: bool,
):
"""Initialize coordinator."""
super().__init__(
hass,
_LOGGER,
name="Bluetti polling coordinator",
update_interval=timedelta(seconds=20),
update_interval=timedelta(seconds=polling_interval),
)
self._address = address
self.has_notifier = False
self.notify_future = None
self.current_command = None
self.notify_response = bytearray()
bluetti_device = build_device(address, device_name)
self.persistent_conn = persistent_conn
# Add or modify device fields
self.bluetti_device = DummyDevice(bluetti_device)
# Create client
device = bluetooth.async_ble_device_from_address(hass, address)
if device is None:
self.logger.error("Device %s not available", mac_loggable(address))
return None
self.client = BleakClient(device)
async def _async_update_data(self):
"""Fetch data from API endpoint.
@@ -156,26 +173,41 @@ class PollingCoordinator(DataUpdateCoordinator):
self.logger.debug("Polling data")
device = bluetooth.async_ble_device_from_address(self.hass, self._address)
if device is None:
self.logger.error("Device %s not available", self._address)
return None
if self.bluetti_device is None:
self.logger.error("Device type for %s not found", self._address)
self.logger.error("Device type for %s not found", mac_loggable(self._address))
return None
# Polling
client = BleakClient(device)
parsed_data: dict = {}
# Connect to device
try:
async with async_timeout.timeout(20):
await self.client.connect()
await self.client.start_notify(
BluetoothClient.NOTIFY_UUID, self._notification_handler
)
self.has_notifier = True
except TimeoutError:
self.logger.debug("Connection timed out for device %s", mac_loggable(self._address))
return None
except BleakError as err:
self.logger.debug("Bleak error: %s", err)
return None
try:
async with async_timeout.timeout(15):
await client.connect()
await client.start_notify(
# Reconnect if not connected
if not self.client.is_connected:
await self.client.connect()
# Attach notifier if needed
if not self.has_notifier:
await self.client.start_notify(
BluetoothClient.NOTIFY_UUID, self._notification_handler
)
self.has_notifier = True
for command in self.bluetti_device.polling_commands:
try:
@@ -186,7 +218,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)
)
@@ -207,8 +239,8 @@ class PollingCoordinator(DataUpdateCoordinator):
parsed_data.update(parsed)
except TimeoutError:
self.logger.warning(
"Polling timed out (address: %s)", self._address
self.logger.debug(
"Polling timed out (address: %s)", mac_loggable(self._address)
)
except ParseError:
self.logger.warning("Got a parse exception...")
@@ -223,13 +255,15 @@ class PollingCoordinator(DataUpdateCoordinator):
"Needed to disconnect due to error: %s (This can also be the case if you used device controls)", err
)
except TimeoutError:
self.logger.warning("Polling timed out for device %s", self._address)
self.logger.debug("Polling timed out for device %s", mac_loggable(self._address))
return None
except BleakError as err:
self.logger.warning("Bleak error: %s", err)
return None
finally:
await client.disconnect()
# Disconnect if connection not persistant
if not self.persistent_conn:
await self.client.disconnect()
self.hass.data[DOMAIN][self.config_entry.entry_id][DATA_POLLING_RUNNING] = False
+1 -1
View File
@@ -18,5 +18,5 @@
"iot_class": "local_polling",
"issue_tracker": "https://github.com/Patrick762/hassio-bluetti-bt/issues",
"requirements": ["bluetti_mqtt==0.15.0"],
"version": "0.0.8"
"version": "0.0.10"
}
+5 -4
View File
@@ -32,6 +32,7 @@ from bluetti_mqtt.mqtt_client import (
from . import device_info as dev_info, get_unique_id
from .const import DATA_COORDINATOR, DOMAIN, CONF_OPTIONS, DIAGNOSTIC_FIELDS, ADDITIONAL_DEVICE_FIELDS
from .coordinator import PollingCoordinator, DummyDevice
from .utils import unique_id_loggable
_LOGGER = logging.getLogger(__name__)
@@ -129,10 +130,10 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
_LOGGER.debug("Updating state of %s", self._attr_unique_id)
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
if not isinstance(self.coordinator.data, dict):
_LOGGER.error(
"Invalid data from coordinator (sensor.%s)", self._attr_unique_id
_LOGGER.debug(
"Invalid data from coordinator (sensor.%s)", unique_id_loggable(self._attr_unique_id)
)
self._attr_available = False
return
@@ -151,7 +152,7 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
):
_LOGGER.warning(
"Invalid response data type from coordinator (sensor.%s): %s has type %s",
self._attr_unique_id,
unique_id_loggable(self._attr_unique_id),
response_data,
type(response_data),
)
+10 -9
View File
@@ -35,6 +35,7 @@ from bluetti_mqtt.mqtt_client import (
from . import device_info as dev_info, get_unique_id
from .const import CONTROL_FIELDS, DATA_COORDINATOR, DATA_POLLING_RUNNING, DOMAIN, ADDITIONAL_DEVICE_FIELDS
from .coordinator import PollingCoordinator, DummyDevice
from .utils import mac_loggable, unique_id_loggable
_LOGGER = logging.getLogger(__name__)
@@ -50,7 +51,7 @@ async def async_setup_entry(
_LOGGER.error("Device has no address")
# Generate device info
_LOGGER.info("Creating sensors for device with address %s", address)
_LOGGER.info("Creating switches for device with address %s", address)
device_info = dev_info(entry)
# Add sensors according to device_info
@@ -113,10 +114,10 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
_LOGGER.debug("Updating state of %s", self._attr_unique_id)
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
if not isinstance(self.coordinator.data, dict):
_LOGGER.error(
"Invalid data from coordinator (sensor.%s)", self._attr_unique_id
"Invalid data from coordinator (switch.%s)", unique_id_loggable(self._attr_unique_id)
)
self._attr_available = False
return
@@ -128,8 +129,8 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
if not isinstance(response_data, bool):
_LOGGER.warning(
"Invalid response data type from coordinator (sensor.%s): %s",
self._attr_unique_id,
"Invalid response data type from coordinator (switch.%s): %s",
unique_id_loggable(self._attr_unique_id),
response_data,
)
self._attr_available = False
@@ -141,19 +142,19 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
async def async_turn_on(self, **kwargs):
"""Turn the entity on."""
_LOGGER.debug("Turn on %s on %s", self._response_key, self._address)
_LOGGER.debug("Turn on %s on %s", self._response_key, mac_loggable(self._address))
await self.write_to_device(True)
async def async_turn_off(self, **kwargs):
"""Turn the entity off."""
_LOGGER.debug("Turn off %s on %s", self._response_key, self._address)
_LOGGER.debug("Turn off %s on %s", self._response_key, mac_loggable(self._address))
await self.write_to_device(False)
async def write_to_device(self, state: bool):
"""Write to device."""
device = bluetooth.async_ble_device_from_address(self.hass, self._address)
if device is None:
_LOGGER.error("Device %s not available", self._address)
_LOGGER.error("Device %s not available", mac_loggable(self._address))
return
command = self._bluetti_device.build_setter_command(self._response_key, state)
@@ -177,7 +178,7 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
await asyncio.sleep(5)
except TimeoutError:
_LOGGER.error("Timed out for device %s", self._address)
_LOGGER.error("Timed out for device %s", mac_loggable(self._address))
return None
except BleakError as err:
_LOGGER.error("Bleak error: %s", err)
@@ -3,9 +3,14 @@
"step": {
"init": {
"data": {
"use_controls": "Steuerung aktivieren (auf eigenes Risiko)"
"use_controls": "Steuerung aktivieren (auf eigenes Risiko)",
"persistent_conn": "Dauerhafte Verbindung (Neustart erforderlich)",
"polling_interval": "Datenabruf-Intervall in Sekunden (Neustart erforderlich)"
}
}
},
"abort": {
"invalid_interval": "Ungültiger Datenabruf-Intervall. Verwende 5 Sekunden oder mehr"
}
}
}
@@ -3,9 +3,14 @@
"step": {
"init": {
"data": {
"use_controls": "Use controls (use at own risk)"
"use_controls": "Use controls (use at own risk)",
"persistent_conn": "Persistent connection (restart required)",
"polling_interval": "Polling interval in seconds (restart required)"
}
}
},
"abort": {
"invalid_interval": "Invalid polling interval. Use 5 seconds or more"
}
}
}
+12
View File
@@ -0,0 +1,12 @@
"""Tools."""
def mac_loggable(mac: str) -> str:
"""Remove parts of the mac address for logging."""
splitted = mac.split(":")
return "XX:XX:XX:XX:XX:" + splitted[-1]
def unique_id_loggable(unique_id: str) -> str:
"""Remove parts of the unique id for logging."""
splitted = unique_id.split("_", maxsplit=1)
serial = splitted[0][:6]
return serial + "XXXXXXXXXX" + splitted[1]