Add power meter and inverter devices to E3/DC (#191296)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Josef Zweck <josef@zweck.dev>
Co-authored-by: Abílio Costa <abmantis@users.noreply.github.com>
This commit is contained in:
AlCalzone
2026-11-27 00:52:18 +00:00
committed by GitHub
co-authored by Claude Opus 5.5 Josef Zweck Abílio Costa
parent 1d07105b76
commit 6fe8a55d46
11 changed files with 2993 additions and 67 deletions
+1 -11
View File
@@ -8,7 +8,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError, HomeAssistantError
from .config_flow import create_modbus_params
from .const import DOMAIN, UNIT_ID
from .const import UNIT_ID
from .coordinator import E3dcConfigEntry, E3dcDataUpdateCoordinator
PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR]
@@ -28,17 +28,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: E3dcConfigEntry) -> None
entry.async_on_unload(device.close)
coordinator = E3dcDataUpdateCoordinator(hass, entry, device)
# The first poll also reads the identity and probes which blocks the station serves
await coordinator.async_config_entry_first_refresh()
if device.serial_number != entry.unique_id:
raise ConfigEntryError(
translation_domain=DOMAIN,
translation_key="serial_mismatch",
translation_placeholders={
"expected": str(entry.unique_id),
"found": str(device.serial_number),
},
)
entry.runtime_data = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
+9
View File
@@ -1,5 +1,7 @@
"""Constants for the E3/DC integration."""
from enum import StrEnum
DOMAIN = "e3dc"
DEFAULT_NAME = "E3/DC"
@@ -8,3 +10,10 @@ DEFAULT_PORT = 502
UNIT_ID = 1
# Poll every 5 seconds because the power flows change from second to second
SCAN_INTERVAL = 5
class PartKind(StrEnum):
"""A kind of part with its own device. The value is its device translation key."""
POWER_METER = "power_meter"
INVERTER = "inverter"
+75 -3
View File
@@ -1,10 +1,12 @@
"""Data update coordinator for E3/DC devices."""
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from datetime import timedelta
import logging
from typing import TYPE_CHECKING, override
from e3dc_ess_modbus import E3dcPowerStation, NotAnE3dcError
from e3dc_ess_modbus import E3dcPowerStation, NotAnE3dcError, PowerMeterType
from modbus_connection import ModbusError
from propcache.api import cached_property
@@ -14,7 +16,7 @@ from homeassistant.exceptions import ConfigEntryError
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DEFAULT_NAME, DOMAIN, SCAN_INTERVAL
from .const import DEFAULT_NAME, DOMAIN, SCAN_INTERVAL, PartKind
_LOGGER = logging.getLogger(__name__)
@@ -23,11 +25,58 @@ POLLED_COMPONENTS = (
"power",
"battery_limits",
"wide_power_meters",
"power_meters",
"inverter_mode_control",
"grid_control",
"inverters",
)
# The components that tell which optional hardware is installed, read once
HARDWARE_COMPONENTS = ("wallboxes", "power_meters")
HARDWARE_COMPONENTS = ("wallboxes",)
@dataclass(frozen=True, kw_only=True, order=True)
class E3dcPart:
"""A power meter or inverter of the power station, with its own device."""
kind: PartKind
slot: int # E3/DC counts the slots from 0
@property
def number(self) -> int:
"""The part's number, counted from 1."""
return self.slot + 1
@property
def built_in(self) -> bool:
"""Whether this is the power station's own inverter."""
return self.kind is PartKind.INVERTER and self.slot == 0
def _installed_meters(device: E3dcPowerStation) -> list[int]:
"""The power meter slots with a meter configured, other than the grid connection point.
The power station's own sensors cover the meter at the grid connection point.
"""
return [
number
for number, meter in device.power_meter_readings.items()
if meter.is_installed and meter.meter_type is not PowerMeterType.ROOT
]
def _connected_inverters(device: E3dcPowerStation) -> list[int]:
"""The power station's own inverter, and each additional one on the grid."""
return [
number
for number, inverter in (device.inverters or {}).items()
if number == 0 or inverter.is_connected
]
PART_SLOTS: dict[PartKind, Callable[[E3dcPowerStation], Iterable[int]]] = {
PartKind.POWER_METER: _installed_meters,
PartKind.INVERTER: _connected_inverters,
}
type E3dcConfigEntry = ConfigEntry[E3dcDataUpdateCoordinator]
@@ -36,6 +85,7 @@ class E3dcDataUpdateCoordinator(DataUpdateCoordinator[None]):
"""Poll the power station."""
config_entry: E3dcConfigEntry
station_device_id: str
def __init__(
self,
@@ -52,6 +102,8 @@ class E3dcDataUpdateCoordinator(DataUpdateCoordinator[None]):
update_interval=timedelta(seconds=SCAN_INTERVAL),
)
self.device = device
# The parts the power station reported in the last successful poll
self.parts: set[E3dcPart] = set()
@cached_property
def device_info(self) -> dr.DeviceInfo:
@@ -70,11 +122,31 @@ class E3dcDataUpdateCoordinator(DataUpdateCoordinator[None]):
@override
async def _async_setup(self) -> None:
# The first poll also reads the identity and probes which blocks the station serves
await self._async_poll(HARDWARE_COMPONENTS)
if self.device.serial_number != self.config_entry.unique_id:
raise ConfigEntryError(
translation_domain=DOMAIN,
translation_key="serial_mismatch",
translation_placeholders={
"expected": str(self.config_entry.unique_id),
"found": str(self.device.serial_number),
},
)
# Register the power station before its parts, which link to it
station = dr.async_get(self.hass).async_get_or_create_from_info(
config_entry_id=self.config_entry.entry_id, device_info=self.device_info
)
self.station_device_id = station.id
@override
async def _async_update_data(self) -> None:
await self._async_poll(POLLED_COMPONENTS)
self.parts = {
E3dcPart(kind=kind, slot=slot)
for kind, slots_fn in PART_SLOTS.items()
for slot in slots_fn(self.device)
}
async def _async_poll(self, components: tuple[str, ...]) -> None:
"""Read the components from the power station, or raise."""
+91 -6
View File
@@ -1,11 +1,16 @@
"""Base entity for E3/DC devices."""
from typing import TYPE_CHECKING
from collections.abc import Callable, Iterable, Mapping
from typing import TYPE_CHECKING, override
from homeassistant.helpers.entity import EntityDescription
from homeassistant.core import callback
from homeassistant.helpers.device_registry import ChildDeviceInfo, DeviceInfo
from homeassistant.helpers.entity import Entity, EntityDescription
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .coordinator import E3dcDataUpdateCoordinator
from .const import DOMAIN, PartKind
from .coordinator import E3dcConfigEntry, E3dcDataUpdateCoordinator, E3dcPart
class E3dcEntity(CoordinatorEntity[E3dcDataUpdateCoordinator]):
@@ -17,12 +22,92 @@ class E3dcEntity(CoordinatorEntity[E3dcDataUpdateCoordinator]):
self,
coordinator: E3dcDataUpdateCoordinator,
entity_description: EntityDescription,
part: E3dcPart | None = None,
) -> None:
"""Initialize the entity."""
"""Initialize the entity, on the power station or on one of its parts."""
super().__init__(coordinator)
self.entity_description = entity_description
serial = coordinator.config_entry.unique_id
if TYPE_CHECKING:
assert serial is not None
self._attr_unique_id = f"{serial}_{entity_description.key}"
self._attr_device_info = coordinator.device_info
if part is None:
prefix = serial
self._attr_device_info = coordinator.device_info
else:
prefix = f"{serial}_{part.kind}_{part.number}"
self._attr_device_info = _part_device_info(coordinator, part, prefix)
self._attr_unique_id = f"{prefix}_{entity_description.key}"
class E3dcPartEntity(E3dcEntity):
"""Defines an entity of a power meter or an inverter."""
def __init__(
self,
coordinator: E3dcDataUpdateCoordinator,
entity_description: EntityDescription,
part: E3dcPart,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator, entity_description, part)
self._part = part
@property
@override
def available(self) -> bool:
return super().available and self._part in self.coordinator.parts
@callback
def async_add_part_entities[_DescriptionT: EntityDescription](
entry: E3dcConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
descriptions: Mapping[PartKind, Iterable[_DescriptionT]],
entity_factory: Callable[
[E3dcDataUpdateCoordinator, _DescriptionT, E3dcPart], Entity
],
) -> None:
"""Add a platform's entities for each part the first time the power station reports it."""
coordinator = entry.runtime_data
added: set[E3dcPart] = set()
@callback
def _async_add_new() -> None:
new = sorted(
part for part in coordinator.parts - added if part.kind in descriptions
)
added.update(new)
entities = [
entity_factory(coordinator, description, part)
for part in new
for description in descriptions[part.kind]
]
if entities:
async_add_entities(entities)
_async_add_new()
entry.async_on_unload(coordinator.async_add_listener(_async_add_new))
def _part_device_info(
coordinator: E3dcDataUpdateCoordinator, part: E3dcPart, identifier: str
) -> DeviceInfo | ChildDeviceInfo:
"""Describe the device of a part.
The power station's own inverter is a child of the power station device, every
other part is a device connected through it.
"""
placeholders = {"number": str(part.number)}
if part.built_in:
return ChildDeviceInfo(
identifiers={(DOMAIN, identifier)},
parent_device_id=coordinator.station_device_id,
translation_key=part.kind,
translation_placeholders=placeholders,
)
return DeviceInfo(
identifiers={(DOMAIN, identifier)},
translation_key=part.kind,
translation_placeholders=placeholders,
via_device_id=coordinator.station_device_id,
)
@@ -61,7 +61,11 @@ rules:
docs-supported-functions: done
docs-troubleshooting: done
docs-use-cases: done
dynamic-devices: todo
dynamic-devices:
status: todo
comment: |
Wallboxes can be added at runtime. The integration only looks for them during setup.
Inverters are handled the same way. Additional inverters can probably be added at runtime too.
entity-category: done
entity-device-class: done
entity-disabled-by-default: done
+289 -12
View File
@@ -3,12 +3,14 @@
from collections.abc import Callable
from dataclasses import dataclass
from enum import IntEnum
from typing import override
from operator import attrgetter
from typing import TYPE_CHECKING, override
from e3dc_ess_modbus import (
E3dcPowerStation,
EmergencyPowerStatus,
InverterMode,
PowerMeterReading,
PowerMeterType,
SgReadyStatus,
)
@@ -22,19 +24,29 @@ from homeassistant.components.sensor import (
from homeassistant.const import (
PERCENTAGE,
EntityCategory,
UnitOfApparentPower,
UnitOfElectricCurrent,
UnitOfElectricPotential,
UnitOfEnergy,
UnitOfFrequency,
UnitOfPower,
UnitOfReactivePower,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .const import PartKind
from .coordinator import E3dcConfigEntry
from .entity import E3dcEntity
from .entity import E3dcEntity, E3dcPartEntity, async_add_part_entities
PARALLEL_UPDATES = 0
PHASES = ("l1", "l2", "l3")
# The manual marks DC tracker 3 as not used, but the E3/DC one reports it
DC_TRACKERS = (1, 2, 3)
def _enum_options(enum_type: type[IntEnum]) -> list[str]:
"""The sensor options a device enum maps to."""
@@ -65,6 +77,26 @@ def _has_additional_feeder(device: E3dcPowerStation) -> bool:
)
def _grid_meter(device: E3dcPowerStation) -> PowerMeterReading | None:
"""The power meter at the grid connection point, if one is configured."""
return next(
(
meter
for meter in device.power_meter_readings.values()
if meter.meter_type is PowerMeterType.ROOT
),
None,
)
def _grid_phase_power(phase: str) -> Callable[[E3dcPowerStation], StateType]:
"""Read the power on ``phase`` at the grid connection point."""
get = attrgetter(f"power_{phase}")
return lambda device: (
get(meter) if (meter := _grid_meter(device)) is not None else None
)
def _power(
key: str,
value_fn: Callable[[E3dcPowerStation], int | None],
@@ -95,6 +127,21 @@ SENSORS: tuple[E3dcSensorDescription, ...] = (
),
_power("house_power", lambda device: device.power.house_power),
_power("grid_power", lambda device: device.power.grid_power),
*(
E3dcSensorDescription(
key=f"grid_power_{phase}",
translation_key="grid_power_phase",
translation_placeholders={"phase": phase.upper()},
component="power_meters",
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
value_fn=_grid_phase_power(phase),
exists_fn=lambda device: _grid_meter(device) is not None,
)
for phase in PHASES
),
_power(
"additional_power",
lambda device: device.power.additional_power,
@@ -256,6 +303,196 @@ SENSORS: tuple[E3dcSensorDescription, ...] = (
)
@dataclass(frozen=True, kw_only=True)
class E3dcPartSensorDescription(SensorEntityDescription):
"""Describe a sensor of a power meter or an inverter."""
value_fn: Callable[[E3dcPowerStation, int], StateType | IntEnum]
def _meter_phase_power(phase: str) -> Callable[[E3dcPowerStation, int], StateType]:
"""Read the power on ``phase`` of a power meter slot."""
get = attrgetter(f"power_{phase}")
return lambda device, number: get(device.power_meter_readings[number])
def _total(meter: PowerMeterReading) -> int | None:
"""The sum of the meter's phase powers, or ``None`` if any is unknown."""
powers = (meter.power_l1, meter.power_l2, meter.power_l3)
known = [power for power in powers if power is not None]
return sum(known) if len(known) == len(powers) else None
POWER_METER_SENSORS: tuple[E3dcPartSensorDescription, ...] = (
E3dcPartSensorDescription(
key="type",
translation_key="power_meter_type",
device_class=SensorDeviceClass.ENUM,
options=_enum_options(PowerMeterType),
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda device, number: device.power_meter_readings[number].meter_type,
),
E3dcPartSensorDescription(
key="power",
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda device, number: _total(device.power_meter_readings[number]),
),
*(
E3dcPartSensorDescription(
key=f"power_{phase}",
translation_key="power_phase",
translation_placeholders={"phase": phase.upper()},
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
value_fn=_meter_phase_power(phase),
)
for phase in PHASES
),
)
def _inverter_value(attribute: str) -> Callable[[E3dcPowerStation, int], StateType]:
"""Read ``attribute`` of an inverter slot, which only exists once the slot answered."""
get = attrgetter(attribute)
def _value(device: E3dcPowerStation, number: int) -> StateType:
if TYPE_CHECKING:
assert device.inverters is not None
value: StateType = get(device.inverters[number])
return value
return _value
INVERTER_SENSORS: tuple[E3dcPartSensorDescription, ...] = (
*(
E3dcPartSensorDescription(
key=f"active_power_{phase}",
translation_key="active_power_phase",
translation_placeholders={"phase": phase.upper()},
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
value_fn=_inverter_value(f"active_power_{phase}"),
)
for phase in PHASES
),
*(
E3dcPartSensorDescription(
key=f"apparent_power_{phase}",
translation_key="apparent_power_phase",
translation_placeholders={"phase": phase.upper()},
device_class=SensorDeviceClass.APPARENT_POWER,
native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE,
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
value_fn=_inverter_value(f"apparent_power_{phase}"),
)
for phase in PHASES
),
*(
E3dcPartSensorDescription(
key=f"reactive_power_{phase}",
translation_key="reactive_power_phase",
translation_placeholders={"phase": phase.upper()},
device_class=SensorDeviceClass.REACTIVE_POWER,
native_unit_of_measurement=UnitOfReactivePower.VOLT_AMPERE_REACTIVE,
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
value_fn=_inverter_value(f"reactive_power_{phase}"),
)
for phase in PHASES
),
*(
E3dcPartSensorDescription(
key=f"voltage_{phase}",
translation_key="voltage_phase",
translation_placeholders={"phase": phase.upper()},
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
entity_registry_enabled_default=False,
value_fn=_inverter_value(f"voltage_{phase}"),
)
for phase in PHASES
),
*(
E3dcPartSensorDescription(
key=f"current_{phase}",
translation_key="current_phase",
translation_placeholders={"phase": phase.upper()},
device_class=SensorDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=2,
entity_registry_enabled_default=False,
value_fn=_inverter_value(f"current_{phase}"),
)
for phase in PHASES
),
E3dcPartSensorDescription(
key="frequency",
device_class=SensorDeviceClass.FREQUENCY,
native_unit_of_measurement=UnitOfFrequency.HERTZ,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=2,
entity_registry_enabled_default=False,
value_fn=_inverter_value("frequency"),
),
*(
E3dcPartSensorDescription(
key=f"dc_power_{tracker}",
translation_key="dc_power",
translation_placeholders={"tracker": str(tracker)},
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
value_fn=_inverter_value(f"dc_power_{tracker}"),
)
for tracker in DC_TRACKERS
),
*(
E3dcPartSensorDescription(
key=f"dc_voltage_{tracker}",
translation_key="dc_voltage",
translation_placeholders={"tracker": str(tracker)},
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
entity_registry_enabled_default=False,
value_fn=_inverter_value(f"dc_voltage_{tracker}"),
)
for tracker in DC_TRACKERS
),
*(
E3dcPartSensorDescription(
key=f"dc_current_{tracker}",
translation_key="dc_current",
translation_placeholders={"tracker": str(tracker)},
device_class=SensorDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=2,
entity_registry_enabled_default=False,
value_fn=_inverter_value(f"dc_current_{tracker}"),
)
for tracker in DC_TRACKERS
),
)
PART_SENSORS: dict[PartKind, tuple[E3dcPartSensorDescription, ...]] = {
PartKind.POWER_METER: POWER_METER_SENSORS,
PartKind.INVERTER: INVERTER_SENSORS,
}
async def async_setup_entry(
hass: HomeAssistant,
entry: E3dcConfigEntry,
@@ -265,11 +502,34 @@ async def async_setup_entry(
coordinator = entry.runtime_data
device = coordinator.device
served = {*device.readings_components, *device.settings_components}
async_add_entities(
E3dcSensor(coordinator, description)
for description in SENSORS
if description.component in served and description.exists_fn(device)
)
# The keys of the station sensors that are already added
added_sensors: set[str] = set()
@callback
def _async_add_new() -> None:
"""Add station sensors for hardware the first time the power station reports it."""
entities: list[SensorEntity] = []
for description in SENSORS:
if (
description.key not in added_sensors
and description.component in served
and description.exists_fn(device)
):
added_sensors.add(description.key)
entities.append(E3dcSensor(coordinator, description))
if entities:
async_add_entities(entities)
_async_add_new()
entry.async_on_unload(coordinator.async_add_listener(_async_add_new))
async_add_part_entities(entry, async_add_entities, PART_SENSORS, E3dcPartSensor)
def _state(value: StateType | IntEnum) -> StateType:
"""The sensor state for a value, with enum members as their option."""
if isinstance(value, IntEnum):
return value.name.lower()
return value
class E3dcSensor(E3dcEntity, SensorEntity):
@@ -277,10 +537,27 @@ class E3dcSensor(E3dcEntity, SensorEntity):
entity_description: E3dcSensorDescription
@property
@override
def available(self) -> bool:
return super().available and self.entity_description.exists_fn(
self.coordinator.device
)
@property
@override
def native_value(self) -> StateType:
value = self.entity_description.value_fn(self.coordinator.device)
if isinstance(value, IntEnum):
return value.name.lower()
return value
return _state(self.entity_description.value_fn(self.coordinator.device))
class E3dcPartSensor(E3dcPartEntity, SensorEntity):
"""Defines a sensor of a power meter or an inverter."""
entity_description: E3dcPartSensorDescription
@property
@override
def native_value(self) -> StateType:
return _state(
self.entity_description.value_fn(self.coordinator.device, self._part.slot)
)
@@ -44,6 +44,14 @@
}
}
},
"device": {
"inverter": {
"name": "Inverter {number}"
},
"power_meter": {
"name": "Power meter {number}"
}
},
"entity": {
"binary_sensor": {
"charge_lock_time": {
@@ -72,15 +80,33 @@
"active_power_failsafe_timeout": {
"name": "Active power failsafe timeout"
},
"active_power_phase": {
"name": "Active power {phase}"
},
"additional_power": {
"name": "Additional feeder power"
},
"apparent_power_phase": {
"name": "Apparent power {phase}"
},
"autarky": {
"name": "Self-sufficiency"
},
"battery_power": {
"name": "Battery power"
},
"current_phase": {
"name": "Current {phase}"
},
"dc_current": {
"name": "DC current {tracker}"
},
"dc_power": {
"name": "DC power {tracker}"
},
"dc_voltage": {
"name": "DC voltage {tracker}"
},
"emergency_power_status": {
"name": "Emergency power",
"state": {
@@ -97,6 +123,9 @@
"grid_power": {
"name": "Grid power"
},
"grid_power_phase": {
"name": "Grid power {phase}"
},
"house_power": {
"name": "House power"
},
@@ -113,12 +142,33 @@
"max_discharge_power": {
"name": "Maximum discharge power"
},
"power_meter_type": {
"name": "Meter type",
"state": {
"bidirectional": "Bidirectional",
"control_bypass": "Control bypass",
"data_display": "Data display only",
"external_consumption": "External consumption",
"external_farm": "External farm",
"external_production": "External production",
"farm": "Farm",
"not_used": "Not used",
"root": "Grid connection point",
"wallbox": "Wallbox"
}
},
"power_phase": {
"name": "Power {phase}"
},
"pv_power": {
"name": "PV power"
},
"reactive_power_failsafe_timeout": {
"name": "Reactive power failsafe timeout"
},
"reactive_power_phase": {
"name": "Reactive power {phase}"
},
"self_consumption": {
"name": "Self-consumption"
},
@@ -131,6 +181,9 @@
"switch_on_recommended": "Switch-on recommended"
}
},
"voltage_phase": {
"name": "Voltage {phase}"
},
"wallbox_power": {
"name": "Wallbox power"
},
+21 -2
View File
@@ -69,9 +69,21 @@ def seed_power_station(unit: MockModbusUnit) -> None:
40084: 2, # Emergency power not active
40085: 0b0000100, # EMS status: emergency power ready
40088: 0b1, # Wallbox 0 available
40105: 1, # Power meter 0 at the grid connection point
40109: 2, # Power meter 1 measures an additional feeder
40105: 1, # Power meter slot 0 at the grid connection point
40106: 0xFED4, # Power meter slot 0 power L1, -300 W
40107: 0xFF38, # Power meter slot 0 power L2, -200 W
40108: 0xFF9C, # Power meter slot 0 power L3, -100 W
40109: 2, # Power meter slot 1 measures an additional feeder
40110: 100, # Power meter slot 1 power L1, in W
40111: 100, # Power meter slot 1 power L2, in W
40112: 100, # Power meter slot 1 power L3, in W
40137: 1, # SG Ready status
40138: int32_words(-300), # Power meter slot 0 power L1, 32 bit
40140: int32_words(-200), # Power meter slot 0 power L2, 32 bit
40142: int32_words(-100), # Power meter slot 0 power L3, 32 bit
40144: int32_words(100), # Power meter slot 1 power L1, 32 bit
40146: int32_words(100), # Power meter slot 1 power L2, 32 bit
40148: int32_words(100), # Power meter slot 1 power L3, 32 bit
40194: 30, # Active power failsafe timeout, in s
40196: 30, # Reactive power failsafe timeout, in s
40201: 0, # Inverter mode: normal
@@ -79,5 +91,12 @@ def seed_power_station(unit: MockModbusUnit) -> None:
40204: int32_words(-9000), # Battery max discharge power, in W
40206: int32_words(9135), # Battery remaining energy, in Wh
40208: int32_words(10500), # Battery full charge energy, in Wh
41006: int32_words(1750), # Inverter 0 active power L1, in W
41018: 2301, # Inverter 0 voltage L1, in 0.1 V
41019: 2299, # Inverter 0 voltage L2, in 0.1 V
41020: 2310, # Inverter 0 voltage L3, in 0.1 V
41024: 5001, # Inverter 0 frequency, in 0.01 Hz
41025: 2754, # Inverter 0 DC power 1, in W
41027: 1210, # Inverter 0 DC power 3, in W
},
)
@@ -94,13 +94,13 @@
'40093': 0,
'40094': 0,
'40104': 1,
'40105': 0,
'40106': 0,
'40107': 0,
'40105': 65236,
'40106': 65336,
'40107': 65436,
'40108': 2,
'40109': 0,
'40110': 0,
'40111': 0,
'40109': 100,
'40110': 100,
'40111': 100,
'40112': 0,
'40113': 0,
'40114': 0,
@@ -126,17 +126,17 @@
'40134': 0,
'40135': 0,
'40136': 1,
'40137': 0,
'40138': 0,
'40139': 0,
'40140': 0,
'40141': 0,
'40142': 0,
'40143': 0,
'40137': 65236,
'40138': 65535,
'40139': 65336,
'40140': 65535,
'40141': 65436,
'40142': 65535,
'40143': 100,
'40144': 0,
'40145': 0,
'40145': 100,
'40146': 0,
'40147': 0,
'40147': 100,
'40148': 0,
'40149': 0,
'40150': 0,
@@ -188,6 +188,278 @@
'40206': 0,
'40207': 10500,
'40208': 0,
'40999': 0,
'41000': 0,
'41001': 0,
'41002': 0,
'41003': 0,
'41004': 0,
'41005': 1750,
'41006': 0,
'41007': 0,
'41008': 0,
'41009': 0,
'41010': 0,
'41011': 0,
'41012': 0,
'41013': 0,
'41014': 0,
'41015': 0,
'41016': 0,
'41017': 2301,
'41018': 2299,
'41019': 2310,
'41020': 0,
'41021': 0,
'41022': 0,
'41023': 5001,
'41024': 2754,
'41025': 0,
'41026': 1210,
'41027': 0,
'41028': 0,
'41029': 0,
'41030': 0,
'41031': 0,
'41032': 0,
'41033': 0,
'41034': 0,
'41035': 0,
'41036': 0,
'41037': 0,
'41038': 0,
'41039': 0,
'41040': 0,
'41041': 0,
'41042': 0,
'41043': 0,
'41044': 0,
'41045': 0,
'41046': 0,
'41047': 0,
'41048': 0,
'41049': 0,
'41050': 0,
'41051': 0,
'41052': 0,
'41053': 0,
'41054': 0,
'41055': 0,
'41056': 0,
'41057': 0,
'41058': 0,
'41059': 0,
'41060': 0,
'41061': 0,
'41062': 0,
'41063': 0,
'41064': 0,
'41065': 0,
'41066': 0,
'41067': 0,
'41068': 0,
'41069': 0,
'41070': 0,
'41071': 0,
'41072': 0,
'41073': 0,
'41074': 0,
'41075': 0,
'41076': 0,
'41077': 0,
'41078': 0,
'41079': 0,
'41080': 0,
'41081': 0,
'41082': 0,
'41083': 0,
'41084': 0,
'41085': 0,
'41086': 0,
'41087': 0,
'41088': 0,
'41089': 0,
'41090': 0,
'41091': 0,
'41092': 0,
'41093': 0,
'41094': 0,
'41095': 0,
'41096': 0,
'41097': 0,
'41098': 0,
'41099': 0,
'41100': 0,
'41101': 0,
'41102': 0,
'41103': 0,
'41104': 0,
'41105': 0,
'41106': 0,
'41107': 0,
'41108': 0,
'41109': 0,
'41110': 0,
'41111': 0,
'41112': 0,
'41113': 0,
'41114': 0,
'41115': 0,
'41116': 0,
'41117': 0,
'41118': 0,
'41119': 0,
'41120': 0,
'41121': 0,
'41122': 0,
'41123': 0,
'41124': 0,
'41125': 0,
'41126': 0,
'41127': 0,
'41128': 0,
'41129': 0,
'41130': 0,
'41131': 0,
'41132': 0,
'41133': 0,
'41134': 0,
'41135': 0,
'41136': 0,
'41137': 0,
'41138': 0,
'41139': 0,
'41140': 0,
'41141': 0,
'41142': 0,
'41143': 0,
'41144': 0,
'41145': 0,
'41146': 0,
'41147': 0,
'41148': 0,
'41149': 0,
'41150': 0,
'41151': 0,
'41152': 0,
'41153': 0,
'41154': 0,
'41155': 0,
'41156': 0,
'41157': 0,
'41158': 0,
'41159': 0,
'41160': 0,
'41161': 0,
'41162': 0,
'41163': 0,
'41164': 0,
'41165': 0,
'41166': 0,
'41167': 0,
'41168': 0,
'41169': 0,
'41170': 0,
'41171': 0,
'41172': 0,
'41173': 0,
'41174': 0,
'41175': 0,
'41176': 0,
'41177': 0,
'41178': 0,
'41179': 0,
'41180': 0,
'41181': 0,
'41182': 0,
'41183': 0,
'41184': 0,
'41185': 0,
'41186': 0,
'41187': 0,
'41188': 0,
'41189': 0,
'41190': 0,
'41191': 0,
'41192': 0,
'41193': 0,
'41194': 0,
'41195': 0,
'41196': 0,
'41197': 0,
'41198': 0,
'41199': 0,
'41200': 0,
'41201': 0,
'41202': 0,
'41203': 0,
'41204': 0,
'41205': 0,
'41206': 0,
'41207': 0,
'41208': 0,
'41209': 0,
'41210': 0,
'41211': 0,
'41212': 0,
'41213': 0,
'41214': 0,
'41215': 0,
'41216': 0,
'41217': 0,
'41218': 0,
'41219': 0,
'41220': 0,
'41221': 0,
'41222': 0,
'41223': 0,
'41224': 0,
'41225': 0,
'41226': 0,
'41227': 0,
'41228': 0,
'41229': 0,
'41230': 0,
'41231': 0,
'41232': 0,
'41233': 0,
'41234': 0,
'41235': 0,
'41236': 0,
'41237': 0,
'41238': 0,
'41239': 0,
'41240': 0,
'41241': 0,
'41242': 0,
'41243': 0,
'41244': 0,
'41245': 0,
'41246': 0,
'41247': 0,
'41248': 0,
'41249': 0,
'41250': 0,
'41251': 0,
'41252': 0,
'41253': 0,
'41254': 0,
'41255': 0,
'41256': 0,
'41257': 0,
'41258': 0,
'41259': 0,
'41260': 0,
'41261': 0,
'41262': 0,
'41263': 0,
'41264': 0,
'41265': 0,
'41266': 0,
'41267': 0,
'41268': 0,
'41269': 0,
'41270': 0,
}),
}),
'read_error': None,
File diff suppressed because it is too large Load Diff
+230 -17
View File
@@ -14,14 +14,15 @@ from pytest_homeassistant.common import (
)
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.e3dc.const import SCAN_INTERVAL
from homeassistant.const import Platform
from homeassistant.components.e3dc.const import DOMAIN, SCAN_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import int32_words, seed
from . import MOCK_SERIAL, int32_words, seed
PV_POWER = "sensor.e3_dc_s10_x_pv_power"
GRID_POWER_L1 = "sensor.e3_dc_s10_x_grid_power_l1"
BATTERY_LIMIT_SENSORS = [
"sensor.e3_dc_s10_x_maximum_charge_power",
"sensor.e3_dc_s10_x_maximum_discharge_power",
@@ -51,35 +52,53 @@ async def test_all_entities(
("holding", "entity_id", "state"),
[
pytest.param(
{40206: int32_words(4200)},
{40206: int32_words(4200)}, # Battery remaining energy, in Wh
"sensor.e3_dc_s10_x_stored_energy",
"4.2",
id="battery_limits",
),
pytest.param(
{40137: 2},
{40137: 2}, # SG Ready status
"sensor.e3_dc_s10_x_sg_ready_status",
"normal",
id="wide_power_meters",
),
pytest.param(
{40137: 0},
{40137: 0}, # SG Ready status
"sensor.e3_dc_s10_x_sg_ready_status",
"unknown",
id="sg_ready_unknown_value",
),
pytest.param(
{40194: 60},
{40194: 60}, # Active power failsafe timeout, in s
"sensor.e3_dc_s10_x_active_power_failsafe_timeout",
"60",
id="grid_control",
),
pytest.param(
{40201: 10},
{40201: 10}, # Inverter mode
"sensor.e3_dc_s10_x_inverter_mode",
"idle_off_grid_power_save",
id="inverter_mode_control",
),
pytest.param(
{40138: int32_words(-500)}, # Power meter slot 0 power L1, 32 bit
"sensor.e3_dc_s10_x_grid_power_l1",
"-500",
id="grid_meter",
),
pytest.param(
{40144: int32_words(200)}, # Power meter slot 1 power L1, 32 bit
"sensor.power_meter_2_power",
"400",
id="power_meters",
),
pytest.param(
{41006: int32_words(2000)}, # Inverter slot 0 active power L1, in W
"sensor.e3_dc_s10_x_inverter_1_active_power_l1",
"2000",
id="inverters",
),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
@@ -104,7 +123,7 @@ async def test_sensor_follows_poll(
("holding", "entity_ids"),
[
pytest.param(
{40088: 0},
{40088: 0}, # No wallbox available
[
"sensor.e3_dc_s10_x_wallbox_power",
"sensor.e3_dc_s10_x_wallbox_solar_power",
@@ -112,17 +131,26 @@ async def test_sensor_follows_poll(
id="no_wallbox",
),
pytest.param(
{40109: 0},
{40109: 0}, # Power meter slot 1 not installed
["sensor.e3_dc_s10_x_additional_feeder_power"],
id="no_additional_feeder",
),
pytest.param(
{40084: 0},
{40105: 0}, # Power meter slot 0 not installed
[
"sensor.e3_dc_s10_x_grid_power_l1",
"sensor.e3_dc_s10_x_grid_power_l2",
"sensor.e3_dc_s10_x_grid_power_l3",
],
id="no_grid_meter",
),
pytest.param(
{40084: 0}, # Emergency power not supported
["sensor.e3_dc_s10_x_emergency_power"],
id="no_emergency_power",
),
pytest.param(
{40208: int32_words(0)},
{40208: int32_words(0)}, # Battery full charge energy, in Wh
BATTERY_LIMIT_SENSORS,
id="no_battery_capacity",
),
@@ -152,12 +180,12 @@ async def test_optional_hardware_missing(
("refused_register", "entity_ids"),
[
pytest.param(
40137,
40137, # Start of the SG Ready status and 32-bit power meter block
["sensor.e3_dc_s10_x_sg_ready_status"],
id="no_wide_power_meters",
),
pytest.param(
40186,
40186, # Start of the grid control block
[
"sensor.e3_dc_s10_x_active_power_failsafe_timeout",
"sensor.e3_dc_s10_x_reactive_power_failsafe_timeout",
@@ -165,11 +193,23 @@ async def test_optional_hardware_missing(
id="no_grid_control",
),
pytest.param(
40200,
40200, # Start of the inverter mode block
["sensor.e3_dc_s10_x_inverter_mode"],
id="no_inverter_mode_control",
),
pytest.param(40202, BATTERY_LIMIT_SENSORS, id="no_battery_limits"),
pytest.param(
40202, # Start of the battery limits block
BATTERY_LIMIT_SENSORS,
id="no_battery_limits",
),
pytest.param(
41000, # Start of the inverter slot 0 block
[
"sensor.e3_dc_s10_x_inverter_1_active_power_l1",
"sensor.e3_dc_s10_x_inverter_1_dc_power_1",
],
id="no_inverters",
),
],
)
@pytest.mark.usefixtures("mock_get_unit")
@@ -190,3 +230,176 @@ async def test_block_missing_from_firmware(
assert hass.states.get(PV_POWER) is not None
for entity_id in entity_ids:
assert entity_registry.async_get(entity_id) is None
def _part_devices(
device_registry: dr.DeviceRegistry, entry: MockConfigEntry
) -> dict[str, tuple[str | None, str]]:
"""The part devices' names and how they link to the power station.
The devices are keyed by their identifier without the serial number.
"""
station = device_registry.async_get_device_by_identifier(
(DOMAIN, MOCK_SERIAL), entry.entry_id
)
connected = [
device
for device in dr.async_entries_for_config_entry(device_registry, entry.entry_id)
if device.via_device_id == station.id
]
children = dr.async_entries_for_parent_device(device_registry, station.id)
return {
identifier.removeprefix(f"{MOCK_SERIAL}_"): (device.name, relation)
for relation, devices in (("via", connected), ("child", children))
for device in devices
for _, identifier in device.identifiers
}
@pytest.mark.parametrize(
("holding", "devices"),
[
pytest.param(
{},
{
"power_meter_2": ("Power meter 2", "via"),
"inverter_1": ("Inverter 1", "child"),
},
id="one_of_each",
),
pytest.param(
{
40113: 4, # Power meter slot 2 measures external consumption
41052: 2302, # Inverter slot 1 voltage L1, in 0.1 V
},
{
"power_meter_2": ("Power meter 2", "via"),
"power_meter_3": ("Power meter 3", "via"),
"inverter_1": ("Inverter 1", "child"),
"inverter_2": ("Inverter 2", "via"),
},
id="several",
),
],
)
@pytest.mark.usefixtures("mock_get_unit")
async def test_part_devices(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_unit: MockModbusUnit,
mock_config_entry: MockConfigEntry,
holding: dict[int, int | list[int]],
devices: dict[str, tuple[str, str]],
) -> None:
"""Test the power meters and inverters get a device named after their slot."""
seed(mock_unit, holding)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# The power station's own inverter is a child device, the other parts are
# connected through it. The meter at the grid connection point has no device.
assert _part_devices(device_registry, mock_config_entry) == devices
@pytest.mark.parametrize(
("setup_holding", "holding", "entity_id"),
[
pytest.param(
{},
{
40113: 2, # Power meter slot 2 measures external production
40150: int32_words(300), # Power meter slot 2 power L1, 32 bit
},
"sensor.power_meter_3_power",
id="power_meter",
),
pytest.param(
{},
{
41052: 2302, # Inverter slot 1 voltage L1, in 0.1 V
41040: int32_words(1200), # Inverter slot 1 active power L1, in W
},
"sensor.inverter_2_active_power_l1",
id="inverter",
),
pytest.param(
{40105: 0}, # Power meter slot 0 not installed
{40105: 1}, # Power meter slot 0 at the grid connection point
GRID_POWER_L1,
id="grid_meter",
),
],
)
@pytest.mark.usefixtures("mock_get_unit")
async def test_added_when_reported(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
entity_registry: er.EntityRegistry,
mock_unit: MockModbusUnit,
mock_config_entry: MockConfigEntry,
setup_holding: dict[int, int | list[int]],
holding: dict[int, int | list[int]],
entity_id: str,
) -> None:
"""Test hardware the power station reports after setup gets its sensors."""
seed(mock_unit, setup_holding)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert entity_registry.async_get(entity_id) is None
seed(mock_unit, holding)
freezer.tick(timedelta(seconds=SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert entity_registry.async_get(entity_id) is not None
@pytest.mark.parametrize(
("setup_holding", "holding", "entity_id"),
[
pytest.param(
{},
{40109: 0}, # Power meter slot 1 not installed
"sensor.power_meter_2_power",
id="power_meter",
),
pytest.param(
{41052: 2302}, # Inverter slot 1 voltage L1, connected
{41052: 0}, # Inverter slot 1 voltage L1, disconnected
"sensor.inverter_2_active_power_l1",
id="inverter",
),
pytest.param(
{},
{40105: 0}, # Power meter slot 0 not installed
GRID_POWER_L1,
id="grid_meter",
),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_get_unit")
async def test_unavailable_when_hardware_gone(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_unit: MockModbusUnit,
mock_config_entry: MockConfigEntry,
setup_holding: dict[int, int | list[int]],
holding: dict[int, int | list[int]],
entity_id: str,
) -> None:
"""Test sensors become unavailable once their hardware is gone."""
seed(mock_unit, setup_holding)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
seed(mock_unit, holding)
freezer.tick(timedelta(seconds=SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE