Compare commits
110
Commits
0.0.19
...
0.2.0-alpha.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
773a9b2205 | ||
|
|
998362a5e6 | ||
|
|
206d22c50b | ||
|
|
e2ac4cf8f5 | ||
|
|
ba98204ab2 | ||
|
|
8912a0bd08 | ||
|
|
db0147e7c1 | ||
|
|
c5f985b5f6 | ||
|
|
63f798ca5a | ||
|
|
483ca4049d | ||
|
|
de1ca78c90 | ||
|
|
a72f42eb4a | ||
|
|
6ce8f24477 | ||
|
|
28cd715327 | ||
|
|
49c1409656 | ||
|
|
d61459c011 | ||
|
|
edf5e87720 | ||
|
|
742964b78b | ||
|
|
21e89e738d | ||
|
|
52fd1932fa | ||
|
|
3e54283faf | ||
|
|
9be8aa47ac | ||
|
|
8967f3379c | ||
|
|
6f9afedfdb | ||
|
|
fe23dd00cd | ||
|
|
566761dba7 | ||
|
|
33cb6e6fbd | ||
|
|
5823136280 | ||
|
|
7b6f845edb | ||
|
|
1fbcf83b1b | ||
|
|
da2017a24b | ||
|
|
83f0db267c | ||
|
|
149633f9c8 | ||
|
|
9ab7cefda7 | ||
|
|
52853d6d3e | ||
|
|
c96f551024 | ||
|
|
75209ee1aa | ||
|
|
7396616113 | ||
|
|
a7f7ff1843 | ||
|
|
cc755b3003 | ||
|
|
e5f690ef3b | ||
|
|
fa9bcf63ca | ||
|
|
211f1971c5 | ||
|
|
a1e9c180b3 | ||
|
|
0e5c1a0b44 | ||
|
|
0f33a31ee5 | ||
|
|
23551ae829 | ||
|
|
a54b36a90b | ||
|
|
f85661345c | ||
|
|
3d3401c942 | ||
|
|
f50232ee89 | ||
|
|
5922362772 | ||
|
|
6478825503 | ||
|
|
3169ee182e | ||
|
|
ece1fc4129 | ||
|
|
4d54e048c5 | ||
|
|
09a9112279 | ||
|
|
b37276ec52 | ||
|
|
4f88792371 | ||
|
|
7da392d85a | ||
|
|
03ea349cbf | ||
|
|
5a762266c0 | ||
|
|
12a59346e9 | ||
|
|
206099ab64 | ||
|
|
6be2abaaf2 | ||
|
|
c3bfad0ea6 | ||
|
|
b548528085 | ||
|
|
6e433e3551 | ||
|
|
b34d0a3039 | ||
|
|
2922c5cb90 | ||
|
|
9af3d67ec6 | ||
|
|
221da9a38d | ||
|
|
f5430216a8 | ||
|
|
591c86baf5 | ||
|
|
97154bb027 | ||
|
|
b2672ec302 | ||
|
|
f5b8e09fb4 | ||
|
|
c8d75d1899 | ||
|
|
efaa9d0fdb | ||
|
|
9315650ddc | ||
|
|
9df2073585 | ||
|
|
2c6df77078 | ||
|
|
e584d32037 | ||
|
|
5ac8d8d7ae | ||
|
|
0cd5ae10fb | ||
|
|
a93b80796a | ||
|
|
a7967e74dd | ||
|
|
5bd98d6de3 | ||
|
|
2a4c3e943c | ||
|
|
dcfebb0f84 | ||
|
|
44dbd2b965 | ||
|
|
89928e2d9c | ||
|
|
dc3aaf92e1 | ||
|
|
95b1dafeb1 | ||
|
|
15a890fb7d | ||
|
|
542f244a28 | ||
|
|
eb701de865 | ||
|
|
f8ed8141ac | ||
|
|
bf86fe172b | ||
|
|
babdd1755e | ||
|
|
7596f8cee1 | ||
|
|
98d2a0b73e | ||
|
|
c499fbcd9b | ||
|
|
ec996d5728 | ||
|
|
7f576df84b | ||
|
|
8bc8ba4a4b | ||
|
|
213ee82e63 | ||
|
|
c08099ca4f | ||
|
|
4008dc844e | ||
|
|
e27c28b5c8 |
No files matched your search
@@ -0,0 +1,3 @@
|
|||||||
|
*/__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
github: Patrick762
|
||||||
@@ -14,32 +14,16 @@ body:
|
|||||||
value: "An exception appeared"
|
value: "An exception appeared"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: textarea
|
||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: Version
|
label: What version of our software are you running?
|
||||||
description: What version of our software are you running?
|
|
||||||
options:
|
|
||||||
- 0.0.11
|
|
||||||
- 0.0.10
|
|
||||||
- 0.0.9
|
|
||||||
default: 0
|
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: textarea
|
||||||
id: device
|
id: device
|
||||||
attributes:
|
attributes:
|
||||||
label: What device are you seeing the problem on?
|
label: What device are you seeing the problem on?
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- AC60
|
|
||||||
- AC200M
|
|
||||||
- AC300
|
|
||||||
- AC500
|
|
||||||
- EB3A
|
|
||||||
- EP500
|
|
||||||
- EP500P
|
|
||||||
- EP900
|
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
@@ -50,6 +34,7 @@ body:
|
|||||||
options:
|
options:
|
||||||
- USB dongle
|
- USB dongle
|
||||||
- ESPHome bluetooth proxy
|
- ESPHome bluetooth proxy
|
||||||
|
- Internal bluetooth adapter
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
name: Unittests
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
# Allows you to run this workflow manually from the Actions tab
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v3
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -r requirements.txt
|
||||||
|
- name: Run unittests
|
||||||
|
run: python3 -m unittest discover -s tests -p "*_test.py"
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
*/__pycache__/
|
*/__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM python:3
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install -r requirements.txt
|
||||||
|
|
||||||
|
COPY tests ./tests
|
||||||
|
COPY custom_components ./custom_components
|
||||||
|
|
||||||
|
RUN python3 -m unittest discover -s tests -p "*_test.py"
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2024 Patrick762
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -17,11 +17,14 @@ After the installation, you can use this button to install the integration:
|
|||||||
### Supported devices:
|
### Supported devices:
|
||||||
|
|
||||||
- AC60
|
- AC60
|
||||||
|
- AC70 (basic data)
|
||||||
|
- AC70P (untested)
|
||||||
- AC180 (basic data)
|
- AC180 (basic data)
|
||||||
- AC180P (basic data)
|
- AC180P (tested)
|
||||||
|
- AC200L (untested)
|
||||||
- AC200M
|
- AC200M
|
||||||
- AC300 (tested)
|
- AC300 (tested)
|
||||||
- AC500
|
- AC500 (tested)
|
||||||
- EB3A
|
- EB3A
|
||||||
- EP500
|
- EP500
|
||||||
- EP500P
|
- EP500P
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from homeassistant.helpers.entity import DeviceInfo
|
|||||||
from homeassistant.exceptions import ConfigEntryNotReady
|
from homeassistant.exceptions import ConfigEntryNotReady
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
|
CONF_ENCRYPTION,
|
||||||
CONF_MAX_RETRIES,
|
CONF_MAX_RETRIES,
|
||||||
CONF_PERSISTENT_CONN,
|
CONF_PERSISTENT_CONN,
|
||||||
CONF_POLLING_INTERVAL,
|
CONF_POLLING_INTERVAL,
|
||||||
@@ -33,13 +34,16 @@ _LOGGER = logging.getLogger(__name__)
|
|||||||
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."""
|
||||||
|
|
||||||
|
_LOGGER.debug("Init Bluetti BT Integration for device %s", entry.data.get(CONF_NAME))
|
||||||
|
|
||||||
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)
|
polling_interval = entry.data.get(CONF_POLLING_INTERVAL, 60)
|
||||||
persistent_conn = entry.data.get(CONF_PERSISTENT_CONN, False)
|
persistent_conn = entry.data.get(CONF_PERSISTENT_CONN, False)
|
||||||
polling_timeout = entry.data.get(CONF_POLLING_TIMEOUT, 45)
|
polling_timeout = entry.data.get(CONF_POLLING_TIMEOUT, 120)
|
||||||
max_retries = entry.data.get(CONF_MAX_RETRIES, 5)
|
max_retries = entry.data.get(CONF_MAX_RETRIES, 5)
|
||||||
|
use_encryption = entry.data.get(CONF_ENCRYPTION, False)
|
||||||
|
|
||||||
if address is None:
|
if address is None:
|
||||||
return False
|
return False
|
||||||
@@ -53,10 +57,12 @@ 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, polling_interval, persistent_conn, polling_timeout, max_retries)
|
_LOGGER.debug("Creating coordinator")
|
||||||
|
coordinator = PollingCoordinator(hass, address, device_name, polling_interval, persistent_conn, polling_timeout, max_retries, use_encryption)
|
||||||
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)
|
||||||
|
|
||||||
|
_LOGGER.debug("Creating entities")
|
||||||
platforms: list = PLATFORMS
|
platforms: list = PLATFORMS
|
||||||
if use_controls is True:
|
if use_controls is True:
|
||||||
_LOGGER.warning("You are using controls with this integration at your own risk!")
|
_LOGGER.warning("You are using controls with this integration at your own risk!")
|
||||||
@@ -65,6 +71,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
# Setup platforms
|
# Setup platforms
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, platforms)
|
await hass.config_entries.async_forward_entry_setups(entry, platforms)
|
||||||
|
|
||||||
|
_LOGGER.debug("Setup done")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ from .bluetti_bt_lib.field_attributes import FIELD_ATTRIBUTES, FieldType
|
|||||||
from .bluetti_bt_lib.utils.device_builder import build_device
|
from .bluetti_bt_lib.utils.device_builder import build_device
|
||||||
|
|
||||||
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
|
from .const import DATA_COORDINATOR, DOMAIN, CONF_USE_CONTROLS
|
||||||
from .coordinator import PollingCoordinator
|
from .coordinator import PollingCoordinator
|
||||||
from .utils import unique_id_loggable
|
from .utils import unique_id_loggable
|
||||||
|
|
||||||
@@ -36,6 +36,7 @@ async def async_setup_entry(
|
|||||||
|
|
||||||
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)
|
||||||
|
use_controls = entry.data.get(CONF_USE_CONTROLS, False)
|
||||||
if address is None:
|
if address is None:
|
||||||
_LOGGER.error("Device has no address")
|
_LOGGER.error("Device has no address")
|
||||||
|
|
||||||
@@ -51,9 +52,8 @@ async def async_setup_entry(
|
|||||||
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):
|
||||||
if field_config.type == FieldType.BOOL:
|
if field_config.type == FieldType.BOOL:
|
||||||
category = None
|
|
||||||
if field_config.setter is True:
|
if field_config.setter is True:
|
||||||
category = EntityCategory.DIAGNOSTIC
|
continue
|
||||||
|
|
||||||
sensors_to_add.append(
|
sensors_to_add.append(
|
||||||
BluettiBinarySensor(
|
BluettiBinarySensor(
|
||||||
@@ -62,7 +62,6 @@ async def async_setup_entry(
|
|||||||
address,
|
address,
|
||||||
field_key,
|
field_key,
|
||||||
field_config.name,
|
field_config.name,
|
||||||
category=category,
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -79,7 +78,6 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
|
|||||||
address,
|
address,
|
||||||
response_key: str,
|
response_key: str,
|
||||||
name: str,
|
name: str,
|
||||||
category: EntityCategory | None = None,
|
|
||||||
):
|
):
|
||||||
"""Init battery entity."""
|
"""Init battery entity."""
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
@@ -88,12 +86,38 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
|
|||||||
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
|
||||||
|
self._unavailable_counter = 5
|
||||||
|
|
||||||
self._attr_device_info = device_info
|
self._attr_device_info = device_info
|
||||||
self._attr_name = name
|
self._attr_name = name
|
||||||
self._attr_available = False
|
self._attr_available = False
|
||||||
self._attr_unique_id = get_unique_id(e_name)
|
self._attr_unique_id = get_unique_id(e_name)
|
||||||
self._attr_entity_category = category
|
|
||||||
|
@property
|
||||||
|
def available(self) -> bool:
|
||||||
|
"""Return if entity is available."""
|
||||||
|
return self._attr_available
|
||||||
|
|
||||||
|
def _set_available(self):
|
||||||
|
"""Set sensor as available."""
|
||||||
|
self._attr_available = True
|
||||||
|
self._unavailable_counter = 0
|
||||||
|
self._attr_extra_state_attributes = {}
|
||||||
|
self.async_write_ha_state()
|
||||||
|
|
||||||
|
def _set_unavailable(self, cause: str = "Unknown"):
|
||||||
|
"""Set sensor as unavailable."""
|
||||||
|
self._unavailable_counter += 1
|
||||||
|
|
||||||
|
self._attr_extra_state_attributes = {
|
||||||
|
"unavailable_counter": self._unavailable_counter,
|
||||||
|
"unavailable_cause": cause,
|
||||||
|
}
|
||||||
|
|
||||||
|
if self._unavailable_counter >= 5:
|
||||||
|
self._attr_available = False
|
||||||
|
|
||||||
|
self.async_write_ha_state()
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
def _handle_coordinator_update(self) -> None:
|
def _handle_coordinator_update(self) -> None:
|
||||||
@@ -102,17 +126,24 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
|
|||||||
if self.coordinator.reader.persistent_conn and not self.coordinator.reader.client.is_connected:
|
if self.coordinator.reader.persistent_conn and not self.coordinator.reader.client.is_connected:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if self.coordinator.data is None:
|
||||||
|
_LOGGER.debug(
|
||||||
|
"Data from coordinator is None",
|
||||||
|
)
|
||||||
|
self._set_unavailable("Data is None")
|
||||||
|
return
|
||||||
|
|
||||||
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
|
_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.debug(
|
_LOGGER.debug(
|
||||||
"Invalid data from coordinator (binary_sensor.%s)", unique_id_loggable(self._attr_unique_id)
|
"Invalid data from coordinator (binary_sensor.%s)", unique_id_loggable(self._attr_unique_id)
|
||||||
)
|
)
|
||||||
self._attr_available = False
|
self._set_unavailable("Invalid data")
|
||||||
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:
|
||||||
self._attr_available = False
|
self._set_unavailable("No data")
|
||||||
return
|
return
|
||||||
|
|
||||||
if not isinstance(response_data, bool):
|
if not isinstance(response_data, bool):
|
||||||
@@ -121,9 +152,9 @@ class BluettiBinarySensor(CoordinatorEntity, BinarySensorEntity):
|
|||||||
unique_id_loggable(self._attr_unique_id),
|
unique_id_loggable(self._attr_unique_id),
|
||||||
response_data,
|
response_data,
|
||||||
)
|
)
|
||||||
self._attr_available = False
|
self._set_unavailable("Invalid data type")
|
||||||
return
|
return
|
||||||
|
|
||||||
self._attr_available = True
|
self._set_available()
|
||||||
self._attr_is_on = self.coordinator.data[self._response_key] is True
|
self._attr_is_on = self.coordinator.data[self._response_key] is True
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
@@ -43,6 +43,11 @@ class BluettiDevice:
|
|||||||
"""The address ranges that are writable"""
|
"""The address ranges that are writable"""
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pack_num_field(self) -> List[ReadHoldingRegisters]:
|
||||||
|
"""The address 'range' of the pack num result. Matches pack_num_result"""
|
||||||
|
return []
|
||||||
|
|
||||||
def has_field(self, field: str):
|
def has_field(self, field: str):
|
||||||
return any(f.name == field for f in self.struct.fields)
|
return any(f.name == field for f in self.struct.fields)
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ class ProtocolV1Device(BluettiDevice):
|
|||||||
# Device info
|
# Device info
|
||||||
self.struct.add_string_field("device_type", 10, 6)
|
self.struct.add_string_field("device_type", 10, 6)
|
||||||
self.struct.add_sn_field("serial_number", 17)
|
self.struct.add_sn_field("serial_number", 17)
|
||||||
|
self.struct.add_version_field('arm_version', 23)
|
||||||
|
self.struct.add_version_field('dsp_version', 25)
|
||||||
|
|
||||||
# Power IO
|
# Power IO
|
||||||
self.struct.add_uint_field("dc_input_power", 36)
|
self.struct.add_uint_field("dc_input_power", 36)
|
||||||
@@ -29,13 +31,6 @@ class ProtocolV1Device(BluettiDevice):
|
|||||||
# Battery
|
# Battery
|
||||||
self.struct.add_uint_field("total_battery_percent", 43)
|
self.struct.add_uint_field("total_battery_percent", 43)
|
||||||
|
|
||||||
# Battery packs
|
|
||||||
self.struct.add_uint_field("pack_num_max", 91) # internal
|
|
||||||
self.struct.add_decimal_field("total_battery_voltage", 92, 1)
|
|
||||||
self.struct.add_uint_field("pack_num", 96) # internal
|
|
||||||
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
|
||||||
self.struct.add_uint_field("pack_battery_percent", 99)
|
|
||||||
|
|
||||||
# Output state
|
# Output state
|
||||||
self.struct.add_bool_field("ac_output_on", 48)
|
self.struct.add_bool_field("ac_output_on", 48)
|
||||||
self.struct.add_bool_field("dc_output_on", 49)
|
self.struct.add_bool_field("dc_output_on", 49)
|
||||||
@@ -56,20 +51,16 @@ class ProtocolV1Device(BluettiDevice):
|
|||||||
ReadHoldingRegisters(36, 4),
|
ReadHoldingRegisters(36, 4),
|
||||||
ReadHoldingRegisters(41, 1),
|
ReadHoldingRegisters(41, 1),
|
||||||
ReadHoldingRegisters(43, 1),
|
ReadHoldingRegisters(43, 1),
|
||||||
ReadHoldingRegisters(91, 2),
|
|
||||||
ReadHoldingRegisters(96, 1),
|
|
||||||
ReadHoldingRegisters(98, 2),
|
|
||||||
ReadHoldingRegisters(48, 2),
|
ReadHoldingRegisters(48, 2),
|
||||||
|
ReadHoldingRegisters(3007, 2),
|
||||||
]
|
]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return [range(3006, 3008)]
|
return [range(3006, 3009)]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
def pack_num_field(self) -> List[ReadHoldingRegisters]:
|
||||||
return [
|
return [
|
||||||
ReadHoldingRegisters(91, 2),
|
|
||||||
ReadHoldingRegisters(96, 1),
|
ReadHoldingRegisters(96, 1),
|
||||||
ReadHoldingRegisters(98, 2),
|
|
||||||
]
|
]
|
||||||
@@ -6,6 +6,8 @@ from typing import Any, Callable, List, cast
|
|||||||
import async_timeout
|
import async_timeout
|
||||||
from bleak import BleakClient, BleakError
|
from bleak import BleakClient, BleakError
|
||||||
|
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.bluetooth.encryption import BluettiEncryption, Message, MessageType
|
||||||
|
|
||||||
from ..base_devices.BluettiDevice import BluettiDevice
|
from ..base_devices.BluettiDevice import BluettiDevice
|
||||||
from ..const import NOTIFY_UUID, RESPONSE_TIMEOUT, WRITE_UUID
|
from ..const import NOTIFY_UUID, RESPONSE_TIMEOUT, WRITE_UUID
|
||||||
from ..exceptions import BadConnectionError, ModbusError, ParseError
|
from ..exceptions import BadConnectionError, ModbusError, ParseError
|
||||||
@@ -23,6 +25,7 @@ class DeviceReader:
|
|||||||
persistent_conn: bool = False,
|
persistent_conn: bool = False,
|
||||||
polling_timeout: int = 45,
|
polling_timeout: int = 45,
|
||||||
max_retries: int = 5,
|
max_retries: int = 5,
|
||||||
|
encrypted: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.client = bleak_client
|
self.client = bleak_client
|
||||||
self.bluetti_device = bluetti_device
|
self.bluetti_device = bluetti_device
|
||||||
@@ -30,6 +33,7 @@ class DeviceReader:
|
|||||||
self.persistent_conn = persistent_conn
|
self.persistent_conn = persistent_conn
|
||||||
self.polling_timeout = polling_timeout
|
self.polling_timeout = polling_timeout
|
||||||
self.max_retries = max_retries
|
self.max_retries = max_retries
|
||||||
|
self.encrypted = encrypted
|
||||||
|
|
||||||
self.has_notifier = False
|
self.has_notifier = False
|
||||||
self.notify_future: asyncio.Future[Any] | None = None
|
self.notify_future: asyncio.Future[Any] | None = None
|
||||||
@@ -39,6 +43,8 @@ class DeviceReader:
|
|||||||
# polling mutex to guard against switches
|
# polling mutex to guard against switches
|
||||||
self.polling_lock = asyncio.Lock()
|
self.polling_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
self.encryption = BluettiEncryption()
|
||||||
|
|
||||||
async def read_data(
|
async def read_data(
|
||||||
self, filter_registers: List[ReadHoldingRegisters] | None = None
|
self, filter_registers: List[ReadHoldingRegisters] | None = None
|
||||||
) -> dict | None:
|
) -> dict | None:
|
||||||
@@ -53,6 +59,8 @@ class DeviceReader:
|
|||||||
if filter_registers is not None:
|
if filter_registers is not None:
|
||||||
polling_commands = filter_registers
|
polling_commands = filter_registers
|
||||||
pack_commands = []
|
pack_commands = []
|
||||||
|
_LOGGER.info("Polling commands: " + ",".join([f"{c.starting_address}-{c.starting_address + c.quantity - 1}" for c in polling_commands]))
|
||||||
|
_LOGGER.info("Pack comands: " + ",".join([f"{c.starting_address}-{c.starting_address + c.quantity - 1}" for c in pack_commands]))
|
||||||
|
|
||||||
parsed_data: dict = {}
|
parsed_data: dict = {}
|
||||||
|
|
||||||
@@ -66,8 +74,8 @@ class DeviceReader:
|
|||||||
await self.client.connect()
|
await self.client.connect()
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if attempt == self.max_retries or attempt == 1:
|
if attempt == self.max_retries:
|
||||||
raise # pass exception on max_retries attempt
|
raise e # pass exception on max_retries attempt
|
||||||
else:
|
else:
|
||||||
_LOGGER.warning(
|
_LOGGER.warning(
|
||||||
f"Connect unsucessful (attempt {attempt}): {e}. Retrying..."
|
f"Connect unsucessful (attempt {attempt}): {e}. Retrying..."
|
||||||
@@ -81,6 +89,10 @@ class DeviceReader:
|
|||||||
)
|
)
|
||||||
self.has_notifier = True
|
self.has_notifier = True
|
||||||
|
|
||||||
|
while self.encrypted and not self.encryption.is_ready_for_commands:
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
_LOGGER.debug("Encryption handshake not finished yet")
|
||||||
|
|
||||||
# Execute polling commands
|
# Execute polling commands
|
||||||
for command in polling_commands:
|
for command in polling_commands:
|
||||||
try:
|
try:
|
||||||
@@ -97,17 +109,29 @@ class DeviceReader:
|
|||||||
_LOGGER.warning("Got a parse exception")
|
_LOGGER.warning("Got a parse exception")
|
||||||
|
|
||||||
# Execute pack polling commands
|
# Execute pack polling commands
|
||||||
if len(pack_commands) > 0:
|
if len(pack_commands) > 0 and len(self.bluetti_device.pack_num_field) == 1:
|
||||||
_LOGGER.debug("Polling battery packs")
|
_LOGGER.debug("Polling battery packs")
|
||||||
for pack in range(1, self.bluetti_device.pack_num_max + 1):
|
for pack in range(1, self.bluetti_device.pack_num_max + 1):
|
||||||
|
_LOGGER.debug("Setting pack_num to %i", pack)
|
||||||
|
|
||||||
# Set current pack number
|
# Set current pack number
|
||||||
await self._async_send_command(
|
command = self.bluetti_device.build_setter_command(
|
||||||
self.bluetti_device.build_setter_command(
|
|
||||||
"pack_num", pack
|
"pack_num", pack
|
||||||
)
|
)
|
||||||
|
body = command.parse_response(
|
||||||
|
await self._async_send_command(command)
|
||||||
)
|
)
|
||||||
|
_LOGGER.debug("Raw data set: %s", body)
|
||||||
|
|
||||||
# We need to wait after switching packs for the data to be available
|
# Check set pack_num
|
||||||
|
set_pack = int.from_bytes(body, byteorder='big')
|
||||||
|
if set_pack is not pack:
|
||||||
|
_LOGGER.warning("Pack polling failed (pack_num %i doesn't match expected %i)", set_pack, pack)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if self.bluetti_device.pack_num_max > 1:
|
||||||
|
# We need to wait after switching packs
|
||||||
|
# for the data to be available
|
||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
|
|
||||||
for command in pack_commands:
|
for command in pack_commands:
|
||||||
@@ -121,26 +145,16 @@ class DeviceReader:
|
|||||||
)
|
)
|
||||||
_LOGGER.debug("Parsed data: %s", parsed)
|
_LOGGER.debug("Parsed data: %s", parsed)
|
||||||
|
|
||||||
pack_number = parsed.get("pack_num")
|
|
||||||
if (
|
|
||||||
not isinstance(pack_number, int)
|
|
||||||
or pack_number != pack
|
|
||||||
):
|
|
||||||
_LOGGER.debug(
|
|
||||||
"Parsed pack_num(%s) does not match expected '%s'",
|
|
||||||
pack_number,
|
|
||||||
pack,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
for key, value in parsed.items():
|
for key, value in parsed.items():
|
||||||
|
# Ignore likely unavailable pack data
|
||||||
|
if value != 0:
|
||||||
parsed_data.update({key + str(pack): value})
|
parsed_data.update({key + str(pack): value})
|
||||||
|
|
||||||
except ParseError:
|
except ParseError:
|
||||||
_LOGGER.warning("Got a parse exception...")
|
_LOGGER.warning("Got a parse exception...")
|
||||||
|
|
||||||
except TimeoutError:
|
except TimeoutError as err:
|
||||||
_LOGGER.error("Polling timed out")
|
_LOGGER.error(f"Polling timed out ({self.polling_timeout}s). Trying again later", exc_info=err)
|
||||||
return None
|
return None
|
||||||
except BleakError as err:
|
except BleakError as err:
|
||||||
_LOGGER.error("Bleak error: %s", err)
|
_LOGGER.error("Bleak error: %s", err)
|
||||||
@@ -149,10 +163,21 @@ class DeviceReader:
|
|||||||
# Disconnect if connection not persistant
|
# Disconnect if connection not persistant
|
||||||
if not self.persistent_conn:
|
if not self.persistent_conn:
|
||||||
if self.has_notifier:
|
if self.has_notifier:
|
||||||
|
try:
|
||||||
await self.client.stop_notify(NOTIFY_UUID)
|
await self.client.stop_notify(NOTIFY_UUID)
|
||||||
|
except:
|
||||||
|
# Ignore errors here
|
||||||
|
pass
|
||||||
self.has_notifier = False
|
self.has_notifier = False
|
||||||
await self.client.disconnect()
|
await self.client.disconnect()
|
||||||
|
|
||||||
|
# Check if dict is empty
|
||||||
|
if not parsed_data:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Reset Encryption keys
|
||||||
|
self.encryption.reset()
|
||||||
|
|
||||||
return parsed_data
|
return parsed_data
|
||||||
|
|
||||||
async def _async_send_command(self, command: ReadHoldingRegisters) -> bytes:
|
async def _async_send_command(self, command: ReadHoldingRegisters) -> bytes:
|
||||||
@@ -165,7 +190,16 @@ class DeviceReader:
|
|||||||
|
|
||||||
# Make request
|
# Make request
|
||||||
_LOGGER.debug("Requesting %s", command)
|
_LOGGER.debug("Requesting %s", command)
|
||||||
await self.client.write_gatt_char(WRITE_UUID, bytes(command))
|
|
||||||
|
command_bytes = bytes(command)
|
||||||
|
|
||||||
|
# Encrypt command
|
||||||
|
if self.encrypted is True:
|
||||||
|
if not self.encryption.is_ready_for_commands:
|
||||||
|
return bytes()
|
||||||
|
command_bytes = self.encryption.aes_encrypt(command_bytes, self.encryption.secure_aes_key, None)
|
||||||
|
|
||||||
|
await self.client.write_gatt_char(WRITE_UUID, command_bytes)
|
||||||
|
|
||||||
# Wait for response
|
# Wait for response
|
||||||
res = await asyncio.wait_for(self.notify_future, timeout=RESPONSE_TIMEOUT)
|
res = await asyncio.wait_for(self.notify_future, timeout=RESPONSE_TIMEOUT)
|
||||||
@@ -175,25 +209,61 @@ class DeviceReader:
|
|||||||
return cast(bytes, res)
|
return cast(bytes, res)
|
||||||
|
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
_LOGGER.warning("Polling single command timed out")
|
_LOGGER.debug("Polling single command timed out")
|
||||||
except ModbusError as err:
|
except ModbusError as err:
|
||||||
_LOGGER.warning(
|
_LOGGER.debug(
|
||||||
"Got an invalid request error for %s: %s",
|
"Got an invalid request error for %s: %s",
|
||||||
command,
|
command,
|
||||||
err,
|
err,
|
||||||
)
|
)
|
||||||
except (BadConnectionError, BleakError) as err:
|
except (BadConnectionError, BleakError) as err:
|
||||||
_LOGGER.warning(
|
# Ignore other errors
|
||||||
"Needed to disconnect due to error: %s (This can also be the case if you used device controls)",
|
pass
|
||||||
err,
|
|
||||||
)
|
|
||||||
|
|
||||||
# caught an exception, return empty bytes object
|
# caught an exception, return empty bytes object
|
||||||
return bytes()
|
return bytes()
|
||||||
|
|
||||||
def _notification_handler(self, _sender: int, data: bytearray):
|
async def _notification_handler(self, _sender: int, data: bytearray):
|
||||||
"""Handle bt data."""
|
"""Handle bt data."""
|
||||||
|
|
||||||
|
# Handle encrypted data
|
||||||
|
if self.encrypted is True:
|
||||||
|
message = Message(data)
|
||||||
|
|
||||||
|
# Handle key exchange
|
||||||
|
if message.is_pre_key_exchange:
|
||||||
|
message.verify_checksum()
|
||||||
|
|
||||||
|
if message.type == MessageType.CHALLENGE:
|
||||||
|
challenge_response = self.encryption.msg_challenge(message)
|
||||||
|
await self.client.write_gatt_char(WRITE_UUID, challenge_response)
|
||||||
|
return
|
||||||
|
|
||||||
|
if message.type == MessageType.CHALLENGE_ACCEPTED:
|
||||||
|
_LOGGER.debug("Challenge accepted")
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.encryption.unsecure_aes_key is None:
|
||||||
|
_LOGGER.error("Received encrypted message before key initialization")
|
||||||
|
|
||||||
|
key, iv = self.encryption.getKeyIv()
|
||||||
|
decrypted = Message(self.encryption.aes_decrypt(message.buffer, key, iv))
|
||||||
|
|
||||||
|
if decrypted.is_pre_key_exchange:
|
||||||
|
decrypted.verify_checksum()
|
||||||
|
|
||||||
|
if decrypted.type == MessageType.PEER_PUBKEY:
|
||||||
|
peer_pubkey_response = self.encryption.msg_peer_pubkey(decrypted)
|
||||||
|
await self.client.write_gatt_char(WRITE_UUID, peer_pubkey_response)
|
||||||
|
return
|
||||||
|
|
||||||
|
if decrypted.type == MessageType.PUBKEY_ACCEPTED:
|
||||||
|
self.encryption.msg_key_accepted(decrypted)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Handle as message
|
||||||
|
data = decrypted.buffer
|
||||||
|
|
||||||
# Ignore notifications we don't expect
|
# Ignore notifications we don't expect
|
||||||
if self.notify_future is None or self.notify_future.done():
|
if self.notify_future is None or self.notify_future.done():
|
||||||
_LOGGER.warning("Unexpected notification")
|
_LOGGER.warning("Unexpected notification")
|
||||||
|
|||||||
@@ -0,0 +1,289 @@
|
|||||||
|
from enum import Enum
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import pyasn1.codec.der.decoder as der_decoder
|
||||||
|
import pyasn1.codec.der.encoder as der_encoder
|
||||||
|
from pyasn1.type import univ
|
||||||
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ec
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.exceptions import InvalidSignature
|
||||||
|
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.const import LOCAL_AES_KEY, PRIVATE_KEY_L1, PUBLIC_KEY_K2, SECP_256R1_PUBLIC_PREFIX
|
||||||
|
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
KEX_MAGIC = b"**"
|
||||||
|
AES_BLOCK_SIZE = 16
|
||||||
|
|
||||||
|
def hexsum(s, sz: int):
|
||||||
|
checksum = sum(s)
|
||||||
|
as_hex = f"{checksum:0{sz*2}x}"
|
||||||
|
return bytes.fromhex(as_hex)
|
||||||
|
|
||||||
|
def hexxor(a: bytes, b: bytes) -> bytes | None:
|
||||||
|
if len(a) != len(b):
|
||||||
|
_LOGGER.error("Can only XOR two identical length byte strings")
|
||||||
|
return None
|
||||||
|
return bytes([x ^ y for x, y in zip(a, b)])
|
||||||
|
|
||||||
|
def raw_ecdsa_to_der(sig):
|
||||||
|
# <byte r[32]> <byte s[32]>
|
||||||
|
|
||||||
|
if len(sig) != 64:
|
||||||
|
raise ValueError("ecdsa signature is the wrong size")
|
||||||
|
|
||||||
|
seq = univ.SequenceOf()
|
||||||
|
seq.extend(
|
||||||
|
[
|
||||||
|
univ.Integer(int.from_bytes(sig[:32], "big")), # r
|
||||||
|
univ.Integer(int.from_bytes(sig[32:], "big")), # s
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return der_encoder.encode(seq)
|
||||||
|
|
||||||
|
def der_to_raw_ecdsa(sig):
|
||||||
|
# 30 45 02 20 1956307e59448178b47c222e4e1e6c8ef7d707bc230e5a9fa77f919ec44e5f74
|
||||||
|
# | | | | |> byte r[0x20]
|
||||||
|
# | | | |---> Length
|
||||||
|
# | | |------> DER type (int)
|
||||||
|
# | |---------> Payload size
|
||||||
|
# |------------> DER type (sequence)
|
||||||
|
|
||||||
|
# 02 21 00cfad6e11abd5e803fb6874c3838bc968db1f3c070ae6b85db9d8ed8936a1eb5c
|
||||||
|
# | | |> byte s[0x21]
|
||||||
|
# | |---> Length
|
||||||
|
# |------> DER type (int)
|
||||||
|
|
||||||
|
seq, remainder = der_decoder.decode(sig)
|
||||||
|
if remainder:
|
||||||
|
raise ValueError("Found trailing data")
|
||||||
|
|
||||||
|
return b"".join([int.to_bytes(int(x), 0x20, "big") for x in seq])
|
||||||
|
|
||||||
|
def verify_and_extract_signed_data(message, signed_data_suffix: bytes | None):
|
||||||
|
# 64 bytes of data
|
||||||
|
# 64 bytes of signature
|
||||||
|
if len(message) != 128:
|
||||||
|
raise ValueError("Unexpected message length")
|
||||||
|
|
||||||
|
data = message[:64]
|
||||||
|
signature = message[64:]
|
||||||
|
signed_data = data.tobytes() + signed_data_suffix
|
||||||
|
der_signature = raw_ecdsa_to_der(signature)
|
||||||
|
try:
|
||||||
|
key_bytes = bytes.fromhex(PUBLIC_KEY_K2)
|
||||||
|
serialization.load_der_public_key(key_bytes).verify(
|
||||||
|
der_signature, signed_data, ec.ECDSA(hashes.SHA256())
|
||||||
|
)
|
||||||
|
_LOGGER.debug("Signature OK")
|
||||||
|
except InvalidSignature:
|
||||||
|
raise
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
def pubkey_from_bytes(data):
|
||||||
|
encoded_peer_pubkey = bytes.fromhex(SECP_256R1_PUBLIC_PREFIX) + data
|
||||||
|
return serialization.load_der_public_key(encoded_peer_pubkey)
|
||||||
|
|
||||||
|
def generate_keypair():
|
||||||
|
private = ec.generate_private_key(ec.SECP256R1())
|
||||||
|
return (private.public_key(), private)
|
||||||
|
|
||||||
|
def pubkey_to_bytes(pubkey):
|
||||||
|
out = pubkey.public_bytes(
|
||||||
|
encoding=serialization.Encoding.X962,
|
||||||
|
format=serialization.PublicFormat.UncompressedPoint,
|
||||||
|
)
|
||||||
|
|
||||||
|
if out[0] != 0x4 or len(out) != 65:
|
||||||
|
raise RuntimeError(
|
||||||
|
"First byte should be 04 for the uncompressed format, and total size 64"
|
||||||
|
)
|
||||||
|
|
||||||
|
return out[1:]
|
||||||
|
|
||||||
|
class MessageType(Enum):
|
||||||
|
CHALLENGE = 1
|
||||||
|
CHALLENGE_ACCEPTED = 3
|
||||||
|
PEER_PUBKEY = 4
|
||||||
|
PUBKEY_ACCEPTED = 6
|
||||||
|
|
||||||
|
class Message:
|
||||||
|
"""
|
||||||
|
Two types of messages. The first one is for communication that happens before we have
|
||||||
|
a proper symmetric key available. These are fully handled by this file, it's purely
|
||||||
|
to setup the encryption protocol.
|
||||||
|
|
||||||
|
2a2a .... 0000
|
||||||
|
| |> Body checksum
|
||||||
|
| |-----> Body
|
||||||
|
|----------> Magic value for pre-key-exchange
|
||||||
|
|
||||||
|
The second type is for anything after. This can either contain the type 1 message above, or
|
||||||
|
anything else -- at this point we're just wrapping the regular protocol, and we just forward
|
||||||
|
the packets dowm the regular processing path after decrypting them.
|
||||||
|
|
||||||
|
See aes_decrypt() for the format.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, buffer: bytes):
|
||||||
|
self.buffer = buffer
|
||||||
|
self.view = memoryview(self.buffer)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def header(self) -> memoryview:
|
||||||
|
return self.view[:2]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_pre_key_exchange(self) -> bool:
|
||||||
|
return self.header == KEX_MAGIC
|
||||||
|
|
||||||
|
@property
|
||||||
|
def checksum(self) -> memoryview:
|
||||||
|
return self.view[-2:]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def body(self) -> memoryview:
|
||||||
|
return self.view[len(self.header) : -len(self.checksum)]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def data(self) -> memoryview:
|
||||||
|
return self.body[2:]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> int:
|
||||||
|
return MessageType(self.body[0])
|
||||||
|
|
||||||
|
def verify_checksum(self):
|
||||||
|
message_checksum = self.checksum
|
||||||
|
computed_checksum = hexsum(self.body, len(message_checksum))
|
||||||
|
if computed_checksum != message_checksum:
|
||||||
|
_LOGGER.error("Checksum error!")
|
||||||
|
_LOGGER.debug("Checksum OK")
|
||||||
|
|
||||||
|
class BluettiEncryption:
|
||||||
|
# Derived exclusively from data sent over the network
|
||||||
|
# Used for the initial handshake
|
||||||
|
unsecure_aes_key: bytes | None = None
|
||||||
|
|
||||||
|
# Predictably derived from a seed sent by the peer
|
||||||
|
# This is the same for all the messages encrypted
|
||||||
|
# with that key during the connection
|
||||||
|
unsecure_aes_iv: bytes | None = None
|
||||||
|
|
||||||
|
# Proper key exchange gives us another key,
|
||||||
|
# that is used for the remainder of the connection
|
||||||
|
# IV is random per message
|
||||||
|
secure_aes_key: bytes | None = None
|
||||||
|
|
||||||
|
# Received through key exchange
|
||||||
|
# The signing key for the key exchange is well-known
|
||||||
|
peer_pubkey: bytes | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_ready_for_commands(self) -> bool:
|
||||||
|
return self.secure_aes_key is not None and self.peer_pubkey is not None
|
||||||
|
|
||||||
|
def aes_decrypt(self, data: bytes, aes_key: bytes | None, iv: bytes | None):
|
||||||
|
data_len = (data[0] << 8) + data[1]
|
||||||
|
|
||||||
|
if iv is None:
|
||||||
|
iv = hashlib.md5(data[2:6]).digest()
|
||||||
|
encrypted = memoryview(data)[6:]
|
||||||
|
else:
|
||||||
|
encrypted = memoryview(data[2:])
|
||||||
|
|
||||||
|
if len(encrypted) % AES_BLOCK_SIZE != 0:
|
||||||
|
raise ValueError("Data not aligned on aes block size")
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(aes_key), modes.CBC(iv))
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
decrypted = decryptor.update(encrypted) + decryptor.finalize()
|
||||||
|
decrypted = decrypted[:data_len]
|
||||||
|
|
||||||
|
_LOGGER.debug(">PLAIN " + decrypted.hex())
|
||||||
|
return decrypted
|
||||||
|
|
||||||
|
|
||||||
|
def aes_encrypt(self, data: bytes, aes_key: bytes | None, iv: bytes | None):
|
||||||
|
message_header = int.to_bytes(len(data), 2, "big")
|
||||||
|
|
||||||
|
if iv is None:
|
||||||
|
iv_seed = os.urandom(4)
|
||||||
|
iv = hashlib.md5(iv_seed).digest()
|
||||||
|
message_header += iv_seed
|
||||||
|
|
||||||
|
padding = (AES_BLOCK_SIZE - len(data) % AES_BLOCK_SIZE) % AES_BLOCK_SIZE
|
||||||
|
data += bytes(padding)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(aes_key), modes.CBC(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
encrypted = encryptor.update(data) + encryptor.finalize()
|
||||||
|
encrypted = message_header + encrypted
|
||||||
|
|
||||||
|
_LOGGER.debug("PLAIN> " + data.hex())
|
||||||
|
return encrypted
|
||||||
|
|
||||||
|
def msg_challenge(self, message: Message) -> bytes | None:
|
||||||
|
_LOGGER.debug("Received challenge")
|
||||||
|
|
||||||
|
if len(message.data) != 4:
|
||||||
|
_LOGGER.error("Unexpected message length")
|
||||||
|
return None
|
||||||
|
|
||||||
|
self.unsecure_aes_iv = hashlib.md5(message.data[::-1].tobytes()).digest()
|
||||||
|
static_key = bytes.fromhex(LOCAL_AES_KEY)
|
||||||
|
self.unsecure_aes_key = hexxor(self.unsecure_aes_iv, static_key)
|
||||||
|
|
||||||
|
_LOGGER.info("Unsecure iv " + self.unsecure_aes_iv.hex())
|
||||||
|
_LOGGER.info("Unsecure key " + self.unsecure_aes_key.hex())
|
||||||
|
|
||||||
|
body = bytes.fromhex("0204") + self.unsecure_aes_iv[8:12]
|
||||||
|
return b"".join([KEX_MAGIC, body, hexsum(body, 2)])
|
||||||
|
|
||||||
|
def msg_peer_pubkey(self, message: Message) -> bytes | None:
|
||||||
|
_LOGGER.debug("Received peer pubkey, checking signature")
|
||||||
|
data = verify_and_extract_signed_data(message.data, self.unsecure_aes_iv)
|
||||||
|
self.peer_pubkey = pubkey_from_bytes(data)
|
||||||
|
|
||||||
|
_LOGGER.debug("Generating a local keypair")
|
||||||
|
self.my_pubkey, self.my_privkey = generate_keypair()
|
||||||
|
my_pubkey_bytes = pubkey_to_bytes(self.my_pubkey)
|
||||||
|
|
||||||
|
_LOGGER.debug("Signing the local pubkey")
|
||||||
|
signing_secret = int.from_bytes(
|
||||||
|
bytes.fromhex(PRIVATE_KEY_L1), "big"
|
||||||
|
)
|
||||||
|
signing_key = ec.derive_private_key(signing_secret, ec.SECP256R1())
|
||||||
|
to_sign = my_pubkey_bytes + self.unsecure_aes_iv
|
||||||
|
signature = signing_key.sign(to_sign, ec.ECDSA(hashes.SHA256()))
|
||||||
|
raw_signature = der_to_raw_ecdsa(signature)
|
||||||
|
|
||||||
|
body = b"".join([bytes.fromhex("0580"), my_pubkey_bytes, raw_signature])
|
||||||
|
msg = b"".join([KEX_MAGIC, body, hexsum(body, 2)])
|
||||||
|
return self.aes_encrypt(msg, self.unsecure_aes_key, self.unsecure_aes_iv)
|
||||||
|
|
||||||
|
def msg_key_accepted(self, message: Message) -> None:
|
||||||
|
_LOGGER.debug("Received key exchange confirmation, calculating shared secret")
|
||||||
|
|
||||||
|
if len(message.data) != 1:
|
||||||
|
raise ValueError("Unexpected message length")
|
||||||
|
if message.data[0] != 0:
|
||||||
|
raise ValueError("Key acceptance response is not 0")
|
||||||
|
|
||||||
|
self.secure_aes_key = self.my_privkey.exchange(ec.ECDH(), self.peer_pubkey)
|
||||||
|
_LOGGER.info("Secure key " + self.secure_aes_key.hex())
|
||||||
|
|
||||||
|
def getKeyIv(self):
|
||||||
|
return (
|
||||||
|
(self.unsecure_aes_key, self.unsecure_aes_iv)
|
||||||
|
if self.secure_aes_key is None
|
||||||
|
else (self.secure_aes_key, None)
|
||||||
|
)
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.peer_pubkey = None
|
||||||
|
self.secure_aes_key = None
|
||||||
@@ -4,3 +4,8 @@ RESPONSE_TIMEOUT = 5
|
|||||||
WRITE_UUID = "0000ff02-0000-1000-8000-00805f9b34fb"
|
WRITE_UUID = "0000ff02-0000-1000-8000-00805f9b34fb"
|
||||||
NOTIFY_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"
|
NOTIFY_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"
|
||||||
DEVICE_NAME_UUID = "00002a00-0000-1000-8000-00805f9b34fb"
|
DEVICE_NAME_UUID = "00002a00-0000-1000-8000-00805f9b34fb"
|
||||||
|
|
||||||
|
LOCAL_AES_KEY = "459FC535808941F17091E0993EE3E93D"
|
||||||
|
PRIVATE_KEY_L1 = "4F19A16E3E87BDD9BD24D3E5495B88041511943CBC8B969ADE9641D0F56AF337"
|
||||||
|
PUBLIC_KEY_K2 = "3059301306072a8648ce3d020106082a8648ce3d03010703420004A73ABF5D2232C8C1C72E68304343C272495E3A8FD6F30EA96DE2F4B3CE60B251EE21AC667CF8A71E18B46B664EAEFFE3C489F24F695B6411DB7E22CCC85A8594"
|
||||||
|
SECP_256R1_PUBLIC_PREFIX = "3059301306072a8648ce3d020106082a8648ce3d03010703420004"
|
||||||
@@ -1,8 +1,52 @@
|
|||||||
"""AC180P fields."""
|
"""AC180P fields."""
|
||||||
|
|
||||||
from ..base_devices.ProtocolV2Device import ProtocolV2Device
|
from typing import List
|
||||||
|
|
||||||
|
from ..field_enums import ChargingMode
|
||||||
|
from ..utils.commands import ReadHoldingRegisters
|
||||||
|
from ..base_devices.ProtocolV2Device import ProtocolV2Device
|
||||||
|
|
||||||
class AC180P(ProtocolV2Device):
|
class AC180P(ProtocolV2Device):
|
||||||
def __init__(self, address: str, sn: str):
|
def __init__(self, address: str, sn: str):
|
||||||
super().__init__(address, "AC180P", sn)
|
super().__init__(address, "AC180P", sn)
|
||||||
|
|
||||||
|
# Power IO
|
||||||
|
self.struct.add_uint_field('dc_output_power', 140)
|
||||||
|
self.struct.add_uint_field('ac_output_power', 142)
|
||||||
|
self.struct.add_uint_field('dc_input_power', 144)
|
||||||
|
self.struct.add_uint_field('ac_input_power', 146)
|
||||||
|
|
||||||
|
# Input Details (1100 - 1300)
|
||||||
|
self.struct.add_decimal_field('ac_input_voltage', 1314, 1)
|
||||||
|
|
||||||
|
# Controls (2000)
|
||||||
|
self.struct.add_bool_field('ac_output_on_switch', 2011)
|
||||||
|
self.struct.add_bool_field('dc_output_on_switch', 2012)
|
||||||
|
self.struct.add_bool_field('silent_charging_on', 2020) # to be able to choose between normal and silent charging modes
|
||||||
|
self.struct.add_enum_field('charging_mode', 2020, ChargingMode) # can't be set from HA, custom switch needed
|
||||||
|
self.struct.add_bool_field('power_lifting_on', 2021)
|
||||||
|
|
||||||
|
# Controls (2200)
|
||||||
|
self.struct.add_bool_field('grid_enhancement_mode_on', 2225)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
return super().polling_commands + [
|
||||||
|
ReadHoldingRegisters(140, 1),
|
||||||
|
ReadHoldingRegisters(142, 1),
|
||||||
|
ReadHoldingRegisters(144, 1),
|
||||||
|
ReadHoldingRegisters(146, 1),
|
||||||
|
ReadHoldingRegisters(1314, 1),
|
||||||
|
ReadHoldingRegisters(2011, 1),
|
||||||
|
ReadHoldingRegisters(2012, 1),
|
||||||
|
ReadHoldingRegisters(2020, 1),
|
||||||
|
ReadHoldingRegisters(2021, 1),
|
||||||
|
ReadHoldingRegisters(2225, 1),
|
||||||
|
]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def writable_ranges(self) -> List[range]:
|
||||||
|
return super().writable_ranges + [
|
||||||
|
range(2000, 2022),
|
||||||
|
range(2200, 2226)
|
||||||
|
]
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""AC200L fields."""
|
||||||
|
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from ..utils.commands import ReadHoldingRegisters
|
||||||
|
from ..field_enums import AutoSleepMode, OutputMode
|
||||||
|
from ..base_devices.ProtocolV1Device import ProtocolV1Device
|
||||||
|
|
||||||
|
|
||||||
|
class AC200L(ProtocolV1Device):
|
||||||
|
def __init__(self, address: str, sn: str):
|
||||||
|
super().__init__(address, "AC200L", sn)
|
||||||
|
|
||||||
|
# Details
|
||||||
|
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
||||||
|
self.struct.add_decimal_field("internal_ac_voltage", 71, 1, multiplier=10)
|
||||||
|
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
||||||
|
self.struct.add_uint_field("internal_power_one", 73)
|
||||||
|
self.struct.add_decimal_field("internal_ac_frequency", 74, 2, multiplier=10)
|
||||||
|
self.struct.add_uint_field("internal_dc_input_voltage", 86, multiplier=.1)
|
||||||
|
self.struct.add_decimal_field("internal_dc_input_power", 87, 1, multiplier=10)
|
||||||
|
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
||||||
|
|
||||||
|
# Battery packs
|
||||||
|
self.struct.add_uint_field("pack_num_max", 91) # internal
|
||||||
|
self.struct.add_decimal_field("total_battery_voltage", 92, 1, multiplier=.1)
|
||||||
|
self.struct.add_uint_field("pack_num_result", 96) # internal
|
||||||
|
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
||||||
|
self.struct.add_uint_field("pack_battery_percent", 99)
|
||||||
|
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
||||||
|
self.struct.add_version_field("pack_bms_version", 201)
|
||||||
|
|
||||||
|
# Controls
|
||||||
|
self.struct.add_bool_field("power_off", 3060)
|
||||||
|
self.struct.add_enum_field("auto_sleep_mode", 3061, AutoSleepMode)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pack_num_max(self):
|
||||||
|
return 3
|
||||||
|
|
||||||
|
@property
|
||||||
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
return self.struct.get_read_holding_registers(
|
||||||
|
filter=lambda address: address <= 90 or address >= 256 # pack_polling_commands
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def writable_ranges(self) -> List[range]:
|
||||||
|
return super().writable_ranges + [range(3060, 3062)]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
|
return [
|
||||||
|
ReadHoldingRegisters(91, 37),
|
||||||
|
ReadHoldingRegisters(201, 2),
|
||||||
|
]
|
||||||
@@ -13,16 +13,22 @@ class AC200M(ProtocolV1Device):
|
|||||||
|
|
||||||
# Details
|
# Details
|
||||||
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
||||||
self.struct.add_uint_field("internal_ac_voltage", 71)
|
self.struct.add_decimal_field("internal_ac_voltage", 71, 1)
|
||||||
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
||||||
self.struct.add_uint_field("internal_power_one", 73)
|
self.struct.add_uint_field("internal_power_one", 73)
|
||||||
self.struct.add_decimal_field("internal_ac_frequency", 74, 1)
|
self.struct.add_decimal_field("internal_ac_frequency", 74, 2)
|
||||||
self.struct.add_uint_field("internal_dc_input_voltage", 86)
|
self.struct.add_uint_field("internal_dc_input_voltage", 86)
|
||||||
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
||||||
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
||||||
|
|
||||||
# Battery packs
|
# Battery packs
|
||||||
|
self.struct.add_uint_field("pack_num_max", 91) # internal
|
||||||
|
self.struct.add_decimal_field("total_battery_voltage", 92, 1)
|
||||||
|
self.struct.add_uint_field("pack_num_result", 96) # internal
|
||||||
|
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
||||||
|
self.struct.add_uint_field("pack_battery_percent", 99)
|
||||||
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
||||||
|
self.struct.add_version_field("pack_bms_version", 201)
|
||||||
|
|
||||||
# Controls
|
# Controls
|
||||||
self.struct.add_bool_field("power_off", 3060)
|
self.struct.add_bool_field("power_off", 3060)
|
||||||
@@ -34,15 +40,17 @@ class AC200M(ProtocolV1Device):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers(
|
||||||
ReadHoldingRegisters(70, 4),
|
filter=lambda address: address <= 90 or address >= 256 # pack_polling_commands
|
||||||
ReadHoldingRegisters(86, 3),
|
)
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return super().writable_ranges + [range(3060, 3061)]
|
return super().writable_ranges + [range(3060, 3062)]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().pack_polling_commands + [ReadHoldingRegisters(105, 16)]
|
return [
|
||||||
|
ReadHoldingRegisters(91, 37),
|
||||||
|
ReadHoldingRegisters(201, 2),
|
||||||
|
]
|
||||||
@@ -11,27 +11,32 @@ class AC300(ProtocolV1Device):
|
|||||||
def __init__(self, address: str, sn: str):
|
def __init__(self, address: str, sn: str):
|
||||||
super().__init__(address, "AC300", sn)
|
super().__init__(address, "AC300", sn)
|
||||||
|
|
||||||
# Details (matches EP500 + AC500)
|
# Details
|
||||||
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
||||||
self.struct.add_uint_field("internal_ac_voltage", 71)
|
self.struct.add_decimal_field("internal_ac_voltage", 71, 1)
|
||||||
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
||||||
self.struct.add_uint_field("internal_power_one", 73)
|
self.struct.add_int_field("internal_power_one", 73)
|
||||||
self.struct.add_decimal_field("internal_ac_frequency", 74, 1)
|
self.struct.add_decimal_field("internal_ac_frequency", 74, 2)
|
||||||
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
||||||
self.struct.add_uint_field("internal_power_two", 76)
|
self.struct.add_int_field("internal_power_two", 76)
|
||||||
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
||||||
self.struct.add_decimal_field("internal_current_three", 78, 1, (0, 100))
|
self.struct.add_decimal_field("internal_current_three", 78, 1, (0, 100))
|
||||||
self.struct.add_uint_field("internal_power_three", 79)
|
self.struct.add_int_field("internal_power_three", 79)
|
||||||
self.struct.add_decimal_field("ac_input_frequency", 80, 2)
|
self.struct.add_decimal_field("ac_input_frequency", 80, 2)
|
||||||
self.struct.add_uint_field("internal_dc_input_voltage", 86)
|
self.struct.add_uint_field("pv_input_voltage1", 86, multiplier=.1)
|
||||||
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
self.struct.add_decimal_field("pv_input_power1", 87, 1, multiplier=10)
|
||||||
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
self.struct.add_decimal_field("pv_input_current1", 88, 2, multiplier=10)
|
||||||
|
|
||||||
# Battery packs
|
# Battery packs
|
||||||
|
self.struct.add_uint_field("pack_num_max", 91) # internal
|
||||||
|
self.struct.add_decimal_field("total_battery_voltage", 92, 1)
|
||||||
|
self.struct.add_uint_field("pack_num_result", 96) # internal
|
||||||
|
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
||||||
|
self.struct.add_uint_field("pack_battery_percent", 99)
|
||||||
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
||||||
self.struct.add_version_field("pack_bms_version", 201)
|
self.struct.add_version_field("pack_bms_version", 201)
|
||||||
|
|
||||||
# Controls (matches EP500 + AC500)
|
# Controls
|
||||||
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
||||||
self.struct.add_bool_field("split_phase_on", 3004)
|
self.struct.add_bool_field("split_phase_on", 3004)
|
||||||
self.struct.add_enum_field(
|
self.struct.add_enum_field(
|
||||||
@@ -49,21 +54,20 @@ class AC300(ProtocolV1Device):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers(
|
||||||
ReadHoldingRegisters(70, 10),
|
filter=lambda address: address <= 90 or address >= 256 # pack_polling_commands
|
||||||
ReadHoldingRegisters(86, 3),
|
)
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return super().writable_ranges + [
|
return super().writable_ranges + [
|
||||||
range(3001, 3016),
|
range(3001, 3017),
|
||||||
3061,
|
range(3061, 3062),
|
||||||
]
|
]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().pack_polling_commands + [
|
return [
|
||||||
ReadHoldingRegisters(105, 16),
|
ReadHoldingRegisters(91, 37),
|
||||||
ReadHoldingRegisters(201, 2),
|
ReadHoldingRegisters(201, 2),
|
||||||
]
|
]
|
||||||
@@ -11,26 +11,32 @@ class AC500(ProtocolV1Device):
|
|||||||
def __init__(self, address: str, sn: str):
|
def __init__(self, address: str, sn: str):
|
||||||
super().__init__(address, "AC500", sn)
|
super().__init__(address, "AC500", sn)
|
||||||
|
|
||||||
# Details (matches EP500 + AC300)
|
# Details
|
||||||
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
||||||
self.struct.add_uint_field("internal_ac_voltage", 71)
|
self.struct.add_decimal_field("internal_ac_voltage", 71, 1)
|
||||||
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
||||||
self.struct.add_uint_field("internal_power_one", 73)
|
self.struct.add_int_field("internal_power_one", 73)
|
||||||
self.struct.add_decimal_field("internal_ac_frequency", 74, 1)
|
self.struct.add_decimal_field("internal_ac_frequency", 74, 2)
|
||||||
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
||||||
self.struct.add_uint_field("internal_power_two", 76)
|
self.struct.add_int_field("internal_power_two", 76)
|
||||||
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
||||||
self.struct.add_decimal_field("internal_current_three", 78, 1, (0, 100))
|
self.struct.add_decimal_field("internal_current_three", 78, 1, (0, 100))
|
||||||
self.struct.add_uint_field("internal_power_three", 79)
|
self.struct.add_int_field("internal_power_three", 79)
|
||||||
self.struct.add_decimal_field("ac_input_frequency", 80, 2)
|
self.struct.add_decimal_field("ac_input_frequency", 80, 2)
|
||||||
self.struct.add_uint_field("internal_dc_input_voltage", 86)
|
self.struct.add_uint_field("pv_input_voltage1", 86, multiplier=.1)
|
||||||
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
self.struct.add_decimal_field("pv_input_power1", 87, 1, multiplier=10)
|
||||||
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
self.struct.add_decimal_field("pv_input_current1", 88, 2, multiplier=10)
|
||||||
|
|
||||||
# Battery packs (matches EP500)
|
# Battery packs
|
||||||
|
self.struct.add_uint_field("pack_num_max", 91) # internal
|
||||||
|
self.struct.add_decimal_field("total_battery_voltage", 92, 1)
|
||||||
|
self.struct.add_uint_field("pack_num_result", 96) # internal
|
||||||
|
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
||||||
|
self.struct.add_uint_field("pack_battery_percent", 99)
|
||||||
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
||||||
|
self.struct.add_version_field('pack_bms_version', 201)
|
||||||
|
|
||||||
# Controls (matches EP500 + AC300)
|
# Controls
|
||||||
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
||||||
self.struct.add_bool_field("split_phase_on", 3004)
|
self.struct.add_bool_field("split_phase_on", 3004)
|
||||||
self.struct.add_enum_field(
|
self.struct.add_enum_field(
|
||||||
@@ -44,24 +50,24 @@ class AC500(ProtocolV1Device):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_num_max(self):
|
def pack_num_max(self):
|
||||||
return 4
|
return 6
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers(
|
||||||
ReadHoldingRegisters(70, 10),
|
filter=lambda address: address <= 90 or address >= 256 # pack_polling_commands
|
||||||
ReadHoldingRegisters(86, 3),
|
)
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return super().writable_ranges + [
|
return super().writable_ranges + [
|
||||||
range(3001, 3016),
|
range(3001, 3017),
|
||||||
3061,
|
range(3061, 3062),
|
||||||
]
|
]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().pack_polling_commands + [
|
return [
|
||||||
ReadHoldingRegisters(105, 16),
|
ReadHoldingRegisters(91, 37),
|
||||||
|
ReadHoldingRegisters(201, 2),
|
||||||
]
|
]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
"""AC70 fields."""
|
||||||
|
|
||||||
|
from ..base_devices.ProtocolV2Device import ProtocolV2Device
|
||||||
|
|
||||||
|
|
||||||
|
class AC70(ProtocolV2Device):
|
||||||
|
def __init__(self, address: str, sn: str):
|
||||||
|
super().__init__(address, "AC70", sn)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
"""AC70P fields."""
|
||||||
|
|
||||||
|
from ..base_devices.ProtocolV2Device import ProtocolV2Device
|
||||||
|
|
||||||
|
|
||||||
|
class AC70P(ProtocolV2Device):
|
||||||
|
def __init__(self, address: str, sn: str):
|
||||||
|
super().__init__(address, "AC70P", sn)
|
||||||
@@ -25,15 +25,12 @@ class EB3A(ProtocolV1Device):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers()
|
||||||
ReadHoldingRegisters(77, 1),
|
|
||||||
ReadHoldingRegisters(86, 1),
|
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return super().writable_ranges + [
|
return super().writable_ranges + [
|
||||||
3034,
|
range(3034, 3035),
|
||||||
3060,
|
range(3060, 3061),
|
||||||
range(3063, 3066),
|
range(3063, 3067),
|
||||||
]
|
]
|
||||||
@@ -11,12 +11,12 @@ class EP500(ProtocolV1Device):
|
|||||||
def __init__(self, address: str, sn: str):
|
def __init__(self, address: str, sn: str):
|
||||||
super().__init__(address, "EP500", sn)
|
super().__init__(address, "EP500", sn)
|
||||||
|
|
||||||
# Details (matches AC500 + AC300)
|
# Details
|
||||||
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
||||||
self.struct.add_uint_field("internal_ac_voltage", 71)
|
self.struct.add_decimal_field("internal_ac_voltage", 71, 1)
|
||||||
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
||||||
self.struct.add_uint_field("internal_power_one", 73)
|
self.struct.add_uint_field("internal_power_one", 73)
|
||||||
self.struct.add_decimal_field("internal_ac_frequency", 74, 1)
|
self.struct.add_decimal_field("internal_ac_frequency", 74, 2)
|
||||||
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
||||||
self.struct.add_uint_field("internal_power_two", 76)
|
self.struct.add_uint_field("internal_power_two", 76)
|
||||||
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
||||||
@@ -27,10 +27,16 @@ class EP500(ProtocolV1Device):
|
|||||||
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
||||||
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
||||||
|
|
||||||
# Battery packs (matches AC500)
|
# Battery packs
|
||||||
|
self.struct.add_uint_field("pack_num_max", 91) # internal
|
||||||
|
self.struct.add_decimal_field("total_battery_voltage", 92, 1)
|
||||||
|
self.struct.add_uint_field("pack_num_result", 96) # internal
|
||||||
|
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
||||||
|
self.struct.add_uint_field("pack_battery_percent", 99)
|
||||||
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
||||||
|
self.struct.add_version_field("pack_bms_version", 201)
|
||||||
|
|
||||||
# Controls (matches AC500 + AC300)
|
# Controls
|
||||||
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
||||||
self.struct.add_bool_field("split_phase_on", 3004)
|
self.struct.add_bool_field("split_phase_on", 3004)
|
||||||
self.struct.add_enum_field(
|
self.struct.add_enum_field(
|
||||||
@@ -44,20 +50,20 @@ class EP500(ProtocolV1Device):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers(
|
||||||
ReadHoldingRegisters(70, 10),
|
filter=lambda address: address <= 90 or address >= 256 # pack_polling_commands
|
||||||
ReadHoldingRegisters(86, 3),
|
)
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return super().writable_ranges + [
|
return super().writable_ranges + [
|
||||||
range(3001, 3016),
|
range(3001, 3017),
|
||||||
3061,
|
range(3061, 3062),
|
||||||
]
|
]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().pack_polling_commands + [
|
return [
|
||||||
ReadHoldingRegisters(105, 16),
|
ReadHoldingRegisters(91, 37),
|
||||||
|
ReadHoldingRegisters(201, 2),
|
||||||
]
|
]
|
||||||
@@ -11,12 +11,12 @@ class EP500P(ProtocolV1Device):
|
|||||||
def __init__(self, address: str, sn: str):
|
def __init__(self, address: str, sn: str):
|
||||||
super().__init__(address, "EP500P", sn)
|
super().__init__(address, "EP500P", sn)
|
||||||
|
|
||||||
# Details (matches AC500 + AC300)
|
# Details
|
||||||
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
self.struct.add_enum_field("ac_output_mode", 70, OutputMode)
|
||||||
self.struct.add_uint_field("internal_ac_voltage", 71)
|
self.struct.add_decimal_field("internal_ac_voltage", 71, 1)
|
||||||
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
self.struct.add_decimal_field("internal_current_one", 72, 1)
|
||||||
self.struct.add_uint_field("internal_power_one", 73)
|
self.struct.add_uint_field("internal_power_one", 73)
|
||||||
self.struct.add_decimal_field("internal_ac_frequency", 74, 1)
|
self.struct.add_decimal_field("internal_ac_frequency", 74, 2)
|
||||||
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
self.struct.add_decimal_field("internal_current_two", 75, 1)
|
||||||
self.struct.add_uint_field("internal_power_two", 76)
|
self.struct.add_uint_field("internal_power_two", 76)
|
||||||
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
self.struct.add_decimal_field("ac_input_voltage", 77, 1)
|
||||||
@@ -27,10 +27,16 @@ class EP500P(ProtocolV1Device):
|
|||||||
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
self.struct.add_decimal_field("internal_dc_input_power", 87, 1)
|
||||||
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
self.struct.add_decimal_field("internal_dc_input_current", 88, 2)
|
||||||
|
|
||||||
# Battery packs (matches AC500)
|
# Battery packs
|
||||||
|
self.struct.add_uint_field("pack_num_max", 91) # internal
|
||||||
|
self.struct.add_decimal_field("total_battery_voltage", 92, 1)
|
||||||
|
self.struct.add_uint_field("pack_num_result", 96) # internal
|
||||||
|
self.struct.add_decimal_field("pack_voltage", 98, 2) # Full pack voltage
|
||||||
|
self.struct.add_uint_field("pack_battery_percent", 99)
|
||||||
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
self.struct.add_decimal_array_field("cell_voltages", 105, 16, 2) # internal
|
||||||
|
self.struct.add_version_field("pack_bms_version", 201)
|
||||||
|
|
||||||
# Controls (matches AC500 + AC300)
|
# Controls
|
||||||
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
self.struct.add_enum_field("ups_mode", 3001, UpsMode)
|
||||||
self.struct.add_bool_field("split_phase_on", 3004)
|
self.struct.add_bool_field("split_phase_on", 3004)
|
||||||
self.struct.add_enum_field(
|
self.struct.add_enum_field(
|
||||||
@@ -44,20 +50,20 @@ class EP500P(ProtocolV1Device):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers(
|
||||||
ReadHoldingRegisters(70, 10),
|
filter=lambda address: address <= 90 or address >= 256 # pack_polling_commands
|
||||||
ReadHoldingRegisters(86, 3),
|
)
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def writable_ranges(self) -> List[range]:
|
def writable_ranges(self) -> List[range]:
|
||||||
return super().writable_ranges + [
|
return super().writable_ranges + [
|
||||||
range(3001, 3016),
|
range(3001, 3017),
|
||||||
3061,
|
range(3061, 3062),
|
||||||
]
|
]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().pack_polling_commands + [
|
return [
|
||||||
ReadHoldingRegisters(105, 16),
|
ReadHoldingRegisters(91, 37),
|
||||||
|
ReadHoldingRegisters(201, 2),
|
||||||
]
|
]
|
||||||
@@ -62,6 +62,22 @@ class EP600(ProtocolV2Device):
|
|||||||
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)
|
||||||
|
|
||||||
|
# KM - Consumption
|
||||||
|
self.struct.add_int_field("consumption_power_phase1", 1430)
|
||||||
|
self.struct.add_int_field("consumption_power_phase2", 1436)
|
||||||
|
self.struct.add_int_field("consumption_power_phase3", 1442)
|
||||||
|
self.struct.add_decimal_field("consumption_voltage_phase1", 1431, 1)
|
||||||
|
self.struct.add_decimal_field("consumption_voltage_phase2", 1437, 1)
|
||||||
|
self.struct.add_decimal_field("consumption_voltage_phase3", 1443, 1)
|
||||||
|
self.struct.add_decimal_field("consumption_current_phase1", 1432, 1)
|
||||||
|
self.struct.add_decimal_field("consumption_current_phase2", 1438, 1)
|
||||||
|
self.struct.add_decimal_field("consumption_current_phase3", 1444, 1)
|
||||||
|
|
||||||
|
# KM - Totals
|
||||||
|
self.struct.add_uint_field('pv_input_power_all', 144) # Total PV in
|
||||||
|
self.struct.add_uint_field('consumption_power_all', 142) # Total AC out
|
||||||
|
self.struct.add_uint_field('grid_power_all', 146) # Total Grid in - value only +/- unknown
|
||||||
|
|
||||||
# Statistics
|
# Statistics
|
||||||
self.struct.add_decimal_field(
|
self.struct.add_decimal_field(
|
||||||
"total_ac_consumption", 152, 1
|
"total_ac_consumption", 152, 1
|
||||||
@@ -79,36 +95,6 @@ class EP600(ProtocolV2Device):
|
|||||||
self.struct.add_version_field("safety_module_version", 6181) # internal
|
self.struct.add_version_field("safety_module_version", 6181) # internal
|
||||||
self.struct.add_version_field("high_voltage_module_version", 6184) # internal
|
self.struct.add_version_field("high_voltage_module_version", 6184) # internal
|
||||||
|
|
||||||
# @property
|
|
||||||
# def pack_num_max(self):
|
|
||||||
# return 16
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
def polling_commands(self) -> List[ReadHoldingRegisters]:
|
||||||
return super().polling_commands + [
|
return self.struct.get_read_holding_registers()
|
||||||
ReadHoldingRegisters(2022, 2),
|
|
||||||
ReadHoldingRegisters(2213, 5),
|
|
||||||
ReadHoldingRegisters(1212, 3),
|
|
||||||
ReadHoldingRegisters(1220, 3),
|
|
||||||
ReadHoldingRegisters(1228, 3),
|
|
||||||
ReadHoldingRegisters(1236, 3),
|
|
||||||
ReadHoldingRegisters(1244, 3),
|
|
||||||
ReadHoldingRegisters(1300, 1),
|
|
||||||
ReadHoldingRegisters(1313, 3),
|
|
||||||
ReadHoldingRegisters(1319, 3),
|
|
||||||
ReadHoldingRegisters(1325, 3),
|
|
||||||
ReadHoldingRegisters(1500, 1),
|
|
||||||
ReadHoldingRegisters(1510, 3),
|
|
||||||
ReadHoldingRegisters(1517, 3),
|
|
||||||
ReadHoldingRegisters(1524, 3),
|
|
||||||
ReadHoldingRegisters(152, 1),
|
|
||||||
ReadHoldingRegisters(156, 1),
|
|
||||||
ReadHoldingRegisters(158, 1),
|
|
||||||
]
|
|
||||||
|
|
||||||
# @property
|
|
||||||
# def pack_polling_commands(self) -> List[ReadHoldingRegisters]:
|
|
||||||
# return super().pack_polling_commands + [
|
|
||||||
# ReadHoldingRegisters(6101, 10),
|
|
||||||
# ReadHoldingRegisters(6175, 12),
|
|
||||||
# ]
|
|
||||||
@@ -18,7 +18,6 @@ class FieldType(Enum):
|
|||||||
NUMERIC = auto()
|
NUMERIC = auto()
|
||||||
BOOL = auto()
|
BOOL = auto()
|
||||||
ENUM = auto()
|
ENUM = auto()
|
||||||
BUTTON = auto()
|
|
||||||
|
|
||||||
|
|
||||||
class FieldAttributes:
|
class FieldAttributes:
|
||||||
@@ -126,6 +125,14 @@ FIELD_ATTRIBUTES: dict[str, FieldAttributes] = {
|
|||||||
"ac_input_power": PowerFieldAttributes("AC Input Power"),
|
"ac_input_power": PowerFieldAttributes("AC Input Power"),
|
||||||
"ac_output_power": PowerFieldAttributes("AC Output Power"),
|
"ac_output_power": PowerFieldAttributes("AC Output Power"),
|
||||||
"dc_output_power": PowerFieldAttributes("DC Output Power"),
|
"dc_output_power": PowerFieldAttributes("DC Output Power"),
|
||||||
|
"dsp_version": FieldAttributes(
|
||||||
|
type=FieldType.NUMERIC,
|
||||||
|
name=f"DSP Version",
|
||||||
|
),
|
||||||
|
"arm_version": FieldAttributes(
|
||||||
|
type=FieldType.NUMERIC,
|
||||||
|
name=f"ARM Version",
|
||||||
|
),
|
||||||
"power_generation": EnergyFieldAttributes("Total Power Generation"),
|
"power_generation": EnergyFieldAttributes("Total Power Generation"),
|
||||||
"total_battery_percent": FieldAttributes(
|
"total_battery_percent": FieldAttributes(
|
||||||
type=FieldType.NUMERIC,
|
type=FieldType.NUMERIC,
|
||||||
@@ -218,9 +225,29 @@ FIELD_ATTRIBUTES: dict[str, FieldAttributes] = {
|
|||||||
"total_ac_consumption": EnergyFieldAttributes("Total Load Consumption"),
|
"total_ac_consumption": EnergyFieldAttributes("Total Load Consumption"),
|
||||||
"total_grid_consumption": EnergyFieldAttributes("Total Grid Consumption"),
|
"total_grid_consumption": EnergyFieldAttributes("Total Grid Consumption"),
|
||||||
"total_grid_feed": EnergyFieldAttributes("Total Grid Feed"),
|
"total_grid_feed": EnergyFieldAttributes("Total Grid Feed"),
|
||||||
|
|
||||||
|
# KM - Consumption
|
||||||
|
"consumption_power_phase1": PowerFieldAttributes("Consumption Power Phase 1"),
|
||||||
|
"consumption_power_phase2": PowerFieldAttributes("Consumption Power Phase 2"),
|
||||||
|
"consumption_power_phase3": PowerFieldAttributes("Consumption Power Phase 3"),
|
||||||
|
"consumption_voltage_phase1": VoltageFieldAttributes("Consumption Voltage Phase 1"),
|
||||||
|
"consumption_voltage_phase2": VoltageFieldAttributes("Consumption Voltage Phase 2"),
|
||||||
|
"consumption_voltage_phase3": VoltageFieldAttributes("Consumption Voltage Phase 3"),
|
||||||
|
"consumption_current_phase1": CurrentFieldAttributes("Consumption Current Phase 1"),
|
||||||
|
"consumption_current_phase2": CurrentFieldAttributes("Consumption Current Phase 2"),
|
||||||
|
"consumption_current_phase3": CurrentFieldAttributes("Consumption Current Phase 3"),
|
||||||
|
# KM - Consumption end
|
||||||
|
|
||||||
|
# KM - Totals
|
||||||
|
"pv_input_power_all": PowerFieldAttributes("PV Input Power All"),
|
||||||
|
"consumption_power_all": PowerFieldAttributes("Consumption Power All"),
|
||||||
|
"grid_power_all": PowerFieldAttributes("Grid Power All"),
|
||||||
|
# KM - Totals end
|
||||||
|
|
||||||
|
|
||||||
# Device specific controls
|
# Device specific controls
|
||||||
"power_off": FieldAttributes(
|
"power_off": FieldAttributes(
|
||||||
type=FieldType.BUTTON,
|
type=FieldType.BOOL,
|
||||||
setter=True,
|
setter=True,
|
||||||
name="Power Off",
|
name="Power Off",
|
||||||
),
|
),
|
||||||
@@ -294,9 +321,19 @@ FIELD_ATTRIBUTES: dict[str, FieldAttributes] = {
|
|||||||
),
|
),
|
||||||
"power_lifting_on": FieldAttributes(
|
"power_lifting_on": FieldAttributes(
|
||||||
type=FieldType.BOOL,
|
type=FieldType.BOOL,
|
||||||
setter=False, # Disabled for safety reasons
|
setter=True,
|
||||||
name="Power Lifting",
|
name="Power Lifting",
|
||||||
),
|
),
|
||||||
|
"grid_enhancement_mode_on": FieldAttributes(
|
||||||
|
type=FieldType.BOOL,
|
||||||
|
setter=True,
|
||||||
|
name="Grid Enhancement Mode",
|
||||||
|
),
|
||||||
|
"silent_charging_on": FieldAttributes(
|
||||||
|
type=FieldType.BOOL,
|
||||||
|
setter=True,
|
||||||
|
name="Silent Charging",
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,11 @@
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
from ..devices.ac60 import AC60
|
from ..devices.ac60 import AC60
|
||||||
|
from ..devices.ac70 import AC70
|
||||||
|
from ..devices.ac70p import AC70P
|
||||||
from ..devices.ac180 import AC180
|
from ..devices.ac180 import AC180
|
||||||
from ..devices.ac180p import AC180P
|
from ..devices.ac180p import AC180P
|
||||||
|
from ..devices.ac200l import AC200L
|
||||||
from ..devices.ac200m import AC200M
|
from ..devices.ac200m import AC200M
|
||||||
from ..devices.ac300 import AC300
|
from ..devices.ac300 import AC300
|
||||||
from ..devices.ac500 import AC500
|
from ..devices.ac500 import AC500
|
||||||
@@ -16,7 +19,7 @@ from ..devices.ep760 import EP760
|
|||||||
from ..devices.ep800 import EP800
|
from ..devices.ep800 import EP800
|
||||||
|
|
||||||
DEVICE_NAME_RE = re.compile(
|
DEVICE_NAME_RE = re.compile(
|
||||||
r"^(AC60|AC180|AC180P|AC200M|AC300|AC500|EB3A|EP500|EP500P|EP600|EP760|EP800)(\d+)$"
|
r"^(AC60|AC70|AC70P|AC180|AC180P|AC200L|AC200M|AC300|AC500|EB3A|EP500|EP500P|EP600|EP760|EP800)(\d+)$"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -24,10 +27,16 @@ def build_device(address: str, name: str):
|
|||||||
match = DEVICE_NAME_RE.match(name)
|
match = DEVICE_NAME_RE.match(name)
|
||||||
if match[1] == "AC60":
|
if match[1] == "AC60":
|
||||||
return AC60(address, match[2])
|
return AC60(address, match[2])
|
||||||
|
if match[1] == "AC70":
|
||||||
|
return AC70(address, match[2])
|
||||||
|
if match[1] == "AC70P":
|
||||||
|
return AC70P(address, match[2])
|
||||||
if match[1] == "AC180":
|
if match[1] == "AC180":
|
||||||
return AC180(address, match[2])
|
return AC180(address, match[2])
|
||||||
if match[1] == "AC180P":
|
if match[1] == "AC180P":
|
||||||
return AC180P(address, match[2])
|
return AC180P(address, match[2])
|
||||||
|
if match[1] == "AC200L":
|
||||||
|
return AC200L(address, match[2])
|
||||||
if match[1] == "AC200M":
|
if match[1] == "AC200M":
|
||||||
return AC200M(address, match[2])
|
return AC200M(address, match[2])
|
||||||
if match[1] == "AC300":
|
if match[1] == "AC300":
|
||||||
@@ -50,6 +59,6 @@ def build_device(address: str, name: str):
|
|||||||
|
|
||||||
def get_type_by_bt_name(bt_name: str):
|
def get_type_by_bt_name(bt_name: str):
|
||||||
match = DEVICE_NAME_RE.match(bt_name)
|
match = DEVICE_NAME_RE.match(bt_name)
|
||||||
if match is None or len(match) < 2:
|
if match is None:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
return match[1]
|
return match[1]
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
from .commands import ReadHoldingRegisters
|
||||||
import struct
|
import struct
|
||||||
from typing import Any, List, Optional, Tuple, Type
|
from typing import Any, List, Optional, Tuple, Type
|
||||||
|
|
||||||
@@ -30,12 +31,15 @@ class DeviceField:
|
|||||||
|
|
||||||
|
|
||||||
class UintField(DeviceField):
|
class UintField(DeviceField):
|
||||||
def __init__(self, name: str, address: int, range: Optional[Tuple[int, int]]):
|
def __init__(self, name: str, address: int, range: Optional[Tuple[int, int]], multiplier: float):
|
||||||
self.range = range
|
self.range = range
|
||||||
|
self.multiplier = multiplier
|
||||||
super().__init__(name, address, 1)
|
super().__init__(name, address, 1)
|
||||||
|
|
||||||
def parse(self, data: bytes) -> int:
|
def parse(self, data: bytes) -> int:
|
||||||
return struct.unpack("!H", data)[0]
|
val = struct.unpack("!H", data)[0]
|
||||||
|
|
||||||
|
return val * self.multiplier
|
||||||
|
|
||||||
def in_range(self, val: int) -> bool:
|
def in_range(self, val: int) -> bool:
|
||||||
if self.range is None:
|
if self.range is None:
|
||||||
@@ -79,15 +83,16 @@ class EnumField(DeviceField):
|
|||||||
|
|
||||||
class DecimalField(DeviceField):
|
class DecimalField(DeviceField):
|
||||||
def __init__(
|
def __init__(
|
||||||
self, name: str, address: int, scale: int, range: Optional[Tuple[int, int]]
|
self, name: str, address: int, scale: int, range: Optional[Tuple[int, int]], multiplier: float
|
||||||
):
|
):
|
||||||
self.scale = scale
|
self.scale = scale
|
||||||
self.range = range
|
self.range = range
|
||||||
|
self.multiplier = multiplier
|
||||||
super().__init__(name, address, 1)
|
super().__init__(name, address, 1)
|
||||||
|
|
||||||
def parse(self, data: bytes) -> Decimal:
|
def parse(self, data: bytes) -> Decimal:
|
||||||
val = Decimal(struct.unpack("!H", data)[0])
|
val = Decimal(struct.unpack("!H", data)[0])
|
||||||
return val / 10 ** self.scale
|
return (val / 10 ** self.scale) * Decimal(self.multiplier)
|
||||||
|
|
||||||
def in_range(self, val: Decimal) -> bool:
|
def in_range(self, val: Decimal) -> bool:
|
||||||
if self.range is None:
|
if self.range is None:
|
||||||
@@ -144,8 +149,8 @@ class DeviceStruct:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.fields = []
|
self.fields = []
|
||||||
|
|
||||||
def add_uint_field(self, name: str, address: int, range: Tuple[int, int] = None):
|
def add_uint_field(self, name: str, address: int, range: Tuple[int, int] = None, multiplier: float = 1):
|
||||||
self.fields.append(UintField(name, address, range))
|
self.fields.append(UintField(name, address, range, multiplier))
|
||||||
|
|
||||||
def add_int_field(self, name: str, address: int, range: Tuple[int, int] = None):
|
def add_int_field(self, name: str, address: int, range: Tuple[int, int] = None):
|
||||||
self.fields.append(IntField(name, address, range))
|
self.fields.append(IntField(name, address, range))
|
||||||
@@ -157,9 +162,9 @@ class DeviceStruct:
|
|||||||
self.fields.append(EnumField(name, address, enum))
|
self.fields.append(EnumField(name, address, enum))
|
||||||
|
|
||||||
def add_decimal_field(
|
def add_decimal_field(
|
||||||
self, name: str, address: int, scale: int, range: Tuple[int, int] = None
|
self, name: str, address: int, scale: int, range: Tuple[int, int] = None, multiplier: float = 1
|
||||||
):
|
):
|
||||||
self.fields.append(DecimalField(name, address, scale, range))
|
self.fields.append(DecimalField(name, address, scale, range, multiplier))
|
||||||
|
|
||||||
def add_decimal_array_field(self, name: str, address: int, size: int, scale: int):
|
def add_decimal_array_field(self, name: str, address: int, size: int, scale: int):
|
||||||
self.fields.append(DecimalArrayField(name, address, size, scale))
|
self.fields.append(DecimalArrayField(name, address, size, scale))
|
||||||
@@ -176,6 +181,35 @@ class DeviceStruct:
|
|||||||
def add_sn_field(self, name: str, address: int):
|
def add_sn_field(self, name: str, address: int):
|
||||||
self.fields.append(SerialNumberField(name, address))
|
self.fields.append(SerialNumberField(name, address))
|
||||||
|
|
||||||
|
def get_read_holding_registers(self, tolerance=20, filter=lambda address: True):
|
||||||
|
address_set = set()
|
||||||
|
for field in self.fields:
|
||||||
|
for address in range(field.address, field.address + field.size):
|
||||||
|
address_set.add(address)
|
||||||
|
# Filter out addresses that we specificly
|
||||||
|
# specified to exclude.
|
||||||
|
for address in set(address_set):
|
||||||
|
if not filter(address):
|
||||||
|
address_set.remove(address)
|
||||||
|
# Fast path: no addresses -> no commands.
|
||||||
|
if not address_set:
|
||||||
|
return []
|
||||||
|
|
||||||
|
commands = []
|
||||||
|
|
||||||
|
address_list = sorted(address_set)
|
||||||
|
start = address_list[0]
|
||||||
|
last = address_list[0]
|
||||||
|
for address in address_list[1:]:
|
||||||
|
# Create a new group if there's a gap
|
||||||
|
# in the addresses.
|
||||||
|
if address >= last + tolerance:
|
||||||
|
commands.append(ReadHoldingRegisters(start, last - start + 1))
|
||||||
|
start = address
|
||||||
|
last = address
|
||||||
|
commands.append(ReadHoldingRegisters(start, last - start + 1))
|
||||||
|
return commands
|
||||||
|
|
||||||
def parse(self, starting_address: int, data: bytes) -> dict:
|
def parse(self, starting_address: int, data: bytes) -> dict:
|
||||||
# Offsets and size are counted in 2 byte chunks, so for the range we
|
# Offsets and size are counted in 2 byte chunks, so for the range we
|
||||||
# need to divide the byte size by 2
|
# need to divide the byte size by 2
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from homeassistant.components.bluetooth import (
|
|||||||
BluetoothServiceInfoBleak,
|
BluetoothServiceInfoBleak,
|
||||||
async_discovered_service_info,
|
async_discovered_service_info,
|
||||||
)
|
)
|
||||||
from homeassistant.const import CONF_ADDRESS, CONF_NAME
|
from homeassistant.const import CONF_ADDRESS, CONF_NAME, CONF_TYPE
|
||||||
from homeassistant.data_entry_flow import FlowResult
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
from homeassistant.helpers import selector
|
from homeassistant.helpers import selector
|
||||||
|
|
||||||
@@ -22,6 +22,7 @@ from .bluetti_bt_lib.utils.device_builder import get_type_by_bt_name
|
|||||||
from .bluetti_bt_lib.bluetooth.device_recognizer import recognize_device
|
from .bluetti_bt_lib.bluetooth.device_recognizer import recognize_device
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
|
CONF_ENCRYPTION,
|
||||||
CONF_MAX_RETRIES,
|
CONF_MAX_RETRIES,
|
||||||
CONF_PERSISTENT_CONN,
|
CONF_PERSISTENT_CONN,
|
||||||
CONF_POLLING_INTERVAL,
|
CONF_POLLING_INTERVAL,
|
||||||
@@ -48,11 +49,20 @@ class BluettiConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
await self.async_set_unique_id(discovery_info.address)
|
await self.async_set_unique_id(discovery_info.address)
|
||||||
self._abort_if_unique_id_configured()
|
self._abort_if_unique_id_configured()
|
||||||
|
|
||||||
|
if isinstance(discovery_info.name, str):
|
||||||
|
name = re.sub("[^A-Z0-9]+", "", discovery_info.name)
|
||||||
|
discovery_info.manufacturer_data = {
|
||||||
|
CONF_TYPE: get_type_by_bt_name(name)
|
||||||
|
}
|
||||||
|
|
||||||
# Get device type if needed
|
# Get device type if needed
|
||||||
if isinstance(discovery_info.name, str) and discovery_info.name.startswith("PBOX"):
|
if isinstance(discovery_info.name, str) and discovery_info.name.startswith("PBOX"):
|
||||||
bleak_device = BleakClient(discovery_info.device)
|
bleak_device = BleakClient(discovery_info.device)
|
||||||
device_type = await recognize_device(bleak_device, self.hass.loop.create_future)
|
device_type = await recognize_device(bleak_device, self.hass.loop.create_future)
|
||||||
_LOGGER.info("Device identified as %s", device_type)
|
_LOGGER.info("Device identified as %s", device_type)
|
||||||
|
discovery_info.manufacturer_data = {
|
||||||
|
CONF_TYPE: device_type.strip(),
|
||||||
|
}
|
||||||
discovery_info.name = discovery_info.name.replace("PBOX", device_type.strip())
|
discovery_info.name = discovery_info.name.replace("PBOX", device_type.strip())
|
||||||
|
|
||||||
self._discovery_info = discovery_info
|
self._discovery_info = discovery_info
|
||||||
@@ -76,6 +86,7 @@ class BluettiConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
data={
|
data={
|
||||||
CONF_ADDRESS: discovery_info.address,
|
CONF_ADDRESS: discovery_info.address,
|
||||||
CONF_NAME: name,
|
CONF_NAME: name,
|
||||||
|
CONF_TYPE: discovery_info.manufacturer_data.get(CONF_TYPE, "Unknown"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -140,7 +151,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
|
|||||||
if user_input[CONF_MAX_RETRIES] < 1:
|
if user_input[CONF_MAX_RETRIES] < 1:
|
||||||
return self.async_abort(reason="invalid_retries")
|
return self.async_abort(reason="invalid_retries")
|
||||||
|
|
||||||
changed = self.hass.config_entries.async_update_entry(
|
self.hass.config_entries.async_update_entry(
|
||||||
self.config_entry,
|
self.config_entry,
|
||||||
data={
|
data={
|
||||||
**self.config_entry.data,
|
**self.config_entry.data,
|
||||||
@@ -150,14 +161,10 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
|
|||||||
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
|
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
|
||||||
CONF_POLLING_TIMEOUT: user_input[CONF_POLLING_TIMEOUT],
|
CONF_POLLING_TIMEOUT: user_input[CONF_POLLING_TIMEOUT],
|
||||||
CONF_MAX_RETRIES: user_input[CONF_MAX_RETRIES],
|
CONF_MAX_RETRIES: user_input[CONF_MAX_RETRIES],
|
||||||
|
CONF_ENCRYPTION: user_input[CONF_ENCRYPTION],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
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(
|
return self.async_create_entry(
|
||||||
title="",
|
title="",
|
||||||
data={
|
data={
|
||||||
@@ -166,6 +173,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
|
|||||||
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
|
CONF_POLLING_INTERVAL: user_input[CONF_POLLING_INTERVAL],
|
||||||
CONF_POLLING_TIMEOUT: user_input[CONF_POLLING_TIMEOUT],
|
CONF_POLLING_TIMEOUT: user_input[CONF_POLLING_TIMEOUT],
|
||||||
CONF_MAX_RETRIES: user_input[CONF_MAX_RETRIES],
|
CONF_MAX_RETRIES: user_input[CONF_MAX_RETRIES],
|
||||||
|
CONF_ENCRYPTION: user_input[CONF_ENCRYPTION],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -193,6 +201,10 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
|
|||||||
CONF_MAX_RETRIES,
|
CONF_MAX_RETRIES,
|
||||||
default=self.config_entry.data.get(CONF_MAX_RETRIES, 5),
|
default=self.config_entry.data.get(CONF_MAX_RETRIES, 5),
|
||||||
): int,
|
): int,
|
||||||
|
vol.Required(
|
||||||
|
CONF_ENCRYPTION,
|
||||||
|
default=self.config_entry.data.get(CONF_ENCRYPTION, False),
|
||||||
|
): selector.BooleanSelector(),
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -9,6 +9,7 @@ CONF_PERSISTENT_CONN = "persistent_conn"
|
|||||||
CONF_POLLING_INTERVAL = "polling_interval"
|
CONF_POLLING_INTERVAL = "polling_interval"
|
||||||
CONF_POLLING_TIMEOUT = "polling_timeout"
|
CONF_POLLING_TIMEOUT = "polling_timeout"
|
||||||
CONF_MAX_RETRIES = "max_retries"
|
CONF_MAX_RETRIES = "max_retries"
|
||||||
|
CONF_ENCRYPTION = "use_encryption"
|
||||||
|
|
||||||
DATA_COORDINATOR = "coordinator"
|
DATA_COORDINATOR = "coordinator"
|
||||||
DATA_POLLING_RUNNING = "polling_running"
|
DATA_POLLING_RUNNING = "polling_running"
|
||||||
@@ -23,11 +24,17 @@ SUPPORTED_MODELS = [
|
|||||||
"EP500P",
|
"EP500P",
|
||||||
"EP600",
|
"EP600",
|
||||||
"EP760",
|
"EP760",
|
||||||
|
"AC180P",
|
||||||
]
|
]
|
||||||
|
|
||||||
CONTROL_FIELDS = [
|
CONTROL_FIELDS = [
|
||||||
"ac_output_on",
|
"ac_output_on_switch",
|
||||||
"dc_output_on",
|
"dc_output_on_switch",
|
||||||
|
"power_off",
|
||||||
|
"eco_on",
|
||||||
|
"power_lifting_on",
|
||||||
|
"grid_enhancement_mode_on",
|
||||||
|
"silent_charging_on",
|
||||||
]
|
]
|
||||||
|
|
||||||
DIAGNOSTIC_FIELDS = [
|
DIAGNOSTIC_FIELDS = [
|
||||||
@@ -36,10 +43,13 @@ DIAGNOSTIC_FIELDS = [
|
|||||||
"max_ac_output_power",
|
"max_ac_output_power",
|
||||||
"max_ac_output_current",
|
"max_ac_output_current",
|
||||||
"bcu_version",
|
"bcu_version",
|
||||||
|
"dsp_version",
|
||||||
|
"arm_version",
|
||||||
"safety_module_version",
|
"safety_module_version",
|
||||||
"high_voltage_module_version",
|
"high_voltage_module_version",
|
||||||
"power_generation",
|
"power_generation",
|
||||||
"total_ac_consumption",
|
"total_ac_consumption",
|
||||||
"total_grid_consumption",
|
"total_grid_consumption",
|
||||||
"total_grid_feed",
|
"total_grid_feed",
|
||||||
|
"ac_input_voltage",
|
||||||
]
|
]
|
||||||
@@ -33,6 +33,7 @@ class PollingCoordinator(DataUpdateCoordinator):
|
|||||||
persistent_conn: bool,
|
persistent_conn: bool,
|
||||||
polling_timeout: int,
|
polling_timeout: int,
|
||||||
max_retries: int,
|
max_retries: int,
|
||||||
|
encrypted: bool,
|
||||||
):
|
):
|
||||||
"""Initialize coordinator."""
|
"""Initialize coordinator."""
|
||||||
super().__init__(
|
super().__init__(
|
||||||
@@ -42,6 +43,8 @@ class PollingCoordinator(DataUpdateCoordinator):
|
|||||||
update_interval=timedelta(seconds=polling_interval),
|
update_interval=timedelta(seconds=polling_interval),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
self.address = address
|
||||||
|
|
||||||
# Create client
|
# Create client
|
||||||
self.logger.debug("Creating client")
|
self.logger.debug("Creating client")
|
||||||
device = bluetooth.async_ble_device_from_address(hass, address)
|
device = bluetooth.async_ble_device_from_address(hass, address)
|
||||||
@@ -58,6 +61,7 @@ class PollingCoordinator(DataUpdateCoordinator):
|
|||||||
persistent_conn=persistent_conn,
|
persistent_conn=persistent_conn,
|
||||||
polling_timeout=polling_timeout,
|
polling_timeout=polling_timeout,
|
||||||
max_retries=max_retries,
|
max_retries=max_retries,
|
||||||
|
encrypted=encrypted,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _async_update_data(self):
|
async def _async_update_data(self):
|
||||||
@@ -67,4 +71,10 @@ class PollingCoordinator(DataUpdateCoordinator):
|
|||||||
so entities can quickly look up their data.
|
so entities can quickly look up their data.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Check if device is connected
|
||||||
|
if bluetooth.async_address_present(self.hass, self.address, connectable=True) is False:
|
||||||
|
self.logger.warning("Device not connected")
|
||||||
|
self.last_update_success = False
|
||||||
|
return None
|
||||||
|
|
||||||
return await self.reader.read_data()
|
return await self.reader.read_data()
|
||||||
@@ -3,7 +3,9 @@
|
|||||||
"name": "Bluetti BT",
|
"name": "Bluetti BT",
|
||||||
"bluetooth": [
|
"bluetooth": [
|
||||||
{ "local_name": "AC60*" },
|
{ "local_name": "AC60*" },
|
||||||
|
{ "local_name": "AC70*" },
|
||||||
{ "local_name": "AC180*" },
|
{ "local_name": "AC180*" },
|
||||||
|
{ "local_name": "AC200L*" },
|
||||||
{ "local_name": "AC200M*" },
|
{ "local_name": "AC200M*" },
|
||||||
{ "local_name": "AC300*" },
|
{ "local_name": "AC300*" },
|
||||||
{ "local_name": "AC500*" },
|
{ "local_name": "AC500*" },
|
||||||
@@ -16,11 +18,11 @@
|
|||||||
],
|
],
|
||||||
"codeowners": ["@Patrick762"],
|
"codeowners": ["@Patrick762"],
|
||||||
"config_flow": true,
|
"config_flow": true,
|
||||||
"dependencies": ["bluetooth"],
|
"dependencies": ["bluetooth_adapters"],
|
||||||
"documentation": "https://github.com/Patrick762/hassio-bluetti-bt",
|
"documentation": "https://github.com/Patrick762/hassio-bluetti-bt",
|
||||||
"integration_type": "device",
|
"integration_type": "device",
|
||||||
"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": [],
|
"requirements": [],
|
||||||
"version": "0.0.19"
|
"version": "0.1.4"
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ async def async_setup_entry(
|
|||||||
all_fields.update({name+str(pack): field})
|
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 (len(bluetti_device.pack_polling_commands) > 0 and field_key.startswith("pack_")):
|
||||||
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
|
||||||
@@ -114,6 +114,7 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
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
|
||||||
|
self._unavailable_counter = 0
|
||||||
|
|
||||||
self._attr_device_info = device_info
|
self._attr_device_info = device_info
|
||||||
self._attr_name = name
|
self._attr_name = name
|
||||||
@@ -125,6 +126,32 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
self._attr_entity_category = category
|
self._attr_entity_category = category
|
||||||
self._options = options
|
self._options = options
|
||||||
|
|
||||||
|
@property
|
||||||
|
def available(self) -> bool:
|
||||||
|
"""Return if entity is available."""
|
||||||
|
return self._attr_available
|
||||||
|
|
||||||
|
def _set_available(self):
|
||||||
|
"""Set sensor as available."""
|
||||||
|
self._attr_available = True
|
||||||
|
self._unavailable_counter = 0
|
||||||
|
self._attr_extra_state_attributes = {}
|
||||||
|
self.async_write_ha_state()
|
||||||
|
|
||||||
|
def _set_unavailable(self, cause: str = "Unknown"):
|
||||||
|
"""Set sensor as unavailable."""
|
||||||
|
self._unavailable_counter += 1
|
||||||
|
|
||||||
|
self._attr_extra_state_attributes = {
|
||||||
|
"unavailable_counter": self._unavailable_counter,
|
||||||
|
"unavailable_cause": cause,
|
||||||
|
}
|
||||||
|
|
||||||
|
if self._unavailable_counter >= 5:
|
||||||
|
self._attr_available = False
|
||||||
|
|
||||||
|
self.async_write_ha_state()
|
||||||
|
|
||||||
@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."""
|
||||||
@@ -133,10 +160,10 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if self.coordinator.data is None:
|
if self.coordinator.data is None:
|
||||||
_LOGGER.warning(
|
_LOGGER.debug(
|
||||||
"Data from coordinator is None. Skipping update for %s",
|
"Data from coordinator is None",
|
||||||
unique_id_loggable(self._attr_unique_id)
|
|
||||||
)
|
)
|
||||||
|
self._set_unavailable("Data is None")
|
||||||
return
|
return
|
||||||
|
|
||||||
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
|
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
|
||||||
@@ -144,13 +171,13 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
_LOGGER.warning(
|
_LOGGER.warning(
|
||||||
"Invalid data from coordinator (sensor.%s)", unique_id_loggable(self._attr_unique_id)
|
"Invalid data from coordinator (sensor.%s)", unique_id_loggable(self._attr_unique_id)
|
||||||
)
|
)
|
||||||
self._attr_available = False
|
self._set_unavailable("Invalid data")
|
||||||
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)
|
_LOGGER.debug("No data for available for (%s)", self._response_key)
|
||||||
self._attr_available = False
|
self._set_unavailable("No data")
|
||||||
return
|
return
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -166,19 +193,18 @@ class BluettiSensor(CoordinatorEntity, SensorEntity):
|
|||||||
response_data,
|
response_data,
|
||||||
type(response_data),
|
type(response_data),
|
||||||
)
|
)
|
||||||
self._attr_available = False
|
self._set_unavailable("Invalid data type")
|
||||||
return
|
return
|
||||||
|
|
||||||
self._attr_available = True
|
self._set_available()
|
||||||
|
|
||||||
# Different for enum and numeric
|
# Different for enum and numeric
|
||||||
if (
|
if (
|
||||||
self._options is not None
|
self._options is not None
|
||||||
and isinstance(response_data, Enum)
|
and isinstance(response_data, Enum)
|
||||||
and response_data.value < len(self._options)
|
|
||||||
):
|
):
|
||||||
# Enum
|
# Enum
|
||||||
self._attr_native_value = self._options[response_data.value]
|
self._attr_native_value = response_data.name
|
||||||
else:
|
else:
|
||||||
# Numeric
|
# Numeric
|
||||||
self._attr_native_value = response_data
|
self._attr_native_value = response_data
|
||||||
|
|||||||
@@ -108,6 +108,11 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
|
|||||||
self._attr_entity_category = category
|
self._attr_entity_category = category
|
||||||
self._attr_device_class = SwitchDeviceClass.OUTLET
|
self._attr_device_class = SwitchDeviceClass.OUTLET
|
||||||
|
|
||||||
|
@property
|
||||||
|
def available(self) -> bool:
|
||||||
|
"""Return if entity is available."""
|
||||||
|
return self._attr_available
|
||||||
|
|
||||||
@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."""
|
||||||
@@ -117,15 +122,17 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
|
|||||||
|
|
||||||
_LOGGER.debug("Updating state of %s", unique_id_loggable(self._attr_unique_id))
|
_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 (switch.%s)", unique_id_loggable(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
|
||||||
|
self.async_write_ha_state()
|
||||||
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:
|
||||||
self._attr_available = False
|
self._attr_available = False
|
||||||
|
self.async_write_ha_state()
|
||||||
return
|
return
|
||||||
|
|
||||||
if not isinstance(response_data, bool):
|
if not isinstance(response_data, bool):
|
||||||
@@ -135,6 +142,7 @@ class BluettiSwitch(CoordinatorEntity, SwitchEntity):
|
|||||||
response_data,
|
response_data,
|
||||||
)
|
)
|
||||||
self._attr_available = False
|
self._attr_available = False
|
||||||
|
self.async_write_ha_state()
|
||||||
return
|
return
|
||||||
|
|
||||||
self._attr_available = True
|
self._attr_available = True
|
||||||
|
|||||||
@@ -17,7 +17,8 @@
|
|||||||
"persistent_conn": "Dauerhafte Verbindung (Neustart erforderlich)",
|
"persistent_conn": "Dauerhafte Verbindung (Neustart erforderlich)",
|
||||||
"polling_interval": "Datenabruf-Intervall in Sekunden (Neustart erforderlich)",
|
"polling_interval": "Datenabruf-Intervall in Sekunden (Neustart erforderlich)",
|
||||||
"polling_timeout": "Datenabruf-Timeout in Sekunden (Neustart erforderlich)",
|
"polling_timeout": "Datenabruf-Timeout in Sekunden (Neustart erforderlich)",
|
||||||
"max_retries": "Maximale Verbindungsversuche (Neustart erforderlich)"
|
"max_retries": "Maximale Verbindungsversuche (Neustart erforderlich)",
|
||||||
|
"use_encryption": "Verschlüsselte Verbindung (erforderlich für neue Firmware-Versionen)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -17,7 +17,8 @@
|
|||||||
"persistent_conn": "Persistent connection (restart required)",
|
"persistent_conn": "Persistent connection (restart required)",
|
||||||
"polling_interval": "Polling interval in seconds (restart required)",
|
"polling_interval": "Polling interval in seconds (restart required)",
|
||||||
"polling_timeout": "Polling timeout in seconds (restart required)",
|
"polling_timeout": "Polling timeout in seconds (restart required)",
|
||||||
"max_retries": "Maximum amount of connection retries (restart required)"
|
"max_retries": "Maximum amount of connection retries (restart required)",
|
||||||
|
"use_encryption": "Encrypted connection (necessary for latest firmware versions)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2,4 +2,7 @@
|
|||||||
|
|
||||||
# This script is only for development purposes
|
# This script is only for development purposes
|
||||||
|
|
||||||
|
sudo rm -rf /var/ha_config/custom_components/*/__pycache__
|
||||||
sudo cp -r ./custom_components/* /var/ha_config/custom_components/
|
sudo cp -r ./custom_components/* /var/ha_config/custom_components/
|
||||||
|
docker restart homeassistant
|
||||||
|
docker logs -f homeassistant
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
homeassistant
|
||||||
|
bleak_retry_connector
|
||||||
|
pyserial
|
||||||
|
bluetooth_auto_recovery
|
||||||
|
crcmod
|
||||||
|
typing
|
||||||
|
asyncio
|
||||||
|
logging
|
||||||
|
bleak
|
||||||
|
async_timeout
|
||||||
|
aiousbwatcher
|
||||||
|
pyasn1
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
|
||||||
# Execute unittests of python library
|
# Execute unittests of python library inside docker
|
||||||
python3 -m unittest discover -s tests -p "*_test.py"
|
sudo docker build --progress=plain -t bluetti-bt-tests .
|
||||||
@@ -4,8 +4,11 @@ import unittest
|
|||||||
|
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.utils.device_builder import build_device
|
from custom_components.bluetti_bt.bluetti_bt_lib.utils.device_builder import build_device
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac60 import AC60
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac60 import AC60
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac70 import AC70
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac70p import AC70P
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac180 import AC180
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac180 import AC180
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac180p import AC180P
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac180p import AC180P
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac200l import AC200L
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac200m import AC200M
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac200m import AC200M
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac300 import AC300
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac300 import AC300
|
||||||
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac500 import AC500
|
from custom_components.bluetti_bt.bluetti_bt_lib.devices.ac500 import AC500
|
||||||
@@ -32,6 +35,22 @@ class TestDeviceBuilder(unittest.TestCase):
|
|||||||
self.assertIsInstance(built, AC60)
|
self.assertIsInstance(built, AC60)
|
||||||
self.assertEqual(built.address, bt_addr)
|
self.assertEqual(built.address, bt_addr)
|
||||||
|
|
||||||
|
def test_build_ac70(self):
|
||||||
|
bt_addr = "aa:bb:cc:dd:ee:ff"
|
||||||
|
bt_name = "AC7056786746478"
|
||||||
|
built = build_device(bt_addr, bt_name)
|
||||||
|
|
||||||
|
self.assertIsInstance(built, AC70)
|
||||||
|
self.assertEqual(built.address, bt_addr)
|
||||||
|
|
||||||
|
def test_build_ac70p(self):
|
||||||
|
bt_addr = "aa:bb:cc:dd:ee:ff"
|
||||||
|
bt_name = "AC70P56786746478"
|
||||||
|
built = build_device(bt_addr, bt_name)
|
||||||
|
|
||||||
|
self.assertIsInstance(built, AC70P)
|
||||||
|
self.assertEqual(built.address, bt_addr)
|
||||||
|
|
||||||
def test_build_ac180(self):
|
def test_build_ac180(self):
|
||||||
bt_addr = "aa:bb:cc:dd:ee:ff"
|
bt_addr = "aa:bb:cc:dd:ee:ff"
|
||||||
bt_name = "AC18056786746478"
|
bt_name = "AC18056786746478"
|
||||||
@@ -48,6 +67,14 @@ class TestDeviceBuilder(unittest.TestCase):
|
|||||||
self.assertIsInstance(built, AC180P)
|
self.assertIsInstance(built, AC180P)
|
||||||
self.assertEqual(built.address, bt_addr)
|
self.assertEqual(built.address, bt_addr)
|
||||||
|
|
||||||
|
def test_build_ac200l(self):
|
||||||
|
bt_addr = "aa:bb:cc:dd:ee:ff"
|
||||||
|
bt_name = "AC200L56786746478"
|
||||||
|
built = build_device(bt_addr, bt_name)
|
||||||
|
|
||||||
|
self.assertIsInstance(built, AC200L)
|
||||||
|
self.assertEqual(built.address, bt_addr)
|
||||||
|
|
||||||
def test_build_ac200m(self):
|
def test_build_ac200m(self):
|
||||||
bt_addr = "aa:bb:cc:dd:ee:ff"
|
bt_addr = "aa:bb:cc:dd:ee:ff"
|
||||||
bt_name = "AC200M56786746478"
|
bt_name = "AC200M56786746478"
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Unittest for device struct."""
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.utils.commands import ReadHoldingRegisters
|
||||||
|
from custom_components.bluetti_bt.bluetti_bt_lib.utils.struct import DeviceStruct
|
||||||
|
|
||||||
|
class TestDeviceStruct(unittest.TestCase):
|
||||||
|
def test_get_read_holding_registers(self):
|
||||||
|
struct = DeviceStruct()
|
||||||
|
|
||||||
|
struct.add_swap_string_field("device_type", 110, 6)
|
||||||
|
struct.add_sn_field("serial_number", 116)
|
||||||
|
struct.add_decimal_field(
|
||||||
|
"power_generation", 154, 1
|
||||||
|
)
|
||||||
|
struct.add_uint_field("total_battery_percent", 102)
|
||||||
|
|
||||||
|
registers = struct.get_read_holding_registers()
|
||||||
|
|
||||||
|
self.assertGreater(len(registers), 0)
|
||||||
|
|
||||||
|
for reg in registers:
|
||||||
|
self.assertIsInstance(reg, ReadHoldingRegisters)
|
||||||
Reference in new issue
Block a user