Compare commits

...
16 Commits
Author SHA1 Message Date
Patrick762 3a662964b8 Merge pull request #13 from Patrick762/dev
Config options
2023-08-26 20:31:22 +02:00
Patrick762 43be1e1dbe added utility to make macs loggable 2023-08-26 18:01:05 +02:00
Patrick762 e0c7ada147 updated version number 2023-08-26 16:00:41 +02:00
Patrick762 cf43c55cb8 fixed error on first device setup 2023-08-26 15:56:10 +02:00
Patrick762 a5ced35d32 added validation for polling interval 2023-08-26 15:54:33 +02:00
Patrick762 15216e1268 added option for persistant connection 2023-08-26 15:25:14 +02:00
Patrick762 ed10127a90 added option to set polling interval 2023-08-26 14:44:03 +02:00
Patrick762 4c286324c7 Merge pull request #12 from Patrick762/dev
increased version number
2023-08-19 22:42:07 +02:00
Patrick762 6361e661c0 increased version number 2023-08-19 22:41:39 +02:00
Patrick762 0d237f2e45 Merge pull request #11 from Patrick762/dev
Improvements and bug fixes
2023-08-19 22:40:40 +02:00
Patrick762 95f2331cc3 fixed enum sensors 2023-08-19 22:38:30 +02:00
Patrick762 61bc379d3a updated readme 2023-08-19 21:20:32 +02:00
Patrick762 dd7665f069 added option to turn on and off outputs 2023-08-19 21:17:44 +02:00
Patrick762 8fce8270b2 added switches for ac and dc on off 2023-08-19 17:38:24 +02:00
Patrick762 886ab957bb added options flow 2023-08-19 17:06:58 +02:00
Patrick762 5a6dbb8d00 added "my" link to readme 2023-08-19 17:05:59 +02:00
12 changed files with 429 additions and 49 deletions

No files matched your search

+5
View File
@@ -3,6 +3,7 @@
[![Validate with hassfest](https://github.com/Patrick762/hassio-bluetti-bt/actions/workflows/hassfest_validation.yml/badge.svg)](https://github.com/Patrick762/hassio-bluetti-bt/actions/workflows/hassfest_validation.yml)
[![HACS Action](https://github.com/Patrick762/hassio-bluetti-bt/actions/workflows/HACS.yml/badge.svg)](https://github.com/Patrick762/hassio-bluetti-bt/actions/workflows/HACS.yml)
[![Add repo to HACS](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?repository=hassio-bluetti-bt&owner=Patrick762)
Bluetti Integration for Home Assistant
@@ -23,3 +24,7 @@ Based on [bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt).
### Available sensors:
All sensors which are available in bluetti_mqtt (Based on [this file](https://github.com/warhammerkid/bluetti_mqtt/blob/main/bluetti_mqtt/mqtt_client.py))
excluding battery pack fields.
### Available controls:
If enabled in the Integration options (you need to reload the integration if you change this option):
AC and DC outputs
+24 -7
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import re
import logging
from homeassistant.components import bluetooth
from homeassistant.config_entries import ConfigEntry
@@ -11,10 +12,11 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.exceptions import ConfigEntryNotReady
from .const import DOMAIN, MANUFACTURER
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]
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
@@ -22,6 +24,14 @@ 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
@@ -29,16 +39,23 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if not bluetooth.async_address_present(hass, address):
raise ConfigEntryNotReady("Bluetti device not present")
# Create coordinator for polling
coordinator = PollingCoordinator(hass, address, device_name)
await coordinator.async_config_entry_first_refresh()
# Create data structure
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN].setdefault(entry.entry_id, coordinator)
hass.data[DOMAIN].setdefault(entry.entry_id, {})
hass.data[DOMAIN][entry.entry_id].setdefault(DATA_POLLING_RUNNING, False)
# Create coordinator for polling
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)
platforms: list = PLATFORMS
if use_controls is True:
_LOGGER.warning("You are using controls with this integration at your own risk!")
platforms.append(Platform.SWITCH)
# Setup platforms
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
await hass.config_entries.async_forward_entry_setups(entry, platforms)
return True
+10 -9
View File
@@ -26,8 +26,9 @@ from bluetti_mqtt.mqtt_client import (
)
from . import device_info as dev_info, get_unique_id
from .const import DOMAIN, ADDITIONAL_DEVICE_FIELDS
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
@@ -63,7 +64,7 @@ async def async_setup_entry(
sensors_to_add.append(
BluettiBinarySensor(
hass.data[DOMAIN][entry.entry_id],
hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR],
device_info,
address,
field_key,
@@ -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
+72 -1
View File
@@ -14,9 +14,10 @@ from homeassistant.components.bluetooth import (
)
from homeassistant.const import CONF_ADDRESS, CONF_TYPE, CONF_NAME
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import selector
from . import get_type_by_bt_name
from .const import DOMAIN
from .const import CONF_PERSISTENT_CONN, CONF_POLLING_INTERVAL, DATA_COORDINATOR, DOMAIN, CONF_USE_CONTROLS
_LOGGER = logging.getLogger(__name__)
@@ -86,3 +87,73 @@ class BluettiConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
step_id="user",
data_schema=data_schema,
)
@staticmethod
def async_get_options_flow(
config_entry: config_entries.ConfigEntry,
) -> config_entries.OptionsFlow:
"""Create the options flow."""
return OptionsFlowHandler(config_entry)
class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle a option flow."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> 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],
},
},
)
if changed is False:
_LOGGER.error(
"Method OptionsFlowHandler.async_step_init: Config entry %s has not been changed",
self.config_entry.entry_id,
)
return self.async_create_entry(
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],
},
)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
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,
}
),
)
+11
View File
@@ -6,6 +6,17 @@ DOMAIN = "bluetti_bt"
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"
CONTROL_FIELDS = [
"ac_output_on",
"dc_output_on",
]
DIAGNOSTIC_FIELDS = [
"max_ac_input_power",
+60 -21
View File
@@ -1,12 +1,11 @@
"""Coordinator for Bluetti integration."""
from __future__ import annotations
from typing import List
from typing import List, cast
import asyncio
from datetime import timedelta
import logging
from typing import cast
import async_timeout
from bleak import BleakClient, BleakError
@@ -27,6 +26,9 @@ from bluetti_mqtt.bluetooth import (
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__)
@@ -128,51 +130,84 @@ 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.
This is the place to pre-process the data to lookup tables
so entities can quickly look up their data.
"""
self.hass.data[DOMAIN][self.config_entry.entry_id][DATA_POLLING_RUNNING] = True
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:
@@ -183,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)
)
@@ -204,8 +239,8 @@ class PollingCoordinator(DataUpdateCoordinator):
parsed_data.update(parsed)
except TimeoutError:
self.logger.error(
"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...")
@@ -217,16 +252,20 @@ class PollingCoordinator(DataUpdateCoordinator):
)
except (BadConnectionError, BleakError) as err:
self.logger.warning(
"Needed to disconnect due to error: %s", err
"Needed to disconnect due to error: %s (This can also be the case if you used device controls)", err
)
except TimeoutError:
self.logger.error("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.error("Bleak error: %s", 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
# Pass data back to sensors
return parsed_data
+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.2"
"version": "0.0.10"
}
+13 -10
View File
@@ -1,6 +1,7 @@
"""Bluetti BT sensors."""
from __future__ import annotations
from enum import Enum
import logging
from decimal import Decimal
@@ -29,8 +30,9 @@ from bluetti_mqtt.mqtt_client import (
)
from . import device_info as dev_info, get_unique_id
from .const import DOMAIN, CONF_OPTIONS, DIAGNOSTIC_FIELDS, ADDITIONAL_DEVICE_FIELDS
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__)
@@ -65,7 +67,7 @@ async def async_setup_entry(
if field_config.type == MqttFieldType.NUMERIC:
sensors_to_add.append(
BluettiSensor(
hass.data[DOMAIN][entry.entry_id],
hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR],
device_info,
address,
field_key,
@@ -79,7 +81,7 @@ async def async_setup_entry(
elif field_config.type == MqttFieldType.ENUM:
sensors_to_add.append(
BluettiSensor(
hass.data[DOMAIN][entry.entry_id],
hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR],
device_info,
address,
field_key,
@@ -128,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
@@ -146,10 +148,11 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
and not isinstance(response_data, float)
and not isinstance(response_data, complex)
and not isinstance(response_data, Decimal)
and not isinstance(response_data, Enum)
):
_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),
)
@@ -161,11 +164,11 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
# Different for enum and numeric
if (
self._options is not None
and isinstance(response_data, int)
and response_data < len(self._options)
and isinstance(response_data, Enum)
and response_data.value < len(self._options)
):
# Enum
self._attr_native_value = self._options[response_data]
self._attr_native_value = self._options[response_data.value]
else:
# Numeric
self._attr_native_value = response_data
+189
View File
@@ -0,0 +1,189 @@
"""Bluetti BT switches."""
from __future__ import annotations
import asyncio
import logging
import async_timeout
from bleak import BleakClient, BleakError
from homeassistant.components import bluetooth
from homeassistant.components.switch import SwitchEntity, SwitchDeviceClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.const import (
CONF_ADDRESS,
CONF_NAME,
EntityCategory,
)
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
)
from bluetti_mqtt.bluetooth import build_device
from bluetti_mqtt.bluetooth.client import BluetoothClient
from bluetti_mqtt.core.devices.bluetti_device import BluettiDevice
from bluetti_mqtt.mqtt_client import (
NORMAL_DEVICE_FIELDS,
DC_INPUT_FIELDS,
MqttFieldType,
)
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__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Setup switch entities."""
device_name = entry.data.get(CONF_NAME)
address = entry.data.get(CONF_ADDRESS)
if address is None:
_LOGGER.error("Device has no address")
# Generate device info
_LOGGER.info("Creating switches for device with address %s", address)
device_info = dev_info(entry)
# Add sensors according to device_info
bluetti_device = build_device(address, device_name)
bluetti_device = DummyDevice(bluetti_device)
sensors_to_add = []
all_fields = NORMAL_DEVICE_FIELDS
all_fields.update(DC_INPUT_FIELDS)
all_fields.update(ADDITIONAL_DEVICE_FIELDS)
for field_key, field_config in all_fields.items():
if bluetti_device.has_field(field_key):
if field_config.type == MqttFieldType.BOOL:
if field_config.setter is True and field_key in CONTROL_FIELDS:
sensors_to_add.append(
BluettiSwitch(
bluetti_device,
hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR],
device_info,
address,
field_key,
field_config.home_assistant_extra.get(CONF_NAME, ""),
entry.entry_id
)
)
async_add_entities(sensors_to_add)
class BluettiSwitch(CoordinatorEntity, SwitchEntity):
"""Bluetti universal switch."""
def __init__(
self,
bluetti_device: BluettiDevice,
coordinator: PollingCoordinator,
device_info: DeviceInfo,
address,
response_key: str,
name: str,
entry_id: str,
category: EntityCategory | None = None,
):
"""Init entity."""
super().__init__(coordinator)
self._bluetti_device = bluetti_device
e_name = f"{device_info.get('name')} {name}"
self._address = address
self._response_key = response_key
self._entry_id = entry_id
self._attr_device_info = device_info
self._attr_name = e_name
self._attr_available = False
self._attr_unique_id = get_unique_id(e_name)
self._attr_entity_category = category
self._attr_device_class = SwitchDeviceClass.OUTLET
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
_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 (switch.%s)", unique_id_loggable(self._attr_unique_id)
)
self._attr_available = False
return
response_data = self.coordinator.data.get(self._response_key)
if response_data is None:
self._attr_available = False
return
if not isinstance(response_data, bool):
_LOGGER.warning(
"Invalid response data type from coordinator (switch.%s): %s",
unique_id_loggable(self._attr_unique_id),
response_data,
)
self._attr_available = False
return
self._attr_available = True
self._attr_is_on = self.coordinator.data[self._response_key] is True
self.async_write_ha_state()
async def async_turn_on(self, **kwargs):
"""Turn the entity on."""
_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, 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", mac_loggable(self._address))
return
command = self._bluetti_device.build_setter_command(self._response_key, state)
# Wait until polling is done
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:
async with async_timeout.timeout(15):
await client.connect()
# Send command
await client.write_gatt_char(
BluetoothClient.WRITE_UUID, bytes(command)
)
# Wait until device has changed value, otherwise reading register might reset it
await asyncio.sleep(5)
except TimeoutError:
_LOGGER.error("Timed out for device %s", mac_loggable(self._address))
return None
except BleakError as err:
_LOGGER.error("Bleak error: %s", err)
return None
finally:
await client.disconnect()
await self.coordinator.async_request_refresh()
@@ -0,0 +1,16 @@
{
"options": {
"step": {
"init": {
"data": {
"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"
}
}
}
@@ -0,0 +1,16 @@
{
"options": {
"step": {
"init": {
"data": {
"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]