Add local Powerwall grid and site binary sensors to Teslemetry (#186730)

This commit is contained in:
Brett Adams
2026-10-21 11:32:37 +02:00
committed by GitHub
parent c3db444e8d
commit 0fc9992a70
12 changed files with 877 additions and 6 deletions
@@ -88,6 +88,7 @@ from .coordinator import (
TeslemetryEnergyHistoryCoordinator,
TeslemetryEnergySiteInfoCoordinator,
TeslemetryEnergySiteLiveCoordinator,
TeslemetryLocalStatusCoordinator,
TeslemetryMetadataCoordinator,
TeslemetryVehicleDataCoordinator,
)
@@ -819,6 +820,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) -
if live_coordinator is not None:
live_coordinator.enable_local_polling(energy_site_api.primary)
local_status_coordinator = (
TeslemetryLocalStatusCoordinator(
hass, entry, energy_site_api.primary.powerwall, site_id
)
if isinstance(energy_site_api, EnergySiteRouter)
else None
)
energysites.append(
TeslemetryEnergyData(
api=energy_site_api,
@@ -829,6 +838,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) -
device=device,
can_local_control=can_local_control,
subentry_id=subentry_id,
local_status_coordinator=local_status_coordinator,
)
)
@@ -1050,6 +1060,9 @@ async def _async_setup_energy_site(
async def _async_refresh_energy_site(energysite: TeslemetryEnergyData) -> None:
"""Cold read the site info, then resolve the site timezone it carries."""
await energysite.info_coordinator.async_config_entry_first_refresh()
if energysite.local_status_coordinator is not None:
# A local gateway failure must not block the cloud entities.
await energysite.local_status_coordinator.async_refresh()
if energysite.history_coordinator is not None:
await energysite.history_coordinator.async_set_time_zone(
energysite.info_coordinator.data.get("installation_time_zone")
@@ -2,7 +2,7 @@
from collections.abc import Callable
from dataclasses import dataclass
from typing import cast, override
from typing import Any, cast, override
from tesla_fleet_api import firmware_at_least
from tesla_fleet_api.const import Scope
@@ -25,6 +25,7 @@ from .const import TeslemetryState
from .entity import (
TeslemetryEnergyInfoEntity,
TeslemetryEnergyLiveEntity,
TeslemetryEnergyLocalStatusEntity,
TeslemetryRootEntity,
TeslemetryVehiclePollingEntity,
TeslemetryVehicleStreamEntity,
@@ -569,6 +570,82 @@ BLUETOOTH_SESSION_DESCRIPTION = TeslemetryBinarySensorEntityDescription(
)
def _status_bool(*path: str) -> Callable[[dict[str, Any]], bool | None]:
"""Return a function reading a boolean at a path in the gateway status."""
def value_fn(data: dict[str, Any]) -> bool | None:
value: Any = data
for key in path:
if not isinstance(value, dict):
return None
value = value.get(key)
return value if isinstance(value, bool) else None
return value_fn
@dataclass(frozen=True, kw_only=True)
class TeslemetryLocalBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Describes a Teslemetry binary sensor read from the local gateway."""
value_fn: Callable[[dict[str, Any]], bool | None]
_site_shut_down = _status_bool("control", "siteShutdown", "isShutDown")
def _site_running(data: dict[str, Any]) -> bool | None:
"""Return if the site is running, which the gateway reports as shut down."""
shut_down = _site_shut_down(data)
return None if shut_down is None else not shut_down
ENERGY_LOCAL_STATUS_DESCRIPTIONS: tuple[
TeslemetryLocalBinarySensorEntityDescription, ...
] = (
TeslemetryLocalBinarySensorEntityDescription(
key="grid_ok",
value_fn=_status_bool("control", "islanding", "gridOK"),
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
),
TeslemetryLocalBinarySensorEntityDescription(
key="microgrid_ok",
value_fn=_status_bool("control", "islanding", "microGridOK"),
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
),
TeslemetryLocalBinarySensorEntityDescription(
key="contactor_closed",
value_fn=_status_bool("control", "islanding", "contactorClosed"),
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
),
TeslemetryLocalBinarySensorEntityDescription(
key="site_running",
value_fn=_site_running,
device_class=BinarySensorDeviceClass.RUNNING,
entity_category=EntityCategory.DIAGNOSTIC,
),
TeslemetryLocalBinarySensorEntityDescription(
key="site_manager_running",
value_fn=_status_bool("system", "sitemanagerStatus", "isRunning"),
device_class=BinarySensorDeviceClass.RUNNING,
entity_category=EntityCategory.DIAGNOSTIC,
),
TeslemetryLocalBinarySensorEntityDescription(
key="escan_firmware_updating",
value_fn=_status_bool("esCan", "firmwareUpdate", "isUpdating"),
entity_category=EntityCategory.DIAGNOSTIC,
),
TeslemetryLocalBinarySensorEntityDescription(
key="pw3can_firmware_updating",
value_fn=_status_bool("pw3Can", "firmwareUpdate", "isUpdating"),
entity_category=EntityCategory.DIAGNOSTIC,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: TeslemetryConfigEntry,
@@ -620,6 +697,15 @@ async def async_setup_entry(
for description in ENERGY_INFO_DESCRIPTIONS
if description.key in energysite.info_coordinator.data
)
entities.extend(
TeslemetryEnergyLocalBinarySensorEntity(energysite, description)
for energysite in entry.runtime_data.energysites
if (coordinator := energysite.local_status_coordinator)
for description in ENERGY_LOCAL_STATUS_DESCRIPTIONS
# Without a first status, add every sensor so they recover with the gateway.
if coordinator.data is None
or description.value_fn(coordinator.data) is not None
)
async_remove_stale_vehicle_entities(
hass,
@@ -849,3 +935,26 @@ class TeslemetryVehicleBluetoothSessionBinarySensorEntity(
"""Handle the Bluetooth session being established or lost."""
self._attr_is_on = connected
self.async_write_ha_state()
class TeslemetryEnergyLocalBinarySensorEntity(
TeslemetryEnergyLocalStatusEntity, BinarySensorEntity
):
"""Teslemetry energy binary sensor read from the local gateway."""
entity_description: TeslemetryLocalBinarySensorEntityDescription
def __init__(
self,
data: TeslemetryEnergyData,
description: TeslemetryLocalBinarySensorEntityDescription,
) -> None:
"""Initialize the binary sensor."""
self.entity_description = description
super().__init__(data, description.key)
@property
@override
def is_on(self) -> bool | None:
"""Return the state of the binary sensor."""
return self.entity_description.value_fn(self.coordinator.data)
@@ -1,5 +1,6 @@
"""Teslemetry Data Coordinator."""
from abc import abstractmethod
from copy import deepcopy
from dataclasses import asdict
from datetime import date, datetime, time, timedelta, tzinfo
@@ -7,7 +8,7 @@ from functools import partial
import logging
from typing import TYPE_CHECKING, Any, override
from aiopowerwall import PowerwallEnergySite, PowerwallError
from aiopowerwall import PowerwallClient, PowerwallEnergySite, PowerwallError
from tesla_fleet_api.const import VehicleDataEndpoint
from tesla_fleet_api.exceptions import (
GatewayTimeout,
@@ -64,6 +65,7 @@ METADATA_INTERVAL = timedelta(hours=1)
ENERGY_LIVE_INTERVAL = timedelta(seconds=5)
ENERGY_LIVE_LOCAL_MAX_BACKOFF = timedelta(minutes=1)
ENERGY_CONFIG_INTERVAL = timedelta(seconds=30)
LOCAL_STATUS_INTERVAL = timedelta(seconds=10)
# Start of the day the energy history totals cover. Kept out of
# ENERGY_HISTORY_FIELDS, which is the list of keys that become sensors.
@@ -558,3 +560,68 @@ class TeslemetryEnergyHistoryCoordinator(DataUpdateCoordinator[dict[str, Any]]):
tzinfo=self.time_zone or dt_util.get_default_time_zone(),
)
self.async_set_updated_data(data)
class TeslemetryLocalCoordinator[_DataT](DataUpdateCoordinator[_DataT]):
"""Base class for polling a locally paired Powerwall gateway."""
config_entry: TeslemetryConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: TeslemetryConfigEntry,
client: PowerwallClient,
name: str,
update_interval: timedelta,
) -> None:
"""Initialize a local Powerwall coordinator."""
super().__init__(
hass,
LOGGER,
config_entry=config_entry,
name=name,
update_interval=update_interval,
)
self.client = client
@abstractmethod
async def _async_fetch(self) -> _DataT:
"""Fetch the payload from the local gateway."""
@override
async def _async_update_data(self) -> _DataT:
"""Update data from the local gateway."""
try:
return await self._async_fetch()
except PowerwallError as e:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="local_update_failed",
translation_placeholders={"message": str(e)},
) from e
class TeslemetryLocalStatusCoordinator(TeslemetryLocalCoordinator[dict[str, Any]]):
"""Class to poll the status of a locally paired Powerwall gateway."""
def __init__(
self,
hass: HomeAssistant,
config_entry: TeslemetryConfigEntry,
client: PowerwallClient,
site_id: int,
) -> None:
"""Initialize the local Powerwall status coordinator."""
super().__init__(
hass,
config_entry,
client,
f"Teslemetry Powerwall Status {site_id}",
LOCAL_STATUS_INTERVAL,
)
@override
async def _async_fetch(self) -> dict[str, Any]:
"""Fetch the gateway status."""
return await self.client.get_status()
@@ -20,6 +20,7 @@ from .coordinator import (
TeslemetryEnergyHistoryCoordinator,
TeslemetryEnergySiteInfoCoordinator,
TeslemetryEnergySiteLiveCoordinator,
TeslemetryLocalStatusCoordinator,
TeslemetryVehicleDataCoordinator,
)
from .models import TeslemetryEnergyData, TeslemetryVehicleData
@@ -202,6 +203,27 @@ class TeslemetryEnergyHistoryEntity(TeslemetryPollingEntity):
"""Keep the streamed totals; the stream is their only source."""
class TeslemetryEnergyLocalStatusEntity(
TeslemetryRootEntity, CoordinatorEntity[TeslemetryLocalStatusCoordinator]
):
"""Parent class for Teslemetry entities read from the local Powerwall status."""
def __init__(
self,
data: TeslemetryEnergyData,
key: str,
) -> None:
"""Initialize common aspects of a Teslemetry local status entity."""
assert data.local_status_coordinator
self._attr_translation_key = key
self._attr_unique_id = f"{data.id}-{key}"
self._attr_device_info = data.device
super().__init__(data.local_status_coordinator)
class TeslemetryWallConnectorEntity(TeslemetryPollingEntity):
"""Parent class for Teslemetry Wall Connector Entities."""
@@ -49,6 +49,9 @@
"on": "mdi:snowflake-melt"
}
},
"escan_firmware_updating": {
"default": "mdi:update"
},
"grid_services_active": {
"state": {
"off": "mdi:transmission-tower-off",
@@ -79,6 +82,9 @@
"on": "mdi:car-light-high"
}
},
"pw3can_firmware_updating": {
"default": "mdi:update"
},
"remote_start_enabled": {
"state": {
"off": "mdi:remote-off",
@@ -17,6 +17,7 @@ from .coordinator import (
TeslemetryEnergyHistoryCoordinator,
TeslemetryEnergySiteInfoCoordinator,
TeslemetryEnergySiteLiveCoordinator,
TeslemetryLocalStatusCoordinator,
TeslemetryMetadataCoordinator,
TeslemetryVehicleDataCoordinator,
)
@@ -66,3 +67,5 @@ class TeslemetryEnergyData:
# Only sites with a battery/Powerwall can pair for local TEDAPI control.
can_local_control: bool
subentry_id: str | None
# Only set when the site is paired with its local gateway.
local_status_coordinator: TeslemetryLocalStatusCoordinator | None = None
@@ -209,6 +209,9 @@
"components_grid_services_enabled": {
"name": "Grid services enabled"
},
"contactor_closed": {
"name": "Contactor closed"
},
"dc_dc_enable": {
"name": "DC to DC converter"
},
@@ -227,6 +230,9 @@
"emergency_lane_departure_avoidance": {
"name": "Emergency lane departure avoidance"
},
"escan_firmware_updating": {
"name": "ESCAN firmware updating"
},
"europe_vehicle": {
"name": "European vehicle"
},
@@ -236,6 +242,9 @@
"gps_state": {
"name": "GPS state"
},
"grid_ok": {
"name": "Grid OK"
},
"grid_services_active": {
"name": "Grid services active"
},
@@ -269,12 +278,18 @@
"located_at_work": {
"name": "Located at work"
},
"microgrid_ok": {
"name": "Microgrid OK"
},
"offroad_lightbar_present": {
"name": "Offroad lightbar"
},
"pin_to_drive_enabled": {
"name": "PIN to Drive enabled"
},
"pw3can_firmware_updating": {
"name": "PW3CAN firmware updating"
},
"rear_display_hvac_enabled": {
"name": "Rear display HVAC"
},
@@ -290,6 +305,12 @@
"service_mode": {
"name": "Service mode"
},
"site_manager_running": {
"name": "Site manager running"
},
"site_running": {
"name": "Site running"
},
"speed_limit_mode": {
"name": "Speed limited"
},
@@ -1269,6 +1290,9 @@
"command_reason": {
"message": "Command was rejected: {reason}"
},
"local_update_failed": {
"message": "Error fetching data from the local Powerwall gateway: {message}"
},
"missing_scope": {
"message": "Missing required scope: {scope}"
},
+11
View File
@@ -20,6 +20,7 @@ from .const import (
METADATA,
METADATA_ENERGY,
METADATA_LEGACY,
POWERWALL_STATUS,
PRODUCTS,
PRODUCTS_ENERGY,
SITE_INFO,
@@ -378,3 +379,13 @@ def mock_powerwall_connect() -> Generator[AsyncMock]:
"aiopowerwall.PowerwallClient.connect", return_value="GATEWAY-DIN"
) as mock_connect:
yield mock_connect
@pytest.fixture(autouse=True)
def mock_powerwall_status() -> Generator[AsyncMock]:
"""Mock the local Powerwall gateway status."""
with patch(
"aiopowerwall.PowerwallClient.get_status",
side_effect=lambda: deepcopy(POWERWALL_STATUS),
) as mock_status:
yield mock_status
+1
View File
@@ -32,6 +32,7 @@ VEHICLE_DATA_NONE["response"]["vehicle_state"]["rt"] = None
VEHICLE_DATA_NONE["response"]["charge_state"]["charge_port_door_open"] = None
LIVE_STATUS = load_json_object_fixture("live_status.json", DOMAIN)
SITE_INFO = load_json_object_fixture("site_info.json", DOMAIN)
POWERWALL_STATUS = load_json_object_fixture("powerwall_status.json", DOMAIN)
SITE_INFO_WEEK_CROSSING = load_json_object_fixture(
"site_info_week_crossing.json", DOMAIN
)
@@ -0,0 +1,34 @@
{
"control": {
"islanding": {
"contactorClosed": true,
"customerIslandMode": "BACKUP",
"gridOK": true,
"microGridOK": true
},
"siteShutdown": {
"isShutDown": false,
"reasons": []
}
},
"esCan": {
"firmwareUpdate": {
"isUpdating": false,
"msa": null,
"powerwalls": null,
"pvInverters": null,
"sync": null
}
},
"pw3Can": {
"firmwareUpdate": {
"isUpdating": false,
"progress": null
}
},
"system": {
"sitemanagerStatus": {
"isRunning": true
}
}
}
@@ -1968,3 +1968,358 @@
'state': 'off',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_contactor_closed-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_contactor_closed',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Contactor closed',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.CONNECTIVITY: 'connectivity'>,
'original_icon': None,
'original_name': 'Contactor closed',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'contactor_closed',
'unique_id': '123456-contactor_closed',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_contactor_closed-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'connectivity',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site Contactor closed',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_contactor_closed',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_escan_firmware_updating-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_escan_firmware_updating',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'ESCAN firmware updating',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'ESCAN firmware updating',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'escan_firmware_updating',
'unique_id': '123456-escan_firmware_updating',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_escan_firmware_updating-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site ESCAN firmware updating',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_escan_firmware_updating',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_grid_ok-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_grid_ok',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Grid OK',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.CONNECTIVITY: 'connectivity'>,
'original_icon': None,
'original_name': 'Grid OK',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'grid_ok',
'unique_id': '123456-grid_ok',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_grid_ok-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'connectivity',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site Grid OK',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_grid_ok',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_microgrid_ok-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_microgrid_ok',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Microgrid OK',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.CONNECTIVITY: 'connectivity'>,
'original_icon': None,
'original_name': 'Microgrid OK',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'microgrid_ok',
'unique_id': '123456-microgrid_ok',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_microgrid_ok-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'connectivity',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site Microgrid OK',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_microgrid_ok',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_pw3can_firmware_updating-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_pw3can_firmware_updating',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'PW3CAN firmware updating',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'PW3CAN firmware updating',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'pw3can_firmware_updating',
'unique_id': '123456-pw3can_firmware_updating',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_pw3can_firmware_updating-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site PW3CAN firmware updating',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_pw3can_firmware_updating',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_site_manager_running-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_site_manager_running',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Site manager running',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.RUNNING: 'running'>,
'original_icon': None,
'original_name': 'Site manager running',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'site_manager_running',
'unique_id': '123456-site_manager_running',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_site_manager_running-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'running',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site Site manager running',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_site_manager_running',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_site_running-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.energy_site_site_running',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Site running',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.RUNNING: 'running'>,
'original_icon': None,
'original_name': 'Site running',
'platform': 'teslemetry',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'site_running',
'unique_id': '123456-site_running',
'unit_of_measurement': None,
})
# ---
# name: test_local_binary_sensors[binary_sensor.energy_site_site_running-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'running',
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Energy Site Site running',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.energy_site_site_running',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
@@ -1,14 +1,23 @@
"""Test the Teslemetry binary sensor platform."""
from collections.abc import Generator
from copy import deepcopy
from datetime import timedelta
import time
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from aiopowerwall import PowerwallConnectionError
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from freezegun.api import FrozenDateTimeFactory
from habluetooth import CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS
import pytest
from pytest_homeassistant.common import async_fire_time_changed, mock_restore_cache
from pytest_homeassistant.common import (
MockConfigEntry,
async_fire_time_changed,
mock_restore_cache,
)
from pytest_homeassistant.components.bluetooth import (
generate_advertisement_data,
generate_ble_device,
@@ -22,9 +31,20 @@ from teslemetry_stream import Signal
from homeassistant.components.bluetooth.const import UNAVAILABLE_TRACK_SECONDS
from homeassistant.components.bluetooth.manager import HomeAssistantBluetoothManager
from homeassistant.components.teslemetry.const import DOMAIN, SUBENTRY_TYPE_VEHICLE
from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL
from homeassistant.components.teslemetry.const import (
CONF_SITE_ID,
DOMAIN,
SUBENTRY_TYPE_ENERGY_SITE,
SUBENTRY_TYPE_VEHICLE,
)
from homeassistant.components.teslemetry.coordinator import (
LOCAL_STATUS_INTERVAL,
VEHICLE_INTERVAL,
)
from homeassistant.config_entries import ConfigEntryState, ConfigSubentryData
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
@@ -39,10 +59,33 @@ from . import (
assert_entities,
assert_entities_alt,
mock_ble_config_entry,
mock_config_entry,
setup_ble_platform,
setup_platform,
)
from .const import ADDRESS, METADATA, VEHICLE_DATA_ALT, VIN
from .const import ADDRESS, METADATA, POWERWALL_STATUS, VEHICLE_DATA_ALT, VIN
SITE_ID = 123456
LOCAL_STATUS_KEYS = (
"contactor_closed",
"escan_firmware_updating",
"grid_ok",
"microgrid_ok",
"pw3can_firmware_updating",
"site_manager_running",
"site_running",
)
# aiopowerwall's PowerwallClient parses the PEM at construction time, so tests
# that build one need a real (if undersized, for speed) RSA key rather than
# arbitrary bytes.
_TEST_RSA_KEY_PEM = rsa.generate_private_key(
public_exponent=65537, key_size=1024
).private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@@ -439,3 +482,186 @@ async def test_gps_state_requires_location_scope(
)
is not None
) is expected
async def _setup_paired(hass: HomeAssistant) -> MockConfigEntry:
"""Set up the binary sensor platform with the energy site paired locally."""
entry = mock_config_entry()
entry = MockConfigEntry(
domain=entry.domain,
version=entry.version,
minor_version=entry.minor_version,
unique_id=entry.unique_id,
data=dict(entry.data),
subentries_data=[
ConfigSubentryData(
subentry_type=SUBENTRY_TYPE_ENERGY_SITE,
unique_id=str(SITE_ID),
title="Energy Site",
data={
CONF_SITE_ID: SITE_ID,
CONF_HOST: "192.168.91.1",
CONF_PASSWORD: "abcde",
},
)
],
)
entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.teslemetry._async_get_rsa_key_pem",
return_value=_TEST_RSA_KEY_PEM,
),
patch(
"homeassistant.components.teslemetry.PLATFORMS", [Platform.BINARY_SENSOR]
),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry
def _local_entity_ids(entity_registry: er.EntityRegistry) -> dict[str, str]:
"""Return the entity ids of the local status binary sensors by key."""
return {
key: entity_id
for key in LOCAL_STATUS_KEYS
if (
entity_id := entity_registry.async_get_entity_id(
Platform.BINARY_SENSOR, DOMAIN, f"{SITE_ID}-{key}"
)
)
}
def _without(*path: str) -> dict[str, Any]:
"""Return the gateway status without the key at a path."""
data = deepcopy(POWERWALL_STATUS)
parent = data
for key in path[:-1]:
parent = parent[key]
del parent[path[-1]]
return data
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_local_binary_sensors(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a paired energy site creates the local status binary sensors."""
await _setup_paired(hass)
entity_ids = _local_entity_ids(entity_registry)
assert entity_ids.keys() == set(LOCAL_STATUS_KEYS)
for entity_id in entity_ids.values():
assert entity_registry.async_get(entity_id) == snapshot(
name=f"{entity_id}-entry"
)
assert hass.states.get(entity_id) == snapshot(name=f"{entity_id}-state")
async def test_local_binary_sensors_unpaired(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_powerwall_status: AsyncMock,
) -> None:
"""Test an energy site without local pairing creates no local sensors."""
await setup_platform(hass, [Platform.BINARY_SENSOR])
mock_powerwall_status.assert_not_called()
assert not _local_entity_ids(entity_registry)
@pytest.mark.parametrize(
("status", "missing"),
[
pytest.param(_without("pw3Can"), "pw3can_firmware_updating", id="pw3can"),
pytest.param(
_without("control", "siteShutdown", "isShutDown"),
"site_running",
id="site_shutdown",
),
],
)
async def test_local_binary_sensors_missing_signal(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_powerwall_status: AsyncMock,
status: dict[str, Any],
missing: str,
) -> None:
"""Test a signal absent from the first refresh skips its sensor."""
mock_powerwall_status.side_effect = None
mock_powerwall_status.return_value = status
await _setup_paired(hass)
assert _local_entity_ids(entity_registry).keys() == set(LOCAL_STATUS_KEYS) - {
missing
}
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_local_binary_sensors_first_refresh_failure(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_powerwall_status: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensors from a failed first local refresh recover without a reload."""
mock_powerwall_status.side_effect = PowerwallConnectionError("offline")
entry = await _setup_paired(hass)
assert entry.state is ConfigEntryState.LOADED
entity_ids = _local_entity_ids(entity_registry)
assert entity_ids.keys() == set(LOCAL_STATUS_KEYS)
for entity_id in entity_ids.values():
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
mock_powerwall_status.side_effect = None
mock_powerwall_status.return_value = POWERWALL_STATUS
freezer.tick(LOCAL_STATUS_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
for entity_id in entity_ids.values():
assert (state := hass.states.get(entity_id))
assert state.state != STATE_UNAVAILABLE
assert (state := hass.states.get(entity_ids["grid_ok"]))
assert state.state == STATE_ON
async def test_local_binary_sensors_poll_failure(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_powerwall_status: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a failed local poll makes the sensors unavailable until it recovers."""
await _setup_paired(hass)
entity_id = _local_entity_ids(entity_registry)["grid_ok"]
assert (state := hass.states.get(entity_id))
assert state.state == STATE_ON
mock_powerwall_status.side_effect = PowerwallConnectionError("offline")
freezer.tick(LOCAL_STATUS_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
status = deepcopy(POWERWALL_STATUS)
status["control"]["islanding"]["gridOK"] = False
mock_powerwall_status.side_effect = None
mock_powerwall_status.return_value = status
freezer.tick(LOCAL_STATUS_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == STATE_OFF