From 61557063e927be2bd89a164bdf711031cc6a58d7 Mon Sep 17 00:00:00 2001 From: "Brett Adams (Firstmate)" Date: Tue, 17 Nov 2026 11:30:49 +1000 Subject: [PATCH] Add typed Powerwall readers for unit, PV string, islander and site info data --- tesla_fleet_api/tesla/powerwall/__init__.py | 34 +- tesla_fleet_api/tesla/powerwall/client.py | 64 ++- tesla_fleet_api/tesla/powerwall/components.py | 182 +++++- .../fixtures/powerwall_components.json | 528 ++++++++++++++++++ .../powerwall/fixtures/powerwall_config.json | 20 + .../powerwall/fixtures/powerwall_status.json | 95 ++++ tests/powerwall/test_readings.py | 301 ++++++++++ 7 files changed, 1221 insertions(+), 3 deletions(-) create mode 100644 tests/powerwall/fixtures/powerwall_components.json create mode 100644 tests/powerwall/fixtures/powerwall_config.json create mode 100644 tests/powerwall/fixtures/powerwall_status.json create mode 100644 tests/powerwall/test_readings.py diff --git a/tesla_fleet_api/tesla/powerwall/__init__.py b/tesla_fleet_api/tesla/powerwall/__init__.py index 85b59d0..a32f704 100644 --- a/tesla_fleet_api/tesla/powerwall/__init__.py +++ b/tesla_fleet_api/tesla/powerwall/__init__.py @@ -20,27 +20,43 @@ DEFAULT_GATEWAY_HOST, GRID_EXPORT_RULES, OPERATION_MODES, + IslanderPhase, + IslanderSide, PowerwallClient, + SiteInfo, backup_time_remaining, battery_level, battery_level_raw, current_power, + islander_frequency, + islander_voltage, raw_to_scaled_reserve, raw_to_scaled_soc, scaled_to_raw_reserve, scaled_to_raw_soc, + site_info, ) from .components import ( + PV_STRING_STATES, + PV_STRINGS, BatteryRole, BatteryUnit, + BatteryUnitReadings, + PvString, + PvStringState, SignalValue, + battery_unit_readings, battery_units, component, component_float, component_part_number, component_serial, component_signal, + pv_power, pv_string_current, + pv_string_state, + pv_string_voltage, + pv_strings, ) from .energysite import ( ISLAND_MODE_OFF_GRID, @@ -81,6 +97,8 @@ "ISLAND_MODE_OFF_GRID", "ISLAND_MODE_ON_GRID", "OPERATION_MODES", + "PV_STRINGS", + "PV_STRING_STATES", "AuthorizationRole", "AuthorizedClient", "AuthorizedClientState", @@ -92,30 +110,37 @@ "BatteryCalibrationDelayStatus", "BatteryRole", "BatteryUnit", + "BatteryUnitReadings", "ComponentsPayload", "ConfigPayload", "ControllableDeviceProgram", "ControllableDeviceProgramsPayload", "ControllerPayload", "FirmwareDetails", + "IslanderPhase", + "IslanderSide", "ManualBackupInfo", "PowerLocation", "PowerwallAuthenticationError", "PowerwallClient", "PowerwallCommandError", "PowerwallConnectionError", - "PowerwallEnergySite", "PowerwallEmptyReplyError", + "PowerwallEnergySite", "PowerwallError", "PowerwallFaultError", "PowerwallNotSupportedError", "PowerwallProtocolError", "PowerwallRateLimitError", + "PvString", + "PvStringState", "SignalValue", + "SiteInfo", "StatusPayload", "backup_time_remaining", "battery_level", "battery_level_raw", + "battery_unit_readings", "battery_units", "component", "component_float", @@ -123,9 +148,16 @@ "component_serial", "component_signal", "current_power", + "islander_frequency", + "islander_voltage", + "pv_power", "pv_string_current", + "pv_string_state", + "pv_string_voltage", + "pv_strings", "raw_to_scaled_reserve", "raw_to_scaled_soc", "scaled_to_raw_reserve", "scaled_to_raw_soc", + "site_info", ] diff --git a/tesla_fleet_api/tesla/powerwall/client.py b/tesla_fleet_api/tesla/powerwall/client.py index 6c5316e..14283b9 100644 --- a/tesla_fleet_api/tesla/powerwall/client.py +++ b/tesla_fleet_api/tesla/powerwall/client.py @@ -27,7 +27,8 @@ import time from collections.abc import Callable, Mapping from types import TracebackType -from typing import Any, Final, cast +from dataclasses import dataclass +from typing import Any, Final, Literal, cast import aiohttp from google.protobuf.timestamp_pb2 import Timestamp @@ -1702,6 +1703,61 @@ def current_power(status: StatusPayload) -> dict[str, float | None]: } +IslanderPhase = Literal[1, 2, 3] +IslanderSide = Literal["main", "load"] +"""``main`` is the grid side of the islanding contactor, ``load`` the home side.""" + + +def _islander_measurement(status: StatusPayload, field: str) -> float | None: + value = _lookup(status, "esCan", "bus", "ISLANDER", "ISLAND_AcMeasurements", field) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + return float(value) + + +def islander_frequency( + status: StatusPayload, phase: IslanderPhase, side: IslanderSide +) -> float | None: + """Return the islander's measured frequency in Hz for ``phase`` and ``side``.""" + return _islander_measurement(status, f"ISLAND_FreqL{phase}_{side.capitalize()}") + + +def islander_voltage( + status: StatusPayload, phase: IslanderPhase, side: IslanderSide +) -> float | None: + """Return the islander's measured line-to-neutral voltage for ``phase`` and ``side``. + + A single phase site reports near zero on phases 2 and 3. + """ + return _islander_measurement(status, f"ISLAND_VL{phase}N_{side.capitalize()}") + + +@dataclass(frozen=True, slots=True) +class SiteInfo: + """The grid connection settings in the gateway's ``config.json`` ``site_info``. + + Each value is None when the gateway does not report it as text. + """ + + grid_code: str | None + country: str | None + distributor: str | None + + +def site_info(config: ConfigPayload) -> SiteInfo: + """Return the grid connection settings from a :meth:`PowerwallClient.get_config` payload.""" + + def text(key: str) -> str | None: + value = _lookup(config, "site_info", key) + return value if isinstance(value, str) else None + + return SiteInfo( + grid_code=text("grid_code"), + country=text("country"), + distributor=text("distributor"), + ) + + def backup_time_remaining(status: StatusPayload) -> float | None: """Estimated backup runtime in hours at current load, or None if unknown.""" remaining = _lookup( @@ -1717,13 +1773,19 @@ def backup_time_remaining(status: StatusPayload) -> float | None: "DEFAULT_GATEWAY_HOST", "GRID_EXPORT_RULES", "OPERATION_MODES", + "IslanderPhase", + "IslanderSide", "PowerwallClient", + "SiteInfo", "backup_time_remaining", "battery_level", "battery_level_raw", "current_power", + "islander_frequency", + "islander_voltage", "raw_to_scaled_reserve", "raw_to_scaled_soc", "scaled_to_raw_reserve", "scaled_to_raw_soc", + "site_info", ] diff --git a/tesla_fleet_api/tesla/powerwall/components.py b/tesla_fleet_api/tesla/powerwall/components.py index 0f6a128..98f4f0f 100644 --- a/tesla_fleet_api/tesla/powerwall/components.py +++ b/tesla_fleet_api/tesla/powerwall/components.py @@ -13,7 +13,7 @@ import logging from collections.abc import Mapping from dataclasses import dataclass -from typing import Any, Literal, cast +from typing import Any, Final, Literal, cast from .models import ComponentsPayload, ConfigPayload, StatusPayload @@ -26,6 +26,19 @@ BatteryRole = Literal["leader", "follower", "expansion"] +PV_STRINGS: Final = ("A", "B", "C", "D", "E", "F") +"""The PV string inputs of a Powerwall 3 PCH.""" + +PvStringState = Literal["active", "active_parallel", "standby"] + +_PV_STRING_STATES: Final[dict[str, PvStringState]] = { + "Pv_Active": "active", + "Pv_Active_Parallel": "active_parallel", + "Pv_Standby": "standby", +} +PV_STRING_STATES: Final[tuple[PvStringState, ...]] = tuple(_PV_STRING_STATES.values()) +"""Every value :func:`pv_string_state` can return.""" + def _path(data: Any, *keys: str | int) -> Any: """Walk nested mappings and lists; return None if a step is missing.""" @@ -106,6 +119,37 @@ def pv_string_current( return value +def pv_string_voltage( + components: ComponentsPayload, string: str, slot: int = 0 +) -> float | None: + """Return PCH PV string ``string`` (``"A"``-``"F"``) voltage in volts.""" + return component_float(components, "pch", f"PCH_PvVoltage{string}", slot) + + +def pv_string_state( + components: ComponentsPayload, string: str, slot: int = 0 +) -> PvStringState | None: + """Return the state of PCH PV string ``string`` (``"A"``-``"F"``). + + Only the states in :data:`PV_STRING_STATES` are returned; any other + gateway value returns None. + """ + value = component_signal(components, "pch", f"PCH_PvState_{string}", slot) + return _PV_STRING_STATES.get(value) if isinstance(value, str) else None + + +def pv_power(components: ComponentsPayload, slot: int = 0) -> float | None: + """Return the total PV power of the PCH at ``slot`` in watts.""" + return component_float(components, "pch", "PCH_SlowPvPowerSum", slot) + + +def _component_text( + components: ComponentsPayload, kind: str, name: str, slot: int +) -> str | None: + value = component_signal(components, kind, name, slot) + return value if isinstance(value, str) else None + + def component_serial(components: ComponentsPayload, slot: int) -> str | None: """Return the first non-empty serial number reported for component ``slot``.""" for kind in ("hvp", "bms", "pch", "baggr"): @@ -144,6 +188,15 @@ class BatteryUnit: serial_number: str | None part_number: str | None + @property + def unit_id(self) -> str | None: + """Return a stable id for this unit: its serial number for an expansion, else its DIN. + + An expansion's DIN is only in ``config.json``, so its serial number is + the id that is known from the status and components payloads alone. + """ + return self.serial_number if self.role == "expansion" else self.din + def _din(item: Mapping[str, Any]) -> str | None: for key in ("din", "vin"): @@ -386,15 +439,142 @@ def battery_units( return tuple(units) +@dataclass(frozen=True, slots=True) +class PvString: + """One PV string input of a Powerwall 3.""" + + voltage: float | None + """Volts.""" + current: float | None + """Amps, with idle noise read as 0.0 (see :func:`pv_string_current`).""" + state: PvStringState | None + + +def pv_strings(components: ComponentsPayload, slot: int = 0) -> dict[str, PvString]: + """Return every PV string of the PCH at ``slot``, keyed by :data:`PV_STRINGS`.""" + return { + string: PvString( + voltage=pv_string_voltage(components, string, slot), + current=pv_string_current(components, string, slot), + state=pv_string_state(components, string, slot), + ) + for string in PV_STRINGS + } + + +@dataclass(frozen=True, slots=True) +class BatteryUnitReadings: + """The components-payload readings of one :class:`BatteryUnit`. + + Every value is None when the gateway does not report it for the unit. + An expansion has no PCH or PWS, so its PCH and PWS readings are always + None and its PV strings are all None, rather than another unit's row at + the same slot. + """ + + energy_remaining: float | None + """BMS nominal energy remaining, kWh.""" + full_pack_energy: float | None + """BMS nominal full pack energy, kWh.""" + percentage_charged: float | None + """``energy_remaining / full_pack_energy * 100``. + + This is the raw pack ratio, including the bottom buffer that + :func:`~tesla_fleet_api.tesla.powerwall.battery_level` scales out, so it + reads slightly above the site percentage. None while either value is + missing or the full pack energy is 0. + """ + hvp_state: str | None + """The gateway's own text, such as ``HVP_ACTIVE``.""" + hvp_firmware: str | None + battery_connection_status: str | None + """The battery aggregator's status for this slot, such as ``CONNECTED``.""" + battery_power: float | None + """PCH battery power, W.""" + ac_power: float | None + """PCH AC real power, W.""" + ac_voltage_ab: float | None + ac_voltage_an: float | None + ac_voltage_bn: float | None + ac_frequency: float | None + """Hz.""" + pch_state: str | None + """The gateway's own text, such as ``Pch_Active``.""" + pch_firmware: str | None + pws_firmware: str | None + pv_strings: dict[str, PvString] + """Keyed by :data:`PV_STRINGS`.""" + + +def battery_unit_readings( + components: ComponentsPayload, unit: BatteryUnit +) -> BatteryUnitReadings: + """Return the readings of ``unit`` from a components payload.""" + slot = unit.component_slot + powerwall = unit.role != "expansion" + + def number(kind: str, name: str) -> float | None: + return component_float(components, kind, name, slot) + + def text(kind: str, name: str) -> str | None: + return _component_text(components, kind, name, slot) + + def powerwall_number(name: str) -> float | None: + return number("pch", name) if powerwall else None + + def powerwall_text(kind: str, name: str) -> str | None: + return text(kind, name) if powerwall else None + + remaining = number("bms", "BMS_nominalEnergyRemaining") + full = number("bms", "BMS_nominalFullPackEnergy") + return BatteryUnitReadings( + energy_remaining=remaining, + full_pack_energy=full, + percentage_charged=( + remaining / full * 100 if remaining is not None and full else None + ), + hvp_state=text("hvp", "HVP_State"), + hvp_firmware=text("hvp", "HVP_appGitHash"), + # The battery aggregator reports one connection status per slot. + battery_connection_status=_component_text( + components, "baggr", f"BAGGR_LOG_BattConnectionStatus{slot}", 0 + ), + battery_power=powerwall_number("PCH_BatteryPower"), + ac_power=powerwall_number("PCH_AcRealPowerAB"), + ac_voltage_ab=powerwall_number("PCH_AcVoltageAB"), + ac_voltage_an=powerwall_number("PCH_AcVoltageAN"), + ac_voltage_bn=powerwall_number("PCH_AcVoltageBN"), + ac_frequency=powerwall_number("PCH_AcFrequency"), + pch_state=powerwall_text("pch", "PCH_State"), + pch_firmware=powerwall_text("pch", "PCH_appGitHash"), + pws_firmware=powerwall_text("pws", "PWS_appGitHash"), + pv_strings=( + pv_strings(components, slot) + if powerwall + else dict.fromkeys(PV_STRINGS, PvString(None, None, None)) + ), + ) + + __all__ = [ + "PV_STRINGS", + "PV_STRING_STATES", "BatteryRole", "BatteryUnit", + "BatteryUnitReadings", + "PvString", + "PvStringState", "SignalValue", + "battery_unit_readings", "battery_units", "component", "component_float", "component_part_number", "component_serial", "component_signal", + "pv_power", "pv_string_current", + "pv_string_state", + "pv_string_voltage", + "pv_strings", ] diff --git a/tests/powerwall/fixtures/powerwall_components.json b/tests/powerwall/fixtures/powerwall_components.json new file mode 100644 index 0000000..1399a27 --- /dev/null +++ b/tests/powerwall/fixtures/powerwall_components.json @@ -0,0 +1,528 @@ +{ + "components": { + "pch": [ + { + "signals": [ + { + "name": "PCH_State", + "value": null, + "textValue": "Pch_Active", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvVoltageA", + "value": 385.2, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvVoltageB", + "value": 379.6, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvVoltageC", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvVoltageD", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvVoltageE", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvVoltageF", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvCurrentA", + "value": 6.42, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvCurrentB", + "value": 6.31, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvCurrentC", + "value": 1.2e-16, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvCurrentD", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvCurrentE", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvCurrentF", + "value": 0.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvState_A", + "value": null, + "textValue": "Pv_Active", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvState_B", + "value": null, + "textValue": "Pv_Active", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvState_C", + "value": null, + "textValue": "Pv_Standby", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvState_D", + "value": null, + "textValue": "Pv_Standby", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvState_E", + "value": null, + "textValue": "Pv_Standby", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_PvState_F", + "value": null, + "textValue": "Pv_Standby", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_SlowPvPowerSum", + "value": 4868.0, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_BatteryPower", + "value": 1020, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_AcRealPowerAB", + "value": 880, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_AcVoltageAB", + "value": 238.4, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_AcVoltageAN", + "value": 118.8, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_AcVoltageBN", + "value": 119.6, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_AcFrequency", + "value": 50.0025, + "textValue": null, + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + }, + { + "name": "PCH_appGitHash", + "value": null, + "textValue": "4f924de839f0c4", + "boolValue": null, + "timestamp": "2026-10-13T00:00:00+10:00" + } + ], + "activeAlerts": [] + } + ], + "pws": [ + { + "activeAlerts": [], + "signals": [ + { + "boolValue": null, + "name": "PWS_SelfTest", + "textValue": "SELFTEST_STATE_DONE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "PWS_PeImpTestState", + "textValue": "PE_IMPEDANCE_DONE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "PWS_PvIsoTestState", + "textValue": "PV_ISOLATION_DONE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "PWS_RelaySelfTest_State", + "textValue": "RELAY_SELFTEST_DONE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "PWS_MciTestState", + "textValue": "MCI_MODULE_TEST_STANDBY", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "PWS_appGitHash", + "textValue": "04d5dd98fb2037", + "timestamp": "2026-05-12T20:56:09+10:00", + "value": null + }, + { + "boolValue": true, + "name": "PWS_ProdSwitch_State", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + } + ] + } + ], + "bms": [ + { + "activeAlerts": [], + "signals": [ + { + "boolValue": null, + "name": "BMS_nominalEnergyRemaining", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 10.540000000000001 + }, + { + "boolValue": null, + "name": "BMS_nominalFullPackEnergy", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 14.42 + }, + { + "boolValue": null, + "name": "BMS_appGitHash", + "textValue": null, + "timestamp": null, + "value": null + } + ] + }, + { + "activeAlerts": [], + "signals": [ + { + "boolValue": null, + "name": "BMS_nominalEnergyRemaining", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 11.83 + }, + { + "boolValue": null, + "name": "BMS_nominalFullPackEnergy", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 14.42 + }, + { + "boolValue": null, + "name": "BMS_appGitHash", + "textValue": null, + "timestamp": null, + "value": null + } + ] + }, + { + "activeAlerts": [], + "signals": [ + { + "boolValue": null, + "name": "BMS_nominalEnergyRemaining", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 11.27 + }, + { + "boolValue": null, + "name": "BMS_nominalFullPackEnergy", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 14.38 + }, + { + "boolValue": null, + "name": "BMS_appGitHash", + "textValue": null, + "timestamp": null, + "value": null + } + ] + }, + { + "activeAlerts": [ + { + "name": "BMS_a037_SW_NVRAM_Config_Error" + }, + { + "name": "BMS_a048_SW_HVP_HVI_Comms" + }, + { + "name": "BMS_a083_Nvram_Filecache" + } + ], + "signals": [ + { + "boolValue": null, + "name": "BMS_nominalEnergyRemaining", + "textValue": null, + "timestamp": null, + "value": null + }, + { + "boolValue": null, + "name": "BMS_nominalFullPackEnergy", + "textValue": null, + "timestamp": null, + "value": null + }, + { + "boolValue": null, + "name": "BMS_appGitHash", + "textValue": null, + "timestamp": null, + "value": null + } + ] + } + ], + "hvp": [ + { + "activeAlerts": [], + "partNumber": "1800420-11-F", + "serialNumber": "TG10000000001B", + "signals": [ + { + "boolValue": null, + "name": "HVP_State", + "textValue": "HVP_ACTIVE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "HVP_appGitHash", + "textValue": "04d5dd98fb2037", + "timestamp": "2026-05-12T20:55:58+10:00", + "value": null + } + ] + }, + { + "activeAlerts": [], + "partNumber": "1807000-20-B", + "serialNumber": "TG10000000002C", + "signals": [ + { + "boolValue": null, + "name": "HVP_State", + "textValue": "HVP_ACTIVE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "HVP_appGitHash", + "textValue": "04d5dd98fb2037", + "timestamp": "2026-05-12T20:56:04+10:00", + "value": null + } + ] + }, + { + "activeAlerts": [], + "partNumber": "1807000-20-B", + "serialNumber": "TG10000000003D", + "signals": [ + { + "boolValue": null, + "name": "HVP_State", + "textValue": "HVP_ACTIVE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "HVP_appGitHash", + "textValue": "04d5dd98fb2037", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + } + ] + }, + { + "activeAlerts": [], + "partNumber": "", + "serialNumber": "", + "signals": [ + { + "boolValue": null, + "name": "HVP_State", + "textValue": null, + "timestamp": null, + "value": null + }, + { + "boolValue": null, + "name": "HVP_appGitHash", + "textValue": null, + "timestamp": null, + "value": null + } + ] + } + ], + "baggr": [ + { + "activeAlerts": [], + "signals": [ + { + "boolValue": null, + "name": "BAGGR_State", + "textValue": "BAGGR_ACTIVE", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "BAGGR_OperationRequest", + "textValue": "BAGGR_NORMAL_OPERATION", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "BAGGR_NumBatteriesConnected", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 3 + }, + { + "boolValue": null, + "name": "BAGGR_NumBatteriesPresent", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 3 + }, + { + "boolValue": null, + "name": "BAGGR_NumBatteriesExpected", + "textValue": null, + "timestamp": "2026-05-12T20:56:13+10:00", + "value": 3 + }, + { + "boolValue": null, + "name": "BAGGR_LOG_BattConnectionStatus0", + "textValue": "CONNECTED", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "BAGGR_LOG_BattConnectionStatus1", + "textValue": "CONNECTED", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "BAGGR_LOG_BattConnectionStatus2", + "textValue": "CONNECTED", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + }, + { + "boolValue": null, + "name": "BAGGR_LOG_BattConnectionStatus3", + "textValue": "NOT_TARGETED_NOT_PRESENT", + "timestamp": "2026-05-12T20:56:13+10:00", + "value": null + } + ] + } + ] + } +} diff --git a/tests/powerwall/fixtures/powerwall_config.json b/tests/powerwall/fixtures/powerwall_config.json new file mode 100644 index 0000000..14f898b --- /dev/null +++ b/tests/powerwall/fixtures/powerwall_config.json @@ -0,0 +1,20 @@ +{ + "vin": "1707000-00-A--TG000000000000", + "site_info": { + "net_meter_mode": "battery_ok", + "customer_preferred_export_rule": "battery_ok", + "backup_reserve_percent": 20, + "nominal_system_energy_ac": 13.5, + "nominal_system_power_ac": 5.8, + "grid_code": "50Hz_230V_1_SMC_ASNZS4777.2_2020_AUS_A", + "country": "Australia", + "state": "Queensland", + "distributor": "Energex", + "utility": "*", + "retailer": "*", + "region": "ASNZS4777.2:2020_AUS_A", + "site_name": "Energy Site", + "timezone": "Australia/Brisbane" + }, + "default_real_mode": "self_consumption" +} diff --git a/tests/powerwall/fixtures/powerwall_status.json b/tests/powerwall/fixtures/powerwall_status.json new file mode 100644 index 0000000..be887bc --- /dev/null +++ b/tests/powerwall/fixtures/powerwall_status.json @@ -0,0 +1,95 @@ +{ + "control": { + "islanding": { + "contactorClosed": true, + "customerIslandMode": "BACKUP", + "gridOK": true, + "microGridOK": true + }, + "meterAggregates": [ + { + "location": "BATTERY", + "realPowerW": -1250 + }, + { + "location": "SITE", + "realPowerW": 20 + }, + { + "location": "LOAD", + "realPowerW": 1630 + }, + { + "location": "SOLAR", + "realPowerW": 2860 + }, + { + "location": "SOLAR_RGM", + "realPowerW": 2840 + }, + { + "location": "GENERATOR", + "realPowerW": 0 + }, + { + "location": "CONDUCTOR", + "realPowerW": 0 + } + ], + "siteShutdown": { + "isShutDown": false, + "reasons": [] + }, + "batteryBlocks": [ + { + "din": "1707000-30-L--TG10000000000A", + "disableReasons": [] + } + ], + "systemStatus": { + "nominalEnergyRemainingWh": 33650, + "nominalFullPackEnergyWh": 43200 + } + }, + "esCan": { + "bus": { + "ISLANDER": { + "ISLAND_AcMeasurements": { + "ISLAND_FreqL1_Load": 50.01, + "ISLAND_FreqL1_Main": 50.01, + "ISLAND_FreqL2_Load": 50.01, + "ISLAND_FreqL2_Main": 50.01, + "ISLAND_FreqL3_Load": 50.01, + "ISLAND_FreqL3_Main": 50.03, + "ISLAND_GridState": "ISLAND_GridState_Grid_Compliant", + "ISLAND_VL1N_Load": 239.5, + "ISLAND_VL1N_Main": 240.5, + "ISLAND_VL2N_Load": 7.5, + "ISLAND_VL2N_Main": 7.5, + "ISLAND_VL3N_Load": 1.5, + "ISLAND_VL3N_Main": 0.5, + "isComplete": true, + "isMIA": false + } + } + }, + "firmwareUpdate": { + "isUpdating": false, + "msa": null, + "powerwalls": null, + "pvInverters": null, + "sync": null + } + }, + "pw3Can": { + "firmwareUpdate": { + "isUpdating": false, + "progress": null + } + }, + "system": { + "sitemanagerStatus": { + "isRunning": true + } + } +} diff --git a/tests/powerwall/test_readings.py b/tests/powerwall/test_readings.py new file mode 100644 index 0000000..8a72f9c --- /dev/null +++ b/tests/powerwall/test_readings.py @@ -0,0 +1,301 @@ +"""Unit tests for the typed readers over the status, config and components payloads. + +``fixtures/powerwall_{status,config,components}.json`` are a Powerwall 3 +leader with two expansions and an empty fourth component slot, with serial +numbers replaced. The single Powerwall and leader + follower sites are +derived from them. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest + +from tesla_fleet_api.tesla.powerwall import ( + PV_STRING_STATES, + PV_STRINGS, + BatteryUnit, + PvString, + battery_unit_readings, + battery_units, + islander_frequency, + islander_voltage, + pv_power, + pv_string_state, + pv_strings, + site_info, +) + +FIXTURES = Path(__file__).parent / "fixtures" +STATUS: dict[str, Any] = json.loads((FIXTURES / "powerwall_status.json").read_text()) +CONFIG: dict[str, Any] = json.loads((FIXTURES / "powerwall_config.json").read_text()) +COMPONENTS: dict[str, Any] = json.loads( + (FIXTURES / "powerwall_components.json").read_text() +) +LEADER_DIN = "1707000-30-L--TG10000000000A" +FOLLOWER_DIN = "1707000-30-L--TG10000000004E" +NO_PV = PvString(voltage=None, current=None, state=None) + + +def _set_signal(row: dict[str, Any], name: str, value: Any) -> None: + for signal in row["signals"]: + if signal["name"] == name: + signal["value"] = None + signal["textValue"] = None + signal["value" if isinstance(value, (int, float)) else "textValue"] = value + return + raise AssertionError(name) + + +@pytest.fixture +def components() -> dict[str, Any]: + return copy.deepcopy(COMPONENTS) + + +@pytest.fixture +def single_powerwall() -> dict[str, Any]: + """A Powerwall 3 with no expansions.""" + components = copy.deepcopy(COMPONENTS) + for kind in ("bms", "hvp"): + components["components"][kind] = components["components"][kind][:1] + return components + + +@pytest.fixture +def leader_and_follower() -> tuple[dict[str, Any], dict[str, Any]]: + """A leader and one follower Powerwall 3, each with its own PCH and PWS row.""" + status = copy.deepcopy(STATUS) + status["control"]["batteryBlocks"].append( + {"din": FOLLOWER_DIN, "disableReasons": []} + ) + status["control"]["systemStatus"]["nominalFullPackEnergyWh"] = 28840 + components = copy.deepcopy(COMPONENTS) + for kind in ("bms", "hvp"): + components["components"][kind] = components["components"][kind][:2] + components["components"]["hvp"][1]["partNumber"] = "1707000-30-L" + for kind in ("pch", "pws"): + components["components"][kind].append( + copy.deepcopy(components["components"][kind][0]) + ) + follower_pch = components["components"]["pch"][1] + _set_signal(follower_pch, "PCH_PvVoltageA", 401.5) + _set_signal(follower_pch, "PCH_PvState_A", "Pv_Active_Parallel") + _set_signal(follower_pch, "PCH_BatteryPower", -2500) + _set_signal(follower_pch, "PCH_SlowPvPowerSum", 1200.0) + _set_signal(components["components"]["pws"][1], "PWS_appGitHash", "abc123") + return status, components + + +# ── Battery units ─────────────────────────────────────────────────────────── + + +def test_leader_with_expansions(components: dict[str, Any]) -> None: + units = battery_units({}, STATUS, components) + assert [(u.role, u.component_slot, u.unit_id) for u in units] == [ + ("leader", 0, LEADER_DIN), + ("expansion", 1, "TG10000000002C"), + ("expansion", 2, "TG10000000003D"), + ] + leader = battery_unit_readings(components, units[0]) + assert leader.energy_remaining == pytest.approx(10.54) + assert leader.full_pack_energy == 14.42 + assert leader.percentage_charged == pytest.approx(10.54 / 14.42 * 100) + assert leader.hvp_state == "HVP_ACTIVE" + assert leader.hvp_firmware == "04d5dd98fb2037" + assert leader.battery_connection_status == "CONNECTED" + assert leader.battery_power == 1020.0 + assert leader.ac_power == 880.0 + assert leader.ac_voltage_ab == 238.4 + assert leader.ac_voltage_an == 118.8 + assert leader.ac_voltage_bn == 119.6 + assert leader.ac_frequency == 50.0025 + assert leader.pch_state == "Pch_Active" + assert leader.pch_firmware == "4f924de839f0c4" + assert leader.pws_firmware == "04d5dd98fb2037" + assert leader.pv_strings == pv_strings(components) + + expansion = battery_unit_readings(components, units[2]) + assert expansion.energy_remaining == 11.27 + assert expansion.full_pack_energy == 14.38 + assert expansion.hvp_state == "HVP_ACTIVE" + assert expansion.battery_connection_status == "CONNECTED" + + +def test_expansion_never_reads_powerwall_rows(components: dict[str, Any]) -> None: + """An expansion's slot must not pick up a Powerwall 3's PCH or PWS row.""" + for kind in ("pch", "pws"): + rows = components["components"][kind] + rows.extend(copy.deepcopy(rows[0]) for _ in range(2)) + expansion = battery_units({}, STATUS, components)[1] + readings = battery_unit_readings(components, expansion) + assert readings.battery_power is None + assert readings.ac_power is None + assert readings.ac_voltage_ab is None + assert readings.ac_voltage_an is None + assert readings.ac_voltage_bn is None + assert readings.ac_frequency is None + assert readings.pch_state is None + assert readings.pch_firmware is None + assert readings.pws_firmware is None + assert readings.pv_strings == dict.fromkeys(PV_STRINGS, NO_PV) + + +def test_single_powerwall(single_powerwall: dict[str, Any]) -> None: + (leader,) = battery_units({}, STATUS, single_powerwall) + assert leader.role == "leader" + assert leader.unit_id == LEADER_DIN + readings = battery_unit_readings(single_powerwall, leader) + assert readings.battery_power == 1020.0 + assert readings.pv_strings["A"] == PvString( + voltage=385.2, current=6.42, state="active" + ) + + +def test_leader_and_follower( + leader_and_follower: tuple[dict[str, Any], dict[str, Any]], +) -> None: + status, components = leader_and_follower + units = battery_units({}, status, components) + assert [(u.role, u.component_slot, u.unit_id) for u in units] == [ + ("leader", 0, LEADER_DIN), + ("follower", 1, FOLLOWER_DIN), + ] + leader = battery_unit_readings(components, units[0]) + follower = battery_unit_readings(components, units[1]) + assert leader.battery_power == 1020.0 + assert follower.battery_power == -2500.0 + assert leader.pws_firmware == "04d5dd98fb2037" + assert follower.pws_firmware == "abc123" + assert follower.energy_remaining == 11.83 + assert follower.battery_connection_status == "CONNECTED" + assert leader.pv_strings["A"] == PvString( + voltage=385.2, current=6.42, state="active" + ) + assert follower.pv_strings["A"] == PvString( + voltage=401.5, current=6.42, state="active_parallel" + ) + assert follower.pv_strings == pv_strings(components, 1) + assert pv_power(components) == 4868.0 + assert pv_power(components, 1) == 1200.0 + + +def test_unit_id_falls_back_to_none() -> None: + expansion = BatteryUnit( + role="expansion", + block_index=0, + component_slot=1, + din="1807000-20-B--TG10000000002C", + serial_number=None, + part_number=None, + ) + assert expansion.unit_id is None + + +def test_percentage_charged_needs_both_energies(components: dict[str, Any]) -> None: + leader = battery_units({}, STATUS, components)[0] + _set_signal(components["components"]["bms"][0], "BMS_nominalFullPackEnergy", 0) + assert battery_unit_readings(components, leader).percentage_charged is None + components["components"]["bms"][0]["signals"] = [] + readings = battery_unit_readings(components, leader) + assert readings.energy_remaining is None + assert readings.percentage_charged is None + + +def test_connection_status_is_read_at_the_unit_slot( + components: dict[str, Any], +) -> None: + _set_signal( + components["components"]["baggr"][0], + "BAGGR_LOG_BattConnectionStatus2", + "NOT_CONNECTED", + ) + units = battery_units({}, STATUS, components) + statuses = [ + battery_unit_readings(components, u).battery_connection_status for u in units + ] + assert statuses == ["CONNECTED", "CONNECTED", "NOT_CONNECTED"] + + +def test_empty_components_read_as_none() -> None: + (leader,) = battery_units({}, {}, {}) + readings = battery_unit_readings({}, leader) + assert readings.energy_remaining is None + assert readings.hvp_state is None + assert readings.battery_connection_status is None + assert readings.battery_power is None + assert readings.pv_strings == dict.fromkeys(PV_STRINGS, NO_PV) + + +# ── PV strings ────────────────────────────────────────────────────────────── + + +def test_pv_strings(components: dict[str, Any]) -> None: + strings = pv_strings(components) + assert list(strings) == list(PV_STRINGS) + assert strings["B"] == PvString(voltage=379.6, current=6.31, state="active") + # The fixture's idle string C reports float noise current. + assert strings["C"] == PvString(voltage=0.0, current=0.0, state="standby") + assert pv_power(components) == 4868.0 + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("Pv_Active", "active"), + ("Pv_Active_Parallel", "active_parallel"), + ("Pv_Standby", "standby"), + ("Pv_Fault", None), + (1, None), + ], +) +def test_pv_string_state_is_an_allowlist( + components: dict[str, Any], raw: Any, expected: str | None +) -> None: + _set_signal(components["components"]["pch"][0], "PCH_PvState_A", raw) + assert pv_string_state(components, "A") == expected + assert expected is None or expected in PV_STRING_STATES + + +def test_pv_readings_missing() -> None: + assert pv_strings({}) == dict.fromkeys(PV_STRINGS, NO_PV) + assert pv_power({}) is None + + +# ── Status and config ─────────────────────────────────────────────────────── + + +def test_islander_measurements() -> None: + assert islander_frequency(STATUS, 1, "load") == 50.01 + assert islander_frequency(STATUS, 3, "main") == 50.03 + assert islander_voltage(STATUS, 1, "main") == 240.5 + assert islander_voltage(STATUS, 2, "load") == 7.5 + assert islander_voltage(STATUS, 3, "main") == 0.5 + + +def test_islander_measurements_missing() -> None: + assert islander_frequency({}, 1, "main") is None + status = copy.deepcopy(STATUS) + measurements = status["esCan"]["bus"]["ISLANDER"]["ISLAND_AcMeasurements"] + measurements["ISLAND_VL1N_Main"] = None + measurements["ISLAND_FreqL1_Main"] = True + assert islander_voltage(status, 1, "main") is None + assert islander_frequency(status, 1, "main") is None + + +def test_site_info() -> None: + info = site_info(CONFIG) + assert info.grid_code == "50Hz_230V_1_SMC_ASNZS4777.2_2020_AUS_A" + assert info.country == "Australia" + assert info.distributor == "Energex" + + +def test_site_info_missing() -> None: + info = site_info({"site_info": {"country": 1}}) + assert info.grid_code is None + assert info.country is None + assert info.distributor is None + assert site_info({}).grid_code is None