Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed818070c2 | ||
|
|
beb4e6b8fb | ||
|
|
7444097c60 | ||
|
|
0912fcbc49 | ||
|
|
80b03fc1d9 | ||
|
|
92c130b2d6 | ||
|
|
f8e382347e | ||
|
|
bab008b89c | ||
|
|
811501b382 | ||
|
|
90f66c8548 | ||
|
|
924eaa90b6 | ||
|
|
4f95fed85a | ||
|
|
332cf6dc28 | ||
|
|
cc7891ed6a | ||
|
|
12cd2719d2 | ||
|
|
e1d4446fb8 | ||
|
|
b7c705f224 | ||
|
|
a71f419676 | ||
|
|
7af1fb02c6 |
No files matched your search
@@ -22,3 +22,4 @@ Based on [bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt).
|
|||||||
|
|
||||||
### Available sensors:
|
### 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))
|
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.
|
||||||
@@ -6,20 +6,22 @@ import re
|
|||||||
|
|
||||||
from homeassistant.components import bluetooth
|
from homeassistant.components import bluetooth
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import CONF_ADDRESS, CONF_TYPE, Platform
|
from homeassistant.const import CONF_ADDRESS, CONF_TYPE, CONF_NAME, Platform
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity import DeviceInfo
|
from homeassistant.helpers.entity import DeviceInfo
|
||||||
from homeassistant.exceptions import ConfigEntryNotReady
|
from homeassistant.exceptions import ConfigEntryNotReady
|
||||||
|
|
||||||
from .const import DOMAIN, MANUFACTURER
|
from .const import DOMAIN, MANUFACTURER
|
||||||
|
from .coordinator import PollingCoordinator
|
||||||
|
|
||||||
PLATFORMS: [Platform] = [Platform.SENSOR]
|
PLATFORMS: [Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR]
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||||
"""Set up Bluetti Powerstation from a config entry."""
|
"""Set up Bluetti Powerstation from a config entry."""
|
||||||
|
|
||||||
address = entry.data.get(CONF_ADDRESS)
|
address = entry.data.get(CONF_ADDRESS)
|
||||||
|
device_name = entry.data.get(CONF_NAME)
|
||||||
|
|
||||||
if address is None:
|
if address is None:
|
||||||
return False
|
return False
|
||||||
@@ -27,6 +29,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
if not bluetooth.async_address_present(hass, address):
|
if not bluetooth.async_address_present(hass, address):
|
||||||
raise ConfigEntryNotReady("Bluetti device not present")
|
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)
|
||||||
|
|
||||||
# Setup platforms
|
# Setup platforms
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Bluetti BT sensors."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from homeassistant.components.binary_sensor import BinarySensorEntity
|
||||||
|
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.mqtt_client import (
|
||||||
|
NORMAL_DEVICE_FIELDS,
|
||||||
|
DC_INPUT_FIELDS,
|
||||||
|
MqttFieldType,
|
||||||
|
)
|
||||||
|
|
||||||
|
from . import device_info as dev_info, get_unique_id
|
||||||
|
from .const import DOMAIN, ADDITIONAL_DEVICE_FIELDS
|
||||||
|
from .coordinator import PollingCoordinator, DummyDevice
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def async_setup_entry(
|
||||||
|
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
||||||
|
) -> None:
|
||||||
|
"""Setup sensor 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 sensors 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:
|
||||||
|
category = None
|
||||||
|
if field_config.setter is True:
|
||||||
|
category = EntityCategory.DIAGNOSTIC
|
||||||
|
|
||||||
|
sensors_to_add.append(
|
||||||
|
BluettiBinarySensor(
|
||||||
|
hass.data[DOMAIN][entry.entry_id],
|
||||||
|
device_info,
|
||||||
|
address,
|
||||||
|
field_key,
|
||||||
|
field_config.home_assistant_extra.get(CONF_NAME, ""),
|
||||||
|
category=category,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async_add_entities(sensors_to_add)
|
||||||
|
|
||||||
|
|
||||||
|
class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
|
||||||
|
"""Bluetti universal binary sensor."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
coordinator: PollingCoordinator,
|
||||||
|
device_info: DeviceInfo,
|
||||||
|
address,
|
||||||
|
response_key: str,
|
||||||
|
name: str,
|
||||||
|
category: EntityCategory | None = None,
|
||||||
|
):
|
||||||
|
"""Init battery entity."""
|
||||||
|
super().__init__(coordinator)
|
||||||
|
|
||||||
|
e_name = f"{device_info.get('name')} {name}"
|
||||||
|
self._address = address
|
||||||
|
self._response_key = response_key
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _handle_coordinator_update(self) -> None:
|
||||||
|
"""Handle updated data from the coordinator."""
|
||||||
|
_LOGGER.debug("Updating state of %s", self._attr_unique_id)
|
||||||
|
if not isinstance(self.coordinator.data, dict):
|
||||||
|
_LOGGER.error(
|
||||||
|
"Invalid data from coordinator (sensor.%s)", 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 (sensor.%s): %s",
|
||||||
|
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()
|
||||||
@@ -1,7 +1,191 @@
|
|||||||
"""Constants for the Bluetti BT integration."""
|
"""Constants for the Bluetti BT integration."""
|
||||||
|
|
||||||
|
from bluetti_mqtt.mqtt_client import MqttFieldConfig, MqttFieldType
|
||||||
|
|
||||||
DOMAIN = "bluetti_bt"
|
DOMAIN = "bluetti_bt"
|
||||||
MANUFACTURER = "Bluetti"
|
MANUFACTURER = "Bluetti"
|
||||||
|
|
||||||
API_RESPONSE_BATTERY_RANGE_START = "battery_range_start"
|
CONF_OPTIONS = "options"
|
||||||
API_RESPONSE_BATTERY_RANGE_END = "battery_range_end"
|
|
||||||
|
DIAGNOSTIC_FIELDS = [
|
||||||
|
"max_ac_input_power",
|
||||||
|
"max_ac_input_current",
|
||||||
|
"max_ac_output_power",
|
||||||
|
"max_ac_output_current",
|
||||||
|
"bcu_version",
|
||||||
|
"safety_module_version",
|
||||||
|
"high_voltage_module_version",
|
||||||
|
]
|
||||||
|
|
||||||
|
ADDITIONAL_DEVICE_FIELDS = {
|
||||||
|
"max_ac_input_power": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "Max AC Input Power per Phase",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"max_ac_input_current": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "Max AC Input Current per Phase",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"max_ac_output_power": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "Max AC Output Power per Phase",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"max_ac_output_current": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "Max AC Output Current per Phase",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"bcu_version": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={"name": "BCU Version"},
|
||||||
|
),
|
||||||
|
"safety_module_version": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={"name": "Safety Module Version"},
|
||||||
|
),
|
||||||
|
"high_voltage_module_version": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={"name": "High Voltage Safety Module Version"},
|
||||||
|
),
|
||||||
|
"adl400_ac_input_voltage_phase1": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "ADL400 AC Input Voltage Phase 1",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"adl400_ac_input_voltage_phase2": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "ADL400 AC Input Voltage Phase 2",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"adl400_ac_input_voltage_phase3": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "ADL400 AC Input Voltage Phase 3",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_input_voltage_phase1": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Input Voltage Phase 1",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_input_voltage_phase2": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Input Voltage Phase 2",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_input_voltage_phase3": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Input Voltage Phase 3",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_output_voltage_phase1": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Output Voltage Phase 1",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_output_voltage_phase2": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Output Voltage Phase 2",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_output_voltage_phase3": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Output Voltage Phase 3",
|
||||||
|
"unit_of_measurement": "V",
|
||||||
|
"device_class": "voltage",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ac_output_frequency": MqttFieldConfig(
|
||||||
|
type=MqttFieldType.NUMERIC,
|
||||||
|
setter=False,
|
||||||
|
advanced=False,
|
||||||
|
home_assistant_extra={
|
||||||
|
"name": "AC Output Frequency",
|
||||||
|
"unit_of_measurement": "Hz",
|
||||||
|
"device_class": "frequency",
|
||||||
|
"state_class": "measurement",
|
||||||
|
"force_update": True,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
"""Coordinator for Bluetti integration."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from datetime import timedelta
|
||||||
|
import logging
|
||||||
|
from typing import cast
|
||||||
|
import async_timeout
|
||||||
|
|
||||||
|
from bleak import BleakClient, BleakError
|
||||||
|
|
||||||
|
from homeassistant.components import bluetooth
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.helpers.update_coordinator import (
|
||||||
|
DataUpdateCoordinator,
|
||||||
|
)
|
||||||
|
|
||||||
|
from bluetti_mqtt.bluetooth.client import BluetoothClient
|
||||||
|
from bluetti_mqtt.bluetooth import (
|
||||||
|
BadConnectionError,
|
||||||
|
ModbusError,
|
||||||
|
ParseError,
|
||||||
|
build_device,
|
||||||
|
)
|
||||||
|
from bluetti_mqtt.core.devices.bluetti_device import BluettiDevice
|
||||||
|
from bluetti_mqtt.core.commands import ReadHoldingRegisters
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DummyDevice(BluettiDevice):
|
||||||
|
"""Dummy device used to add more fields to existing devices.
|
||||||
|
|
||||||
|
Changes made here are only temporary and should also be
|
||||||
|
contributed to https://github.com/warhammerkid/bluetti_mqtt
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, device: BluettiDevice):
|
||||||
|
"""Init dummy device with real device."""
|
||||||
|
self.struct = device.struct
|
||||||
|
|
||||||
|
if device.type == "EP600":
|
||||||
|
self.struct.add_decimal_field("adl400_ac_input_voltage_phase1", 1229, 1)
|
||||||
|
self.struct.add_decimal_field("adl400_ac_input_voltage_phase2", 1237, 1)
|
||||||
|
self.struct.add_decimal_field("adl400_ac_input_voltage_phase3", 1245, 1)
|
||||||
|
self.struct.add_decimal_field("ac_input_frequency", 1300, 1)
|
||||||
|
self.struct.add_decimal_field("ac_input_voltage_phase1", 1314, 1)
|
||||||
|
self.struct.add_decimal_field("ac_input_voltage_phase2", 1320, 1)
|
||||||
|
self.struct.add_decimal_field("ac_input_voltage_phase3", 1326, 1)
|
||||||
|
self.struct.add_decimal_field("ac_output_frequency", 1500, 1)
|
||||||
|
self.struct.add_decimal_field("ac_output_voltage_phase1", 1511, 1)
|
||||||
|
self.struct.add_decimal_field("ac_output_voltage_phase2", 1518, 1)
|
||||||
|
self.struct.add_decimal_field("ac_output_voltage_phase3", 1525, 1)
|
||||||
|
|
||||||
|
super().__init__(device.address, device.type, device.sn)
|
||||||
|
self._parent = device
|
||||||
|
|
||||||
|
@property
|
||||||
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
if self.type == "EP600":
|
||||||
|
return [
|
||||||
|
ReadHoldingRegisters(100, 62),
|
||||||
|
ReadHoldingRegisters(1229, 19),
|
||||||
|
ReadHoldingRegisters(1300, 1),
|
||||||
|
ReadHoldingRegisters(1314, 13),
|
||||||
|
ReadHoldingRegisters(1500, 1),
|
||||||
|
ReadHoldingRegisters(1511, 15),
|
||||||
|
ReadHoldingRegisters(2022, 6),
|
||||||
|
ReadHoldingRegisters(2213, 4),
|
||||||
|
# Battery
|
||||||
|
ReadHoldingRegisters(6101, 7),
|
||||||
|
ReadHoldingRegisters(6175, 11),
|
||||||
|
]
|
||||||
|
|
||||||
|
return self._parent.polling_commands
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
return self._parent.pack_logging_commands
|
||||||
|
|
||||||
|
@property
|
||||||
|
def logging_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
return self._parent.logging_commands
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pack_logging_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
return self._parent.pack_logging_commands
|
||||||
|
|
||||||
|
@property
|
||||||
|
def writable_ranges(self) -> List[range]:
|
||||||
|
return self._parent.writable_ranges
|
||||||
|
|
||||||
|
|
||||||
|
class PollingCoordinator(DataUpdateCoordinator):
|
||||||
|
"""Polling coordinator."""
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant, address, device_name: str):
|
||||||
|
"""Initialize coordinator."""
|
||||||
|
super().__init__(
|
||||||
|
hass,
|
||||||
|
_LOGGER,
|
||||||
|
name="Bluetti polling coordinator",
|
||||||
|
update_interval=timedelta(seconds=20),
|
||||||
|
)
|
||||||
|
self._address = address
|
||||||
|
self.notify_future = None
|
||||||
|
self.current_command = None
|
||||||
|
self.notify_response = bytearray()
|
||||||
|
bluetti_device = build_device(address, device_name)
|
||||||
|
|
||||||
|
# Add or modify device fields
|
||||||
|
self.bluetti_device = DummyDevice(bluetti_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.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)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Polling
|
||||||
|
client = BleakClient(device)
|
||||||
|
parsed_data: dict = {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with async_timeout.timeout(15):
|
||||||
|
await client.connect()
|
||||||
|
|
||||||
|
await client.start_notify(
|
||||||
|
BluetoothClient.NOTIFY_UUID, self._notification_handler
|
||||||
|
)
|
||||||
|
|
||||||
|
for command in self.bluetti_device.polling_commands:
|
||||||
|
try:
|
||||||
|
# Prepare to make request
|
||||||
|
self.current_command = command
|
||||||
|
self.notify_future = self.hass.loop.create_future()
|
||||||
|
self.notify_response = bytearray()
|
||||||
|
|
||||||
|
# Make request
|
||||||
|
self.logger.debug("Requesting %s", command)
|
||||||
|
await client.write_gatt_char(
|
||||||
|
BluetoothClient.WRITE_UUID, bytes(command)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Wait for response
|
||||||
|
res = await asyncio.wait_for(
|
||||||
|
self.notify_future, timeout=BluetoothClient.RESPONSE_TIMEOUT
|
||||||
|
)
|
||||||
|
|
||||||
|
# Process data
|
||||||
|
self.logger.debug("Got %s bytes", len(res))
|
||||||
|
response = cast(bytes, res)
|
||||||
|
body = command.parse_response(response)
|
||||||
|
parsed = self.bluetti_device.parse(
|
||||||
|
command.starting_address, body
|
||||||
|
)
|
||||||
|
|
||||||
|
self.logger.debug("Parsed data: %s", parsed)
|
||||||
|
parsed_data.update(parsed)
|
||||||
|
|
||||||
|
except TimeoutError:
|
||||||
|
self.logger.error(
|
||||||
|
"Polling timed out (address: %s)", self._address
|
||||||
|
)
|
||||||
|
except ParseError:
|
||||||
|
self.logger.warning("Got a parse exception...")
|
||||||
|
except ModbusError as err:
|
||||||
|
self.logger.warning(
|
||||||
|
"Got an invalid request error for %s: %s",
|
||||||
|
command,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
except (BadConnectionError, BleakError) as err:
|
||||||
|
self.logger.warning(
|
||||||
|
"Needed to disconnect due to error: %s", err
|
||||||
|
)
|
||||||
|
except TimeoutError:
|
||||||
|
self.logger.error("Polling timed out for device %s", self._address)
|
||||||
|
return None
|
||||||
|
except BleakError as err:
|
||||||
|
self.logger.error("Bleak error: %s", err)
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
await client.disconnect()
|
||||||
|
|
||||||
|
# Pass data back to sensors
|
||||||
|
return parsed_data
|
||||||
|
|
||||||
|
def _notification_handler(self, _sender: int, data: bytearray):
|
||||||
|
"""Handle bt data."""
|
||||||
|
|
||||||
|
# Ignore notifications we don't expect
|
||||||
|
if not self.notify_future or self.notify_future.done():
|
||||||
|
return
|
||||||
|
|
||||||
|
# If something went wrong, we might get weird data.
|
||||||
|
if data == b"AT+NAME?\r" or data == b"AT+ADV?\r":
|
||||||
|
err = BadConnectionError("Got AT+ notification")
|
||||||
|
self.notify_future.set_exception(err)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Save data
|
||||||
|
self.notify_response.extend(data)
|
||||||
|
|
||||||
|
if len(self.notify_response) == self.current_command.response_size():
|
||||||
|
if self.current_command.is_valid_response(self.notify_response):
|
||||||
|
self.notify_future.set_result(self.notify_response)
|
||||||
|
else:
|
||||||
|
self.notify_future.set_exception(ParseError("Failed checksum"))
|
||||||
|
elif self.current_command.is_exception_response(self.notify_response):
|
||||||
|
# We got a MODBUS command exception
|
||||||
|
msg = f"MODBUS Exception {self.current_command}: {self.notify_response[2]}"
|
||||||
|
self.notify_future.set_exception(ModbusError(msg))
|
||||||
@@ -2,15 +2,9 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
|
||||||
from datetime import timedelta
|
|
||||||
import logging
|
import logging
|
||||||
from typing import cast
|
from decimal import Decimal
|
||||||
import async_timeout
|
|
||||||
|
|
||||||
from bleak import BleakClient, BleakError
|
|
||||||
|
|
||||||
from homeassistant.components import bluetooth
|
|
||||||
from homeassistant.components.sensor import SensorEntity, CONF_STATE_CLASS
|
from homeassistant.components.sensor import SensorEntity, CONF_STATE_CLASS
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.core import HomeAssistant, callback
|
from homeassistant.core import HomeAssistant, callback
|
||||||
@@ -25,23 +19,18 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
|||||||
from homeassistant.helpers.entity import DeviceInfo
|
from homeassistant.helpers.entity import DeviceInfo
|
||||||
from homeassistant.helpers.update_coordinator import (
|
from homeassistant.helpers.update_coordinator import (
|
||||||
CoordinatorEntity,
|
CoordinatorEntity,
|
||||||
DataUpdateCoordinator,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
from bluetti_mqtt.bluetooth.client import BluetoothClient
|
from bluetti_mqtt.bluetooth import build_device
|
||||||
from bluetti_mqtt.bluetooth import (
|
from bluetti_mqtt.mqtt_client import (
|
||||||
BadConnectionError,
|
NORMAL_DEVICE_FIELDS,
|
||||||
ModbusError,
|
DC_INPUT_FIELDS,
|
||||||
ParseError,
|
MqttFieldType,
|
||||||
build_device,
|
|
||||||
)
|
)
|
||||||
from bluetti_mqtt.mqtt_client import NORMAL_DEVICE_FIELDS
|
|
||||||
|
|
||||||
from . import device_info as dev_info, get_unique_id
|
from . import device_info as dev_info, get_unique_id
|
||||||
from .const import (
|
from .const import DOMAIN, CONF_OPTIONS, DIAGNOSTIC_FIELDS, ADDITIONAL_DEVICE_FIELDS
|
||||||
API_RESPONSE_BATTERY_RANGE_START,
|
from .coordinator import PollingCoordinator, DummyDevice
|
||||||
API_RESPONSE_BATTERY_RANGE_END,
|
|
||||||
)
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -56,171 +45,53 @@ async def async_setup_entry(
|
|||||||
if address is None:
|
if address is None:
|
||||||
_LOGGER.error("Device has no address")
|
_LOGGER.error("Device has no address")
|
||||||
|
|
||||||
# Create coordinator for polling
|
|
||||||
coordinator = PollingCoordinator(hass, address, device_name)
|
|
||||||
await coordinator.async_config_entry_first_refresh()
|
|
||||||
|
|
||||||
# Generate device info
|
# Generate device info
|
||||||
_LOGGER.info("Creating sensors for device with address %s", address)
|
_LOGGER.info("Creating sensors for device with address %s", address)
|
||||||
device_info = dev_info(entry)
|
device_info = dev_info(entry)
|
||||||
|
|
||||||
# Add sensors according to device_info
|
# Add sensors according to device_info
|
||||||
bluetti_device = build_device(address, device_name)
|
bluetti_device = build_device(address, device_name)
|
||||||
|
bluetti_device = DummyDevice(bluetti_device)
|
||||||
|
|
||||||
sensors_to_add = []
|
sensors_to_add = []
|
||||||
for field_key, field_config in NORMAL_DEVICE_FIELDS.items():
|
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 bluetti_device.has_field(field_key):
|
||||||
category = None
|
category = None
|
||||||
|
if field_config.setter is True or field_key in DIAGNOSTIC_FIELDS:
|
||||||
if field_key in (
|
|
||||||
API_RESPONSE_BATTERY_RANGE_START,
|
|
||||||
API_RESPONSE_BATTERY_RANGE_END,
|
|
||||||
):
|
|
||||||
category = EntityCategory.DIAGNOSTIC
|
category = EntityCategory.DIAGNOSTIC
|
||||||
|
if field_config.type == MqttFieldType.NUMERIC:
|
||||||
sensors_to_add.append(
|
sensors_to_add.append(
|
||||||
BluettiSensor(
|
BluettiSensor(
|
||||||
coordinator,
|
hass.data[DOMAIN][entry.entry_id],
|
||||||
device_info,
|
device_info,
|
||||||
address,
|
address,
|
||||||
field_key,
|
field_key,
|
||||||
field_config.home_assistant_extra.get(CONF_NAME, ""),
|
field_config.home_assistant_extra.get(CONF_NAME, ""),
|
||||||
field_config.home_assistant_extra.get(CONF_UNIT_OF_MEASUREMENT, ""),
|
field_config.home_assistant_extra.get(CONF_UNIT_OF_MEASUREMENT),
|
||||||
field_config.home_assistant_extra.get(CONF_DEVICE_CLASS, ""),
|
field_config.home_assistant_extra.get(CONF_DEVICE_CLASS),
|
||||||
field_config.home_assistant_extra.get(CONF_STATE_CLASS, ""),
|
field_config.home_assistant_extra.get(CONF_STATE_CLASS),
|
||||||
category,
|
category=category,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
elif field_config.type == MqttFieldType.ENUM:
|
||||||
|
sensors_to_add.append(
|
||||||
|
BluettiSensor(
|
||||||
|
hass.data[DOMAIN][entry.entry_id],
|
||||||
|
device_info,
|
||||||
|
address,
|
||||||
|
field_key,
|
||||||
|
field_config.home_assistant_extra.get(CONF_NAME, ""),
|
||||||
|
options=field_config.home_assistant_extra.get(CONF_OPTIONS),
|
||||||
|
category=category,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
async_add_entities(sensors_to_add)
|
async_add_entities(sensors_to_add)
|
||||||
|
|
||||||
|
|
||||||
class PollingCoordinator(DataUpdateCoordinator):
|
|
||||||
"""Polling coordinator."""
|
|
||||||
|
|
||||||
def __init__(self, hass: HomeAssistant, address, device_name: str):
|
|
||||||
"""Initialize coordinator."""
|
|
||||||
super().__init__(
|
|
||||||
hass,
|
|
||||||
_LOGGER,
|
|
||||||
name="Bluetti polling coordinator",
|
|
||||||
update_interval=timedelta(seconds=20),
|
|
||||||
)
|
|
||||||
self._address = address
|
|
||||||
self.notify_future = None
|
|
||||||
self.current_command = None
|
|
||||||
self.notify_response = bytearray()
|
|
||||||
self.bluetti_device = build_device(address, device_name)
|
|
||||||
|
|
||||||
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.logger.debug("Polling data")
|
|
||||||
|
|
||||||
device = bluetooth.async_ble_device_from_address(self.hass, self._address)
|
|
||||||
if device is None:
|
|
||||||
self.logger.error("Device not available")
|
|
||||||
return None
|
|
||||||
|
|
||||||
if self.bluetti_device is None:
|
|
||||||
self.logger.error("Device type not found")
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Polling
|
|
||||||
client = BleakClient(device)
|
|
||||||
parsed_data: dict = {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
async with async_timeout.timeout(15):
|
|
||||||
await client.connect()
|
|
||||||
|
|
||||||
await client.start_notify(
|
|
||||||
BluetoothClient.NOTIFY_UUID, self._notification_handler
|
|
||||||
)
|
|
||||||
|
|
||||||
for command in self.bluetti_device.polling_commands:
|
|
||||||
try:
|
|
||||||
# Prepare to make request
|
|
||||||
self.current_command = command
|
|
||||||
self.notify_future = self.hass.loop.create_future()
|
|
||||||
self.notify_response = bytearray()
|
|
||||||
|
|
||||||
# Make request
|
|
||||||
self.logger.debug("Requesting %s", command)
|
|
||||||
await client.write_gatt_char(
|
|
||||||
BluetoothClient.WRITE_UUID, bytes(command)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Wait for response
|
|
||||||
res = await asyncio.wait_for(
|
|
||||||
self.notify_future, timeout=BluetoothClient.RESPONSE_TIMEOUT
|
|
||||||
)
|
|
||||||
|
|
||||||
# Process data
|
|
||||||
self.logger.debug("Got %s bytes", len(res))
|
|
||||||
response = cast(bytes, res)
|
|
||||||
body = command.parse_response(response)
|
|
||||||
parsed = self.bluetti_device.parse(
|
|
||||||
command.starting_address, body
|
|
||||||
)
|
|
||||||
|
|
||||||
self.logger.warning("Parsed data: %s", parsed)
|
|
||||||
parsed_data.update(parsed)
|
|
||||||
|
|
||||||
except TimeoutError:
|
|
||||||
self.logger.error("Polling timed out")
|
|
||||||
except ParseError:
|
|
||||||
self.logger.debug("Got a parse exception...")
|
|
||||||
except ModbusError as err:
|
|
||||||
self.logger.debug(
|
|
||||||
"Got an invalid request error for %s: %s",
|
|
||||||
command,
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
except (BadConnectionError, BleakError) as err:
|
|
||||||
self.logger.debug("Needed to disconnect due to error: %s", err)
|
|
||||||
except TimeoutError:
|
|
||||||
self.logger.error("Polling timed out")
|
|
||||||
return None
|
|
||||||
except BleakError as err:
|
|
||||||
self.logger.error("Bleak error: %s", err)
|
|
||||||
return None
|
|
||||||
finally:
|
|
||||||
await client.disconnect()
|
|
||||||
|
|
||||||
# Pass data back to sensors
|
|
||||||
return parsed_data
|
|
||||||
|
|
||||||
def _notification_handler(self, _sender: int, data: bytearray):
|
|
||||||
"""Handle bt data."""
|
|
||||||
|
|
||||||
# Ignore notifications we don't expect
|
|
||||||
if not self.notify_future or self.notify_future.done():
|
|
||||||
return
|
|
||||||
|
|
||||||
# If something went wrong, we might get weird data.
|
|
||||||
if data == b"AT+NAME?\r" or data == b"AT+ADV?\r":
|
|
||||||
err = BadConnectionError("Got AT+ notification")
|
|
||||||
self.notify_future.set_exception(err)
|
|
||||||
return
|
|
||||||
|
|
||||||
# Save data
|
|
||||||
self.notify_response.extend(data)
|
|
||||||
|
|
||||||
if len(self.notify_response) == self.current_command.response_size():
|
|
||||||
if self.current_command.is_valid_response(self.notify_response):
|
|
||||||
self.notify_future.set_result(self.notify_response)
|
|
||||||
else:
|
|
||||||
self.notify_future.set_exception(ParseError("Failed checksum"))
|
|
||||||
elif self.current_command.is_exception_response(self.notify_response):
|
|
||||||
# We got a MODBUS command exception
|
|
||||||
msg = f"MODBUS Exception {self.current_command}: {self.notify_response[2]}"
|
|
||||||
self.notify_future.set_exception(ModbusError(msg))
|
|
||||||
|
|
||||||
|
|
||||||
class BluettiSensor(CoordinatorEntity, SensorEntity):
|
class BluettiSensor(CoordinatorEntity, SensorEntity):
|
||||||
"""Bluetti universal sensor."""
|
"""Bluetti universal sensor."""
|
||||||
|
|
||||||
@@ -231,10 +102,11 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
address,
|
address,
|
||||||
response_key: str,
|
response_key: str,
|
||||||
name: str,
|
name: str,
|
||||||
unit_of_measurement: str,
|
unit_of_measurement: str | None = None,
|
||||||
device_class: str,
|
device_class: str | None = None,
|
||||||
state_class: str,
|
state_class: str | None = None,
|
||||||
category: EntityCategory | None = None,
|
category: EntityCategory | None = None,
|
||||||
|
options: list[str] | None = None,
|
||||||
):
|
):
|
||||||
"""Init battery entity."""
|
"""Init battery entity."""
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
@@ -245,24 +117,56 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
|
|
||||||
self._attr_device_info = device_info
|
self._attr_device_info = device_info
|
||||||
self._attr_name = e_name
|
self._attr_name = e_name
|
||||||
|
self._attr_available = False
|
||||||
self._attr_unique_id = get_unique_id(e_name)
|
self._attr_unique_id = get_unique_id(e_name)
|
||||||
self._attr_native_unit_of_measurement = unit_of_measurement
|
self._attr_native_unit_of_measurement = unit_of_measurement
|
||||||
self._attr_device_class = device_class
|
self._attr_device_class = device_class
|
||||||
self._attr_state_class = state_class
|
self._attr_state_class = state_class
|
||||||
self._attr_entity_category = category
|
self._attr_entity_category = category
|
||||||
|
self._options = options
|
||||||
@property
|
|
||||||
def available(self) -> bool:
|
|
||||||
if self._address is None:
|
|
||||||
return False
|
|
||||||
return bluetooth.async_address_present(self.hass, self._address)
|
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
def _handle_coordinator_update(self) -> None:
|
def _handle_coordinator_update(self) -> None:
|
||||||
"""Handle updated data from the coordinator."""
|
"""Handle updated data from the coordinator."""
|
||||||
_LOGGER.debug("Updating state of %s", self._attr_unique_id)
|
_LOGGER.debug("Updating state of %s", self._attr_unique_id)
|
||||||
if not isinstance(self.coordinator.data, dict):
|
if not isinstance(self.coordinator.data, dict):
|
||||||
_LOGGER.error("Invalid data from coordinator")
|
_LOGGER.error(
|
||||||
|
"Invalid data from coordinator (sensor.%s)", self._attr_unique_id
|
||||||
|
)
|
||||||
|
self._attr_available = False
|
||||||
return
|
return
|
||||||
self._attr_native_value = self.coordinator.data[self._response_key]
|
|
||||||
|
response_data = self.coordinator.data.get(self._response_key)
|
||||||
|
if response_data is None:
|
||||||
|
self._attr_available = False
|
||||||
|
return
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(response_data, int)
|
||||||
|
and not isinstance(response_data, float)
|
||||||
|
and not isinstance(response_data, complex)
|
||||||
|
and not isinstance(response_data, Decimal)
|
||||||
|
):
|
||||||
|
_LOGGER.warning(
|
||||||
|
"Invalid response data type from coordinator (sensor.%s): %s has type %s",
|
||||||
|
self._attr_unique_id,
|
||||||
|
response_data,
|
||||||
|
type(response_data),
|
||||||
|
)
|
||||||
|
self._attr_available = False
|
||||||
|
return
|
||||||
|
|
||||||
|
self._attr_available = True
|
||||||
|
|
||||||
|
# Different for enum and numeric
|
||||||
|
if (
|
||||||
|
self._options is not None
|
||||||
|
and isinstance(response_data, int)
|
||||||
|
and response_data < len(self._options)
|
||||||
|
):
|
||||||
|
# Enum
|
||||||
|
self._attr_native_value = self._options[response_data]
|
||||||
|
else:
|
||||||
|
# Numeric
|
||||||
|
self._attr_native_value = response_data
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
Reference in new issue
Block a user