Compare commits

..
34 Commits
Author SHA1 Message Date
Patrick762 528378ed9f Merge pull request #19 from Patrick762/dev
Version 0.0.11
2024-01-05 20:58:12 +01:00
Patrick762 b7c162aaef updated readme 2024-01-04 16:02:49 +01:00
Patrick762 dda0d475f4 stop notifier before disconnect 2024-01-04 15:39:02 +01:00
Patrick762 98f004dad1 revert to previous version number 2024-01-04 15:16:15 +01:00
Patrick762 515a06dc3a added more config options 2024-01-04 15:14:36 +01:00
Patrick762 14f2219b94 updated version number, added logging 2023-12-17 21:08:28 +01:00
Patrick762 4710a8183f replaced deploy script 2023-12-17 16:55:41 +01:00
Patrick762 186d73ace1 Merge pull request #24 from ViPeR5000/patch-1
Create pt.json
2023-12-17 16:53:58 +01:00
Rui Melo 7c211cde6f Create pt.json 2023-12-13 21:11:54 +00:00
Patrick762 4f99b7d746 Added install instructions for integration 2023-12-11 19:55:44 +01:00
Patrick762 70d7403aec Added stale bot action 2023-12-10 16:50:47 +01:00
Patrick762 33fe91c2d2 added check if packs available 2023-09-23 19:45:02 +02:00
Patrick762 7904a07e7f added ep600 dc input, prevent pack polling 2023-09-23 17:52:18 +02:00
Patrick762 18e48092c0 Merge pull request #15 from SupaFlav/dev
Add battery pack percent & voltage
2023-09-23 15:47:55 +02:00
Patrick762 792da76a04 Merge pull request #18 from Patrick762/Patrick762-patch-1
Update README.md
2023-09-23 15:26:25 +02:00
Patrick762 107ac9f0c8 Update README.md 2023-09-23 15:25:42 +02:00
SupaFlav 3d8cf4b98f Add 5x reconnect attempts on poll 2023-09-08 19:56:12 -04:00
SupaFlav c3afdcfe89 Allow switches with persistent_conn and add mutex to guard polling 2023-09-03 23:33:26 -04:00
SupaFlav d38c30011c return empty bytes object vs None on exception 2023-09-01 09:51:57 -04:00
SupaFlav 32cfc34c37 refactor send command & return response within new func 2023-08-31 23:42:00 -04:00
SupaFlav 7c25cbbe27 remove commentary 2023-08-30 18:13:51 -04:00
SupaFlav 57d0969701 Merge pull request #1 from Patrick762/dev
Pull latest from upstream
2023-08-30 15:42:27 -04:00
SupaFlav b8a73e0ab9 add polling for battery pack voltage & percent 2023-08-30 15:34:22 -04:00
Patrick762 39c75b0f75 update version number 2023-08-30 21:02:39 +02:00
Patrick762 3dc1cff551 Merge pull request #14 from SupaFlav/dev
Remove redundant connection attempt & don't process callback data on dead connection with persistent_conn active
2023-08-30 20:58:58 +02:00
SupaFlav 296c9cbfd3 Ensure this only applies to persistent connections 2023-08-28 15:33:45 -04:00
SupaFlav 0cadbb9931 Remove extra connection attempt, rm callback debug login when not connected 2023-08-28 15:03:43 -04:00
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
16 changed files with 465 additions and 147 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
name: Close inactive issues
on:
schedule:
- cron: "30 1 * * *"
jobs:
close-issues:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
days-before-issue-stale: 30
days-before-issue-close: 14
stale-issue-label: "stale"
stale-issue-message: "This issue is stale because it has been open for 30 days with no activity."
close-issue-message: "This issue was closed because it has been inactive for 14 days since being marked as stale."
days-before-pr-stale: -1
days-before-pr-close: -1
repo-token: ${{ secrets.GITHUB_TOKEN }}
+8 -5
View File
@@ -1,14 +1,18 @@
# hassio-bluetti-bt # hassio-bluetti-bt
[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg)](https://github.com/hacs/integration) [![hacs_badge](https://img.shields.io/badge/HACS-Default-41BDF5.svg)](https://github.com/hacs/integration)
[![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) [![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) [![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 Bluetti Integration for Home Assistant
Based on [bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt). Based on [bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt).
## Installation
To install this integration, you first need [HACS](https://hacs.xyz/) installed.
After the installation, you can use this button to install the integration:
[![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=Patrick762&repository=hassio-bluetti-bt&category=integration)
### Supported devices: ### Supported devices:
(based on [supported devices of bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt/tree/main/bluetti_mqtt/core/devices)) (based on [supported devices of bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt/tree/main/bluetti_mqtt/core/devices))
@@ -22,8 +26,7 @@ Based on [bluetti_mqtt](https://github.com/warhammerkid/bluetti_mqtt).
- EP600 (tested) - EP600 (tested)
### 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.
### Available controls: ### Available controls:
If enabled in the Integration options (you need to reload the integration if you change this option): If enabled in the Integration options (you need to reload the integration if you change this option):
+16 -2
View File
@@ -12,7 +12,17 @@ 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 DATA_COORDINATOR, DOMAIN, MANUFACTURER, CONF_USE_CONTROLS, DATA_POLLING_RUNNING from .const import (
CONF_MAX_RETRIES,
CONF_PERSISTENT_CONN,
CONF_POLLING_INTERVAL,
CONF_POLLING_TIMEOUT,
CONF_USE_CONTROLS,
DATA_COORDINATOR,
DATA_POLLING_RUNNING,
DOMAIN,
MANUFACTURER,
)
from .coordinator import PollingCoordinator from .coordinator import PollingCoordinator
PLATFORMS: [Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR] PLATFORMS: [Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR]
@@ -25,6 +35,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.data.get(CONF_ADDRESS) address = entry.data.get(CONF_ADDRESS)
device_name = entry.data.get(CONF_NAME) device_name = entry.data.get(CONF_NAME)
use_controls = entry.data.get(CONF_USE_CONTROLS) 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)
polling_timeout = entry.data.get(CONF_POLLING_TIMEOUT, 45)
max_retries = entry.data.get(CONF_MAX_RETRIES, 5)
if address is None: if address is None:
return False return False
@@ -38,7 +52,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data[DOMAIN][entry.entry_id].setdefault(DATA_POLLING_RUNNING, False) hass.data[DOMAIN][entry.entry_id].setdefault(DATA_POLLING_RUNNING, False)
# Create coordinator for polling # Create coordinator for polling
coordinator = PollingCoordinator(hass, address, device_name) coordinator = PollingCoordinator(hass, address, device_name, polling_interval, persistent_conn, polling_timeout, max_retries)
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][entry.entry_id].setdefault(DATA_COORDINATOR, coordinator) hass.data[DOMAIN][entry.entry_id].setdefault(DATA_COORDINATOR, coordinator)
+12 -7
View File
@@ -28,6 +28,7 @@ from bluetti_mqtt.mqtt_client import (
from . import device_info as dev_info, get_unique_id from . import device_info as dev_info, get_unique_id
from .const import DATA_COORDINATOR, DOMAIN, ADDITIONAL_DEVICE_FIELDS from .const import DATA_COORDINATOR, DOMAIN, ADDITIONAL_DEVICE_FIELDS
from .coordinator import PollingCoordinator, DummyDevice from .coordinator import PollingCoordinator, DummyDevice
from .utils import unique_id_loggable
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -35,7 +36,7 @@ _LOGGER = logging.getLogger(__name__)
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: ) -> None:
"""Setup sensor entities.""" """Setup binary_sensor entities."""
device_name = entry.data.get(CONF_NAME) device_name = entry.data.get(CONF_NAME)
address = entry.data.get(CONF_ADDRESS) address = entry.data.get(CONF_ADDRESS)
@@ -43,7 +44,7 @@ async def async_setup_entry(
_LOGGER.error("Device has no address") _LOGGER.error("Device has no address")
# Generate device info # 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) device_info = dev_info(entry)
# Add sensors according to device_info # Add sensors according to device_info
@@ -103,10 +104,14 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
@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)
if self.coordinator.persistent_conn and not self.coordinator.client.is_connected:
return
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
if not isinstance(self.coordinator.data, dict): if not isinstance(self.coordinator.data, dict):
_LOGGER.error( _LOGGER.debug(
"Invalid data from coordinator (sensor.%s)", self._attr_unique_id "Invalid data from coordinator (binary_sensor.%s)", unique_id_loggable(self._attr_unique_id)
) )
self._attr_available = False self._attr_available = False
return return
@@ -118,8 +123,8 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
if not isinstance(response_data, bool): if not isinstance(response_data, bool):
_LOGGER.warning( _LOGGER.warning(
"Invalid response data type from coordinator (sensor.%s): %s", "Invalid response data type from coordinator (binary_sensor.%s): %s",
self._attr_unique_id, unique_id_loggable(self._attr_unique_id),
response_data, response_data,
) )
self._attr_available = False self._attr_available = False
+45 -1
View File
@@ -17,7 +17,14 @@ from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import selector from homeassistant.helpers import selector
from . import get_type_by_bt_name from . import get_type_by_bt_name
from .const import DOMAIN, CONF_USE_CONTROLS from .const import (
CONF_MAX_RETRIES,
CONF_PERSISTENT_CONN,
CONF_POLLING_INTERVAL,
CONF_POLLING_TIMEOUT,
CONF_USE_CONTROLS,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -108,12 +115,29 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
) -> FlowResult: ) -> FlowResult:
"""Manage the options.""" """Manage the options."""
if user_input is not None: if user_input is not None:
# Validate update interval
if user_input[CONF_POLLING_INTERVAL] < 5:
return self.async_abort(reason="invalid_interval")
# Validate update timeout
if user_input[CONF_POLLING_TIMEOUT] < 1:
return self.async_abort(reason="invalid_timeout")
# Validate max retries
if user_input[CONF_MAX_RETRIES] < 1:
return self.async_abort(reason="invalid_retries")
changed = self.hass.config_entries.async_update_entry( changed = self.hass.config_entries.async_update_entry(
self.config_entry, self.config_entry,
data={ data={
**self.config_entry.data, **self.config_entry.data,
**{ **{
CONF_USE_CONTROLS: user_input[CONF_USE_CONTROLS], CONF_USE_CONTROLS: user_input[CONF_USE_CONTROLS],
CONF_PERSISTENT_CONN: user_input[CONF_PERSISTENT_CONN],
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
CONF_POLLING_TIMEOUT: user_input[CONF_POLLING_TIMEOUT],
CONF_MAX_RETRIES: user_input[CONF_MAX_RETRIES],
}, },
}, },
) )
@@ -126,6 +150,10 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
title="", title="",
data={ data={
CONF_USE_CONTROLS: user_input[CONF_USE_CONTROLS], CONF_USE_CONTROLS: user_input[CONF_USE_CONTROLS],
CONF_PERSISTENT_CONN: user_input[CONF_PERSISTENT_CONN],
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
CONF_POLLING_TIMEOUT: user_input[CONF_POLLING_TIMEOUT],
CONF_MAX_RETRIES: user_input[CONF_MAX_RETRIES],
}, },
) )
@@ -137,6 +165,22 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
CONF_USE_CONTROLS, CONF_USE_CONTROLS,
default=self.config_entry.data.get(CONF_USE_CONTROLS, False), default=self.config_entry.data.get(CONF_USE_CONTROLS, False),
): selector.BooleanSelector(), ): 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,
vol.Required(
CONF_POLLING_TIMEOUT,
default=self.config_entry.data.get(CONF_POLLING_TIMEOUT, 45),
): int,
vol.Required(
CONF_MAX_RETRIES,
default=self.config_entry.data.get(CONF_MAX_RETRIES, 5),
): int,
} }
), ),
) )
+76
View File
@@ -7,6 +7,10 @@ MANUFACTURER = "Bluetti"
CONF_OPTIONS = "options" CONF_OPTIONS = "options"
CONF_USE_CONTROLS = "use_controls" CONF_USE_CONTROLS = "use_controls"
CONF_PERSISTENT_CONN = "persistent_conn"
CONF_POLLING_INTERVAL = "polling_interval"
CONF_POLLING_TIMEOUT = "polling_timeout"
CONF_MAX_RETRIES = "max_retries"
DATA_COORDINATOR = "coordinator" DATA_COORDINATOR = "coordinator"
DATA_POLLING_RUNNING = "polling_running" DATA_POLLING_RUNNING = "polling_running"
@@ -77,6 +81,78 @@ ADDITIONAL_DEVICE_FIELDS = {
advanced=False, advanced=False,
home_assistant_extra={"name": "High Voltage Safety Module Version"}, home_assistant_extra={"name": "High Voltage Safety Module Version"},
), ),
'pv_input_power1': MqttFieldConfig(
type=MqttFieldType.NUMERIC,
setter=False,
advanced=False,
home_assistant_extra={
"name": "Solar Input Power 1",
"unit_of_measurement": "W",
"device_class": "power",
"state_class": "measurement",
"force_update": True,
},
),
'pv_input_voltage1': MqttFieldConfig(
type=MqttFieldType.NUMERIC,
setter=False,
advanced=False,
home_assistant_extra={
"name": "Solar Input Voltage 1",
"unit_of_measurement": "V",
"device_class": "voltage",
"state_class": "measurement",
"force_update": True,
},
),
'pv_input_current1': MqttFieldConfig(
type=MqttFieldType.NUMERIC,
setter=False,
advanced=False,
home_assistant_extra={
"name": "Solar Input Current 1",
"unit_of_measurement": "A",
"device_class": "current",
"state_class": "measurement",
"force_update": True,
},
),
'pv_input_power2': MqttFieldConfig(
type=MqttFieldType.NUMERIC,
setter=False,
advanced=False,
home_assistant_extra={
"name": "Solar Input Power 2",
"unit_of_measurement": "W",
"device_class": "power",
"state_class": "measurement",
"force_update": True,
},
),
'pv_input_voltage2': MqttFieldConfig(
type=MqttFieldType.NUMERIC,
setter=False,
advanced=False,
home_assistant_extra={
"name": "Solar Input Voltage 2",
"unit_of_measurement": "V",
"device_class": "voltage",
"state_class": "measurement",
"force_update": True,
},
),
'pv_input_current2': MqttFieldConfig(
type=MqttFieldType.NUMERIC,
setter=False,
advanced=False,
home_assistant_extra={
"name": "Solar Input Current 2",
"unit_of_measurement": "A",
"device_class": "current",
"state_class": "measurement",
"force_update": True,
},
),
"adl400_ac_input_power_phase1": MqttFieldConfig( "adl400_ac_input_power_phase1": MqttFieldConfig(
type=MqttFieldType.NUMERIC, type=MqttFieldType.NUMERIC,
setter=False, setter=False,
+166 -86
View File
@@ -27,6 +27,7 @@ from bluetti_mqtt.core.devices.bluetti_device import BluettiDevice
from bluetti_mqtt.core.commands import ReadHoldingRegisters from bluetti_mqtt.core.commands import ReadHoldingRegisters
from .const import DATA_POLLING_RUNNING, DOMAIN from .const import DATA_POLLING_RUNNING, DOMAIN
from .utils import mac_loggable
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -43,6 +44,13 @@ class DummyDevice(BluettiDevice):
self.struct = device.struct self.struct = device.struct
if device.type == "EP600": if device.type == "EP600":
# DC Solar Input (copied from PR https://github.com/warhammerkid/bluetti_mqtt/pull/87 by KM011092)
self.struct.add_uint_field('pv_input_power1', 1212) # MPP 1 in - value * 0.1
#self.struct.add_uint_field('pv_input_voltage1', 1213) # MPP 1 in - value * 0.1
#self.struct.add_uint_field('pv_input_current1', 1214) # MPP 1 in
self.struct.add_uint_field('pv_input_power2', 1220) # MPP 2 in - value * 0.1
#self.struct.add_uint_field('pv_input_voltage2', 1221) # MPP 2 in - value * 0.1
#self.struct.add_uint_field('pv_input_current2', 1222) # MPP 2 in
# ADL400 Smart Meter for AC Solar # ADL400 Smart Meter for AC Solar
self.struct.add_uint_field("adl400_ac_input_power_phase1", 1228) self.struct.add_uint_field("adl400_ac_input_power_phase1", 1228)
self.struct.add_uint_field("adl400_ac_input_power_phase2", 1236) self.struct.add_uint_field("adl400_ac_input_power_phase2", 1236)
@@ -72,13 +80,14 @@ class DummyDevice(BluettiDevice):
self.struct.add_decimal_field("ac_output_current_phase1", 1512, 1) self.struct.add_decimal_field("ac_output_current_phase1", 1512, 1)
self.struct.add_decimal_field("ac_output_current_phase2", 1519, 1) self.struct.add_decimal_field("ac_output_current_phase2", 1519, 1)
self.struct.add_decimal_field("ac_output_current_phase3", 1526, 1) self.struct.add_decimal_field("ac_output_current_phase3", 1526, 1)
# Testing
# for i in range(0, 10):
# self.struct.add_decimal_field("testing"+str(i), 1520+i, 1)
super().__init__(device.address, device.type, device.sn) super().__init__(device.address, device.type, device.sn)
self._parent = device self._parent = device
@property
def pack_num_max(self):
return self._parent.pack_num_max
@property @property
def polling_commands(self) -> List[ReadHoldingRegisters]: def polling_commands(self) -> List[ReadHoldingRegisters]:
if self.type == "EP600": if self.type == "EP600":
@@ -89,29 +98,19 @@ class DummyDevice(BluettiDevice):
ReadHoldingRegisters(1500, 27), ReadHoldingRegisters(1500, 27),
ReadHoldingRegisters(2022, 6), ReadHoldingRegisters(2022, 6),
ReadHoldingRegisters(2213, 4), ReadHoldingRegisters(2213, 4),
ReadHoldingRegisters(1212, 11),
# Battery # Battery
ReadHoldingRegisters(6101, 7), ReadHoldingRegisters(6101, 7),
ReadHoldingRegisters(6175, 11), ReadHoldingRegisters(6175, 11),
# Testing
# ReadHoldingRegisters(100, 62),
# ReadHoldingRegisters(1100, 51),
# ReadHoldingRegisters(1200, 80),
# ReadHoldingRegisters(1300, 31),
# ReadHoldingRegisters(1400, 48),
# ReadHoldingRegisters(1500, 30),
# ReadHoldingRegisters(2000, 89),
# ReadHoldingRegisters(2200, 41),
# ReadHoldingRegisters(2300, 36),
# ReadHoldingRegisters(6000, 32),
# ReadHoldingRegisters(6100, 100),
# ReadHoldingRegisters(6300, 100),
] ]
return self._parent.polling_commands return self._parent.polling_commands
@property @property
def pack_polling_commands(self) -> List[ReadHoldingRegisters]: def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
return self._parent.pack_logging_commands if self.type == "EP600":
return []
return self._parent.pack_polling_commands
@property @property
def logging_commands(self) -> List[ReadHoldingRegisters]: def logging_commands(self) -> List[ReadHoldingRegisters]:
@@ -129,23 +128,47 @@ class DummyDevice(BluettiDevice):
class PollingCoordinator(DataUpdateCoordinator): class PollingCoordinator(DataUpdateCoordinator):
"""Polling coordinator.""" """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,
polling_timeout: int,
max_retries: int,
):
"""Initialize coordinator.""" """Initialize coordinator."""
super().__init__( super().__init__(
hass, hass,
_LOGGER, _LOGGER,
name="Bluetti polling coordinator", name="Bluetti polling coordinator",
update_interval=timedelta(seconds=20), update_interval=timedelta(seconds=polling_interval),
) )
self._address = address self._address = address
self.has_notifier = False
self.notify_future = None self.notify_future = None
self.current_command = None self.current_command = None
self.notify_response = bytearray() self.notify_response = bytearray()
bluetti_device = build_device(address, device_name) bluetti_device = build_device(address, device_name)
self.persistent_conn = persistent_conn
self.polling_timeout = polling_timeout
self.max_retries = max_retries
# Add or modify device fields # Add or modify device fields
self.bluetti_device = DummyDevice(bluetti_device) self.bluetti_device = DummyDevice(bluetti_device)
# Create client
self.logger.debug("Creating 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)
# polling mutex to guard against switches
self.polling_lock = asyncio.Lock()
async def _async_update_data(self): async def _async_update_data(self):
"""Fetch data from API endpoint. """Fetch data from API endpoint.
@@ -156,91 +179,148 @@ class PollingCoordinator(DataUpdateCoordinator):
self.logger.debug("Polling 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: 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 return None
# Polling
client = BleakClient(device)
parsed_data: dict = {} parsed_data: dict = {}
async with self.polling_lock:
try:
async with async_timeout.timeout(self.polling_timeout):
# Reconnect if not connected
for attempt in range(1, self.max_retries + 1):
try:
if not self.client.is_connected:
await self.client.connect()
break
except Exception as e:
if attempt == self.max_retries or attempt == 1:
raise # pass exception on max_retries attempt
else:
self.logger.warning(f"Connect unsucessful (attempt {attempt}): {e}. Retrying...")
await asyncio.sleep(2)
# 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:
body = command.parse_response(
await self.async_send_command(command)
)
self.logger.debug("Raw data: %s", body)
parsed = self.bluetti_device.parse(
command.starting_address, body
)
self.logger.debug("Parsed data: %s", parsed)
parsed_data.update(parsed)
except ParseError:
self.logger.warning("Got a parse exception...")
if len(self.bluetti_device.pack_polling_commands) > 0:
self.logger.debug("Polling battery packs")
# pack polling
for pack in range (1, self.bluetti_device.pack_num_max + 1):
# Set current pack number
await self.async_send_command(
self.bluetti_device.build_setter_command('pack_num', pack)
)
for command in self.bluetti_device.pack_polling_commands:
# Request & parse result for each pack
try:
body = command.parse_response(
await self.async_send_command(command)
)
parsed = self.bluetti_device.parse(
command.starting_address, body
)
self.logger.debug("Parsed data: %s", parsed)
pack_number = parsed.get('pack_num')
if not isinstance(pack_number, int) or pack_number != pack:
self.logger.debug("Parsed pack_num(%s) does not match expected '%s'", pack_number, pack)
continue
for key, value in parsed.items():
parsed_data.update({key+str(pack):value})
except ParseError:
self.logger.warning("Got a parse exception...")
except TimeoutError:
self.logger.warning("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:
# Disconnect if connection not persistant
if not self.persistent_conn:
if self.has_notifier:
await self.client.stop_notify(BluetoothClient.NOTIFY_UUID)
self.has_notifier = False
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
async def async_send_command(self, command: ReadHoldingRegisters) -> bytes:
"""Send command and return response"""
try: try:
async with async_timeout.timeout(15): # Prepare to make request
await client.connect() self.current_command = command
self.notify_future = self.hass.loop.create_future()
self.notify_response = bytearray()
await client.start_notify( # Make request
BluetoothClient.NOTIFY_UUID, self._notification_handler self.logger.debug("Requesting %s", command)
) await self.client.write_gatt_char(
BluetoothClient.WRITE_UUID, bytes(command)
)
for command in self.bluetti_device.polling_commands: # Wait for response
try: res = await asyncio.wait_for(
# Prepare to make request self.notify_future, timeout=BluetoothClient.RESPONSE_TIMEOUT
self.current_command = command )
self.notify_future = self.hass.loop.create_future()
self.notify_response = bytearray()
# Make request # Process data
self.logger.debug("Requesting %s", command) self.logger.debug("Got %s bytes", len(res))
await client.write_gatt_char( return cast(bytes, res)
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.warning(
"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 (This can also be the case if you used device controls)", err
)
except TimeoutError: except TimeoutError:
self.logger.warning("Polling timed out for device %s", self._address) self.logger.debug(
return None "Polling timed out (address: %s)", mac_loggable(self._address)
except BleakError as err: )
self.logger.warning("Bleak error: %s", err) except ModbusError as err:
return None self.logger.warning(
finally: "Got an invalid request error for %s: %s",
await client.disconnect() command,
err,
)
except (BadConnectionError, BleakError) as err:
self.logger.warning(
"Needed to disconnect due to error: %s (This can also be the case if you used device controls)", err
)
self.hass.data[DOMAIN][self.config_entry.entry_id][DATA_POLLING_RUNNING] = False # caught an exception, return empty bytes object
return bytes()
# Pass data back to sensors
return parsed_data
def _notification_handler(self, _sender: int, data: bytearray): def _notification_handler(self, _sender: int, data: bytearray):
"""Handle bt data.""" """Handle bt data."""
# Ignore notifications we don't expect # Ignore notifications we don't expect
if not self.notify_future or self.notify_future.done(): if not self.notify_future or self.notify_future.done():
_LOGGER.warning("Unexpected notification")
return return
# If something went wrong, we might get weird data. # If something went wrong, we might get weird data.
+1 -1
View File
@@ -18,5 +18,5 @@
"iot_class": "local_polling", "iot_class": "local_polling",
"issue_tracker": "https://github.com/Patrick762/hassio-bluetti-bt/issues", "issue_tracker": "https://github.com/Patrick762/hassio-bluetti-bt/issues",
"requirements": ["bluetti_mqtt==0.15.0"], "requirements": ["bluetti_mqtt==0.15.0"],
"version": "0.0.8" "version": "0.0.11"
} }
+27 -5
View File
@@ -27,11 +27,13 @@ from bluetti_mqtt.mqtt_client import (
NORMAL_DEVICE_FIELDS, NORMAL_DEVICE_FIELDS,
DC_INPUT_FIELDS, DC_INPUT_FIELDS,
MqttFieldType, MqttFieldType,
battery_pack_fields,
) )
from . import device_info as dev_info, get_unique_id from . import device_info as dev_info, get_unique_id
from .const import DATA_COORDINATOR, 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 .coordinator import PollingCoordinator, DummyDevice
from .utils import unique_id_loggable
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -58,8 +60,16 @@ async def async_setup_entry(
all_fields = NORMAL_DEVICE_FIELDS all_fields = NORMAL_DEVICE_FIELDS
all_fields.update(DC_INPUT_FIELDS) all_fields.update(DC_INPUT_FIELDS)
all_fields.update(ADDITIONAL_DEVICE_FIELDS) all_fields.update(ADDITIONAL_DEVICE_FIELDS)
if len(bluetti_device.pack_polling_commands) > 0:
# add pack fields for device
_LOGGER.info("Device type(%s) pack_num_max(%s)", bluetti_device.type, bluetti_device.pack_num_max)
for pack in range (1, bluetti_device.pack_num_max + 1):
for name, field in battery_pack_fields(pack).items():
all_fields.update({name+str(pack): field})
for field_key, field_config in all_fields.items(): for field_key, field_config in all_fields.items():
if bluetti_device.has_field(field_key): if bluetti_device.has_field(field_key) or field_config.id_override is not None:
category = None category = None
if field_config.setter is True or field_key in DIAGNOSTIC_FIELDS: if field_config.setter is True or field_key in DIAGNOSTIC_FIELDS:
category = EntityCategory.DIAGNOSTIC category = EntityCategory.DIAGNOSTIC
@@ -129,16 +139,28 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
@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)
if self.coordinator.persistent_conn and not self.coordinator.client.is_connected:
return
if self.coordinator.data is None:
_LOGGER.warning(
"Data from coordinator is None. Skipping update for %s",
unique_id_loggable(self._attr_unique_id)
)
return
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
if not isinstance(self.coordinator.data, dict): if not isinstance(self.coordinator.data, dict):
_LOGGER.error( _LOGGER.warning(
"Invalid data from coordinator (sensor.%s)", self._attr_unique_id "Invalid data from coordinator (sensor.%s)", unique_id_loggable(self._attr_unique_id)
) )
self._attr_available = False self._attr_available = False
return return
response_data = self.coordinator.data.get(self._response_key) response_data = self.coordinator.data.get(self._response_key)
if response_data is None: if response_data is None:
_LOGGER.warning("No data for available for (%s)", self._response_key)
self._attr_available = False self._attr_available = False
return return
@@ -151,7 +173,7 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
): ):
_LOGGER.warning( _LOGGER.warning(
"Invalid response data type from coordinator (sensor.%s): %s has type %s", "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, response_data,
type(response_data), type(response_data),
) )
+39 -37
View File
@@ -6,7 +6,7 @@ import asyncio
import logging import logging
import async_timeout import async_timeout
from bleak import BleakClient, BleakError from bleak import BleakError
from homeassistant.components import bluetooth from homeassistant.components import bluetooth
from homeassistant.components.switch import SwitchEntity, SwitchDeviceClass from homeassistant.components.switch import SwitchEntity, SwitchDeviceClass
@@ -33,8 +33,9 @@ from bluetti_mqtt.mqtt_client import (
) )
from . import device_info as dev_info, get_unique_id 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 .const import CONTROL_FIELDS, DATA_COORDINATOR, DOMAIN, ADDITIONAL_DEVICE_FIELDS
from .coordinator import PollingCoordinator, DummyDevice from .coordinator import PollingCoordinator, DummyDevice
from .utils import mac_loggable, unique_id_loggable
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -50,7 +51,7 @@ async def async_setup_entry(
_LOGGER.error("Device has no address") _LOGGER.error("Device has no address")
# Generate device info # 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) device_info = dev_info(entry)
# Add sensors according to device_info # Add sensors according to device_info
@@ -98,6 +99,9 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
super().__init__(coordinator) super().__init__(coordinator)
self._bluetti_device = bluetti_device self._bluetti_device = bluetti_device
self._coordinator = coordinator
self._client = coordinator.client
self._polling_lock = coordinator.polling_lock
e_name = f"{device_info.get('name')} {name}" e_name = f"{device_info.get('name')} {name}"
self._address = address self._address = address
self._response_key = response_key self._response_key = response_key
@@ -113,10 +117,14 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
@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)
if self.coordinator.persistent_conn and not self.coordinator.client.is_connected:
return
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
if not isinstance(self.coordinator.data, dict): if not isinstance(self.coordinator.data, dict):
_LOGGER.error( _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 self._attr_available = False
return return
@@ -128,8 +136,8 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
if not isinstance(response_data, bool): if not isinstance(response_data, bool):
_LOGGER.warning( _LOGGER.warning(
"Invalid response data type from coordinator (sensor.%s): %s", "Invalid response data type from coordinator (switch.%s): %s",
self._attr_unique_id, unique_id_loggable(self._attr_unique_id),
response_data, response_data,
) )
self._attr_available = False self._attr_available = False
@@ -141,48 +149,42 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
async def async_turn_on(self, **kwargs): async def async_turn_on(self, **kwargs):
"""Turn the entity on.""" """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) await self.write_to_device(True)
async def async_turn_off(self, **kwargs): async def async_turn_off(self, **kwargs):
"""Turn the entity off.""" """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) await self.write_to_device(False)
async def write_to_device(self, state: bool): async def write_to_device(self, state: bool):
"""Write to device.""" """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)
return
command = self._bluetti_device.build_setter_command(self._response_key, state) command = self._bluetti_device.build_setter_command(self._response_key, state)
# Wait until polling is done async with self._polling_lock:
while self.hass.data[DOMAIN][self._entry_id][DATA_POLLING_RUNNING] is True: try:
_LOGGER.debug("Waiting for polling to finish...") async with async_timeout.timeout(15):
asyncio.sleep(1) if not self._client.is_connected:
await self._client.connect()
client = BleakClient(device) # Send command
try: _LOGGER.debug("Requesting %s (%s,%s)", command, self._response_key, state)
async with async_timeout.timeout(15): await self._client.write_gatt_char(
await client.connect() BluetoothClient.WRITE_UUID, bytes(command)
)
# Send command # Wait until device has changed value, otherwise reading register might reset it
await client.write_gatt_char( await asyncio.sleep(5)
BluetoothClient.WRITE_UUID, bytes(command)
)
# Wait until device has changed value, otherwise reading register might reset it except TimeoutError:
await asyncio.sleep(5) _LOGGER.error("Timed out for device %s", mac_loggable(self._address))
return None
except TimeoutError: except BleakError as err:
_LOGGER.error("Timed out for device %s", self._address) _LOGGER.error("Bleak error: %s", err)
return None return None
except BleakError as err: finally:
_LOGGER.error("Bleak error: %s", err) # Disconnect if connection not persistant
return None if not self._coordinator.persistent_conn:
finally: await self._client.disconnect()
await client.disconnect()
await self.coordinator.async_request_refresh() await self.coordinator.async_request_refresh()
@@ -3,9 +3,18 @@
"step": { "step": {
"init": { "init": {
"data": { "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)",
"polling_timeout": "Datenabruf-Timeout in Sekunden (Neustart erforderlich)",
"max_retries": "Maximale Verbindungsversuche (Neustart erforderlich)"
} }
} }
},
"abort": {
"invalid_interval": "Ungültiger Datenabruf-Intervall. Verwende 5 Sekunden oder mehr",
"invalid_timeout": "Ungültiger Datenabruf-Timeout. Verwende 1 Sekunde oder mehr",
"invalid_retries": "Ungültige maximale Verbindungsversuche. Verwende 1 oder mehr"
} }
} }
} }
@@ -3,9 +3,18 @@
"step": { "step": {
"init": { "init": {
"data": { "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)",
"polling_timeout": "Polling timeout in seconds (restart required)",
"max_retries": "Maximum amount of connection retries (restart required)"
} }
} }
},
"abort": {
"invalid_interval": "Invalid polling interval. Use 5 seconds or more",
"invalid_timeout": "Invalid polling timeout. Use 1 second or more",
"invalid_retries": "Invalid max retries. Use 1 or more"
} }
} }
} }
@@ -0,0 +1,16 @@
{
"options": {
"step": {
"init": {
"data": {
"use_controls": "Usar os comandos",
"persistent_conn": "Ligação presistente (necessario reninciar)",
"polling_interval": "Intervalo deatualização (necessario reninciar)"
}
}
},
"abort": {
"invalid_interval": "Valor invalido . Tem de ser no minimo 5 segundos"
}
}
}
+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]
-1
View File
@@ -1 +0,0 @@
robocopy .\custom_components\bluetti_bt T:\custom_components\bluetti_bt /E
Executable
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# This script is only for development purposes
sudo cp -r ./custom_components/* /var/ha_config/custom_components/