mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Gate Teslemetry cloud-signed Powerwall commands on the paired flag (#194094)
This commit is contained in:
@@ -87,6 +87,7 @@ from .const import (
|
||||
CLIENT_ID,
|
||||
CONF_VIN,
|
||||
DOMAIN,
|
||||
ISSUE_ENERGY_SITE_NOT_PAIRED,
|
||||
ISSUE_GATEWAY_NOT_FOUND,
|
||||
LABS_CHARGE_ON_SOLAR_FEATURE,
|
||||
LOGGER,
|
||||
@@ -351,6 +352,55 @@ def _setup_vehicle_repairs(
|
||||
)
|
||||
|
||||
|
||||
def _setup_energy_site_repairs(
|
||||
hass: HomeAssistant,
|
||||
entry: TeslemetryConfigEntry,
|
||||
metadata_coordinator: TeslemetryMetadataCoordinator,
|
||||
energysites: list[TeslemetryEnergyData],
|
||||
) -> None:
|
||||
"""Keep a repair issue for each battery site signed commands cannot reach."""
|
||||
|
||||
@callback
|
||||
def _handle_metadata_update() -> None:
|
||||
"""Re-evaluate energy site repair issues when metadata changes."""
|
||||
with ir.async_refresh_issues(
|
||||
hass,
|
||||
DOMAIN,
|
||||
issue_id_pattern=f"{ISSUE_ENERGY_SITE_NOT_PAIRED}_",
|
||||
config_entry_id=entry.entry_id,
|
||||
):
|
||||
for energysite in energysites:
|
||||
if (
|
||||
not energysite.can_local_control
|
||||
or energysite.signed_commands_available(metadata_coordinator.data)
|
||||
):
|
||||
continue
|
||||
placeholders = {
|
||||
"site": energysite.device["name"],
|
||||
"link": f"{energysite.device['configuration_url']}/setup",
|
||||
}
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
f"{ISSUE_ENERGY_SITE_NOT_PAIRED}_{entry.entry_id}_{energysite.id}",
|
||||
config_entry_id=entry.entry_id,
|
||||
is_fixable=True,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key=ISSUE_ENERGY_SITE_NOT_PAIRED,
|
||||
translation_placeholders=placeholders,
|
||||
data={
|
||||
"entry_id": entry.entry_id,
|
||||
"site_id": energysite.id,
|
||||
**placeholders,
|
||||
},
|
||||
)
|
||||
|
||||
_handle_metadata_update()
|
||||
entry.async_on_unload(
|
||||
metadata_coordinator.async_add_listener(_handle_metadata_update)
|
||||
)
|
||||
|
||||
|
||||
# Two failure shapes must be caught to fall back to cloud control: the library
|
||||
# wraps existing-key failures in PrivateKeyError, the create-race path raises raw errors.
|
||||
_BLE_KEY_ERRORS: Final = (
|
||||
@@ -1030,6 +1080,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) -
|
||||
vehicle_metadata,
|
||||
)
|
||||
|
||||
_setup_energy_site_repairs(hass, entry, metadata_coordinator, energysites)
|
||||
|
||||
entry.async_on_unload(_async_subscribe_charge_on_solar_labs(hass, entry))
|
||||
|
||||
if stream:
|
||||
|
||||
@@ -32,6 +32,7 @@ CONF_SITE_ID = "site_id"
|
||||
POWERWALL_KEY_FILE = "tesla_powerwall.key"
|
||||
RSA_PARENT_KEY = f"{DOMAIN}_rsa_parent"
|
||||
ISSUE_GATEWAY_NOT_FOUND = "gateway_not_found"
|
||||
ISSUE_ENERGY_SITE_NOT_PAIRED = "energy_site_not_paired"
|
||||
|
||||
ENERGY_HISTORY_FIELDS = [
|
||||
"solar_energy_exported",
|
||||
|
||||
@@ -133,3 +133,13 @@ class TeslemetryEnergyData:
|
||||
# Only set when the site is paired with its local gateway.
|
||||
local_status_coordinator: TeslemetryLocalStatusCoordinator | None = None
|
||||
local_components_coordinator: TeslemetryLocalComponentsCoordinator | None = None
|
||||
|
||||
def signed_commands_available(self, metadata: dict[str, Any]) -> bool:
|
||||
"""Return whether commands Teslemetry signs with its own key can reach the site.
|
||||
|
||||
The cloud can only route them once Teslemetry's key is verified on the
|
||||
gateway, which metadata reports as paired; null means not yet known.
|
||||
"""
|
||||
return isinstance(self.api, EnergySiteRouter) or bool(
|
||||
metadata["energy_sites"].get(str(self.id), {}).get("paired")
|
||||
)
|
||||
|
||||
@@ -17,7 +17,12 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
|
||||
from . import _async_get_rsa_key_pem
|
||||
from .const import ISSUE_GATEWAY_NOT_FOUND, LOGGER, VEHICLE_ISSUE_LEARN_MORE
|
||||
from .const import (
|
||||
ISSUE_ENERGY_SITE_NOT_PAIRED,
|
||||
ISSUE_GATEWAY_NOT_FOUND,
|
||||
LOGGER,
|
||||
VEHICLE_ISSUE_LEARN_MORE,
|
||||
)
|
||||
from .helpers import (
|
||||
PowerwallKeyRejectedError,
|
||||
async_verify_local_gateway,
|
||||
@@ -70,6 +75,45 @@ class VehicleMetadataRepairFlow(RepairsFlow):
|
||||
)
|
||||
|
||||
|
||||
class EnergySiteNotPairedRepairFlow(RepairsFlow):
|
||||
"""Handle a repair that clears once Teslemetry is paired with the gateway."""
|
||||
|
||||
def __init__(
|
||||
self, entry: TeslemetryConfigEntry, site_id: int, placeholders: dict[str, str]
|
||||
) -> None:
|
||||
"""Create flow."""
|
||||
self.entry = entry
|
||||
self.site_id = site_id
|
||||
self.placeholders = placeholders
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, str] | None = None
|
||||
) -> RepairsFlowResult:
|
||||
"""Handle the first step of a fix flow."""
|
||||
return await self.async_step_confirm()
|
||||
|
||||
async def async_step_confirm(
|
||||
self, user_input: dict[str, str] | None = None
|
||||
) -> RepairsFlowResult:
|
||||
"""Handle the confirm step of a fix flow."""
|
||||
if user_input is not None:
|
||||
coordinator = self.entry.runtime_data.metadata_coordinator
|
||||
await coordinator.async_refresh()
|
||||
site = coordinator.data["energy_sites"].get(str(self.site_id), {})
|
||||
if coordinator.last_update_success and site.get("paired"):
|
||||
return self.async_create_entry(data={})
|
||||
return self.async_show_form(
|
||||
step_id="confirm",
|
||||
description_placeholders=self.placeholders,
|
||||
errors={"base": "not_resolved"},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="confirm",
|
||||
description_placeholders=self.placeholders,
|
||||
)
|
||||
|
||||
|
||||
class GatewayNotFoundRepairFlow(RepairsFlow):
|
||||
"""Handle a repair that finds a local Powerwall gateway's current address."""
|
||||
|
||||
@@ -197,6 +241,19 @@ async def async_create_fix_flow(
|
||||
and entry.state is ConfigEntryState.LOADED
|
||||
):
|
||||
return VehicleMetadataRepairFlow(entry, vin, issue_type, vehicle)
|
||||
if (
|
||||
issue_id.startswith(f"{ISSUE_ENERGY_SITE_NOT_PAIRED}_")
|
||||
and data is not None
|
||||
and isinstance(entry_id := data.get("entry_id"), str)
|
||||
and isinstance(site_id := data.get("site_id"), int)
|
||||
and isinstance(site := data.get("site"), str)
|
||||
and isinstance(link := data.get("link"), str)
|
||||
and (entry := hass.config_entries.async_get_entry(entry_id)) is not None
|
||||
and entry.state is ConfigEntryState.LOADED
|
||||
):
|
||||
return EnergySiteNotPairedRepairFlow(
|
||||
entry, site_id, {"site": site, "link": link}
|
||||
)
|
||||
if (
|
||||
issue_id.startswith(f"{ISSUE_GATEWAY_NOT_FOUND}_")
|
||||
and data is not None
|
||||
|
||||
@@ -118,10 +118,26 @@ def async_get_energy_site_for_entry(
|
||||
)
|
||||
|
||||
|
||||
def async_get_energy_site_for_signed_command(
|
||||
hass: HomeAssistant, call: ServiceCall
|
||||
) -> TeslemetryEnergyData:
|
||||
"""Get the energy site for a command Teslemetry signs with its own key."""
|
||||
device, config = async_get_device_and_config_for_service_call(hass, call)
|
||||
site = async_get_energy_site_for_entry(hass, device, config)
|
||||
if not site.signed_commands_available(
|
||||
config.runtime_data.metadata_coordinator.data
|
||||
):
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="energy_site_not_paired",
|
||||
translation_placeholders={"site": site.device["name"]},
|
||||
)
|
||||
return site
|
||||
|
||||
|
||||
async def async_dispatch_battery_power(call: ServiceCall) -> None:
|
||||
"""Charge or discharge the battery at a set power for a set time."""
|
||||
device, config = async_get_device_and_config_for_service_call(call.hass, call)
|
||||
site = async_get_energy_site_for_entry(call.hass, device, config)
|
||||
site = async_get_energy_site_for_signed_command(call.hass, call)
|
||||
|
||||
await handle_energy_site_command(
|
||||
site.api.dispatch_battery_power(
|
||||
@@ -133,8 +149,7 @@ async def async_dispatch_battery_power(call: ServiceCall) -> None:
|
||||
|
||||
async def async_resume_battery_operation(call: ServiceCall) -> None:
|
||||
"""Return the battery to its configured operating mode."""
|
||||
device, config = async_get_device_and_config_for_service_call(call.hass, call)
|
||||
site = async_get_energy_site_for_entry(call.hass, device, config)
|
||||
site = async_get_energy_site_for_signed_command(call.hass, call)
|
||||
|
||||
await handle_energy_site_command(site.api.resume_battery_operation())
|
||||
|
||||
|
||||
@@ -1342,6 +1342,9 @@
|
||||
"command_reason": {
|
||||
"message": "Command was rejected: {reason}"
|
||||
},
|
||||
"energy_site_not_paired": {
|
||||
"message": "Teslemetry is not paired with the Powerwall system for {site}, pair it in the Teslemetry console or set up local control"
|
||||
},
|
||||
"local_command_failed": {
|
||||
"message": "The Powerwall gateway could not complete the command, check the logs for details"
|
||||
},
|
||||
@@ -1404,6 +1407,20 @@
|
||||
}
|
||||
},
|
||||
"issues": {
|
||||
"energy_site_not_paired": {
|
||||
"fix_flow": {
|
||||
"error": {
|
||||
"not_resolved": "Teslemetry still appears to be unpaired. Please complete the pairing at {link}, then try again."
|
||||
},
|
||||
"step": {
|
||||
"confirm": {
|
||||
"description": "Home Assistant cannot send battery commands, such as dispatching battery power, to {site} because Teslemetry is not paired with its Powerwall system and local control is not set up. Teslemetry can only send these commands through the cloud once its key is verified on the Powerwall gateway.\n\n1. Open {link}.\n2. Follow the prompts to pair Teslemetry with the Powerwall system.\n3. Select **Submit** below to re-check.\n\nAlternatively, set up local control for {site}.",
|
||||
"title": "[%key:component::teslemetry::issues::energy_site_not_paired::title%]"
|
||||
}
|
||||
}
|
||||
},
|
||||
"title": "Pair Teslemetry with the Powerwall system for {site}"
|
||||
},
|
||||
"gateway_not_found": {
|
||||
"fix_flow": {
|
||||
"abort": {
|
||||
|
||||
@@ -130,6 +130,7 @@ METADATA = {
|
||||
"123456": {
|
||||
"access": True,
|
||||
"name": "Energy Site",
|
||||
"paired": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -167,6 +168,7 @@ METADATA_LEGACY = {
|
||||
"123456": {
|
||||
"access": True,
|
||||
"name": "Energy Site",
|
||||
"paired": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -200,6 +202,7 @@ METADATA_OLD_FIRMWARE = {
|
||||
"123456": {
|
||||
"access": True,
|
||||
"name": "Energy Site",
|
||||
"paired": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -223,6 +226,7 @@ METADATA_NOSCOPE = {
|
||||
"123456": {
|
||||
"access": True,
|
||||
"name": "Energy Site",
|
||||
"paired": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -243,6 +247,7 @@ METADATA_ENERGY = {
|
||||
"123456": {
|
||||
"access": True,
|
||||
"name": "Energy Site",
|
||||
"paired": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -44,8 +44,8 @@ from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import issue_registry as ir
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import mock_config_entry, setup_platform
|
||||
from .const import METADATA
|
||||
from . import mock_config_entry, setup_paired_platform, setup_platform
|
||||
from .const import METADATA, PRODUCTS
|
||||
|
||||
VEHICLE_VIN = "LRW3F7EK4NC700000"
|
||||
SITE_ID = 123456
|
||||
@@ -745,3 +745,211 @@ async def test_gateway_repair_aborts_without_loaded_site(
|
||||
|
||||
assert result["type"] == FlowResultType.ABORT
|
||||
assert result["reason"] == "entry_not_loaded"
|
||||
|
||||
|
||||
def _energy_issue_id(entry: MockConfigEntry) -> str:
|
||||
"""Return the id of the pairing repair issue of the energy site."""
|
||||
return f"energy_site_not_paired_{entry.entry_id}_{SITE_ID}"
|
||||
|
||||
|
||||
def _metadata_with_paired(paired: bool | None) -> dict[str, Any]:
|
||||
"""Return a copy of the metadata with the energy site paired flag set."""
|
||||
metadata = deepcopy(METADATA)
|
||||
metadata["energy_sites"][str(SITE_ID)]["paired"] = paired
|
||||
return metadata
|
||||
|
||||
|
||||
def _products_without_battery() -> dict[str, Any]:
|
||||
"""Return a copy of the products with a solar-only energy site."""
|
||||
products = deepcopy(PRODUCTS)
|
||||
site = next(
|
||||
product
|
||||
for product in products["response"]
|
||||
if product.get("energy_site_id") == SITE_ID
|
||||
)
|
||||
site["components"]["battery"] = False
|
||||
return products
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"paired", [pytest.param(False, id="not_paired"), pytest.param(None, id="unknown")]
|
||||
)
|
||||
async def test_energy_site_repair_issue_created(
|
||||
hass: HomeAssistant,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
paired: bool | None,
|
||||
) -> None:
|
||||
"""Test a repair issue is created for a battery site Teslemetry cannot sign for."""
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(paired),
|
||||
):
|
||||
entry = await setup_platform(hass, [])
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
issue = issue_registry.async_get_issue(DOMAIN, _energy_issue_id(entry))
|
||||
assert issue is not None
|
||||
assert issue.config_entry_id == entry.entry_id
|
||||
assert issue.translation_key == "energy_site_not_paired"
|
||||
assert issue.translation_placeholders == {
|
||||
"site": "Energy Site",
|
||||
"link": f"https://teslemetry.com/console/energy/{SITE_ID}/setup",
|
||||
}
|
||||
assert issue.data == {
|
||||
"entry_id": entry.entry_id,
|
||||
"site_id": SITE_ID,
|
||||
"site": "Energy Site",
|
||||
"link": f"https://teslemetry.com/console/energy/{SITE_ID}/setup",
|
||||
}
|
||||
|
||||
|
||||
async def test_no_energy_site_repair_issue_when_paired(
|
||||
hass: HomeAssistant, issue_registry: ir.IssueRegistry
|
||||
) -> None:
|
||||
"""Test no repair issue is created when Teslemetry is paired with the gateway."""
|
||||
entry = await setup_platform(hass, [])
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert issue_registry.async_get_issue(DOMAIN, _energy_issue_id(entry)) is None
|
||||
|
||||
|
||||
async def test_no_energy_site_repair_issue_with_local_control(
|
||||
hass: HomeAssistant, issue_registry: ir.IssueRegistry
|
||||
) -> None:
|
||||
"""Test no repair issue is created when the site has local control."""
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(False),
|
||||
):
|
||||
entry = await setup_paired_platform(hass, [])
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert issue_registry.async_get_issue(DOMAIN, _energy_issue_id(entry)) is None
|
||||
|
||||
|
||||
async def test_no_energy_site_repair_issue_without_battery(
|
||||
hass: HomeAssistant, issue_registry: ir.IssueRegistry
|
||||
) -> None:
|
||||
"""Test no repair issue is created for a site without a Powerwall."""
|
||||
with (
|
||||
patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(False),
|
||||
),
|
||||
patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.products",
|
||||
return_value=_products_without_battery(),
|
||||
),
|
||||
):
|
||||
entry = await setup_platform(hass, [])
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert issue_registry.async_get_issue(DOMAIN, _energy_issue_id(entry)) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("before", "after", "issue_before", "issue_after"),
|
||||
[
|
||||
pytest.param(False, True, True, False, id="becomes_paired"),
|
||||
pytest.param(True, False, False, True, id="becomes_unpaired"),
|
||||
],
|
||||
)
|
||||
async def test_energy_site_repair_issue_follows_metadata(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
before: bool,
|
||||
after: bool,
|
||||
issue_before: bool,
|
||||
issue_after: bool,
|
||||
) -> None:
|
||||
"""Test the repair issue follows the paired flag on each metadata poll."""
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(before),
|
||||
):
|
||||
entry = await setup_platform(hass, [])
|
||||
assert (
|
||||
issue_registry.async_get_issue(DOMAIN, _energy_issue_id(entry)) is not None
|
||||
) is issue_before
|
||||
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(after),
|
||||
):
|
||||
freezer.tick(METADATA_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert (
|
||||
issue_registry.async_get_issue(DOMAIN, _energy_issue_id(entry)) is not None
|
||||
) is issue_after
|
||||
|
||||
|
||||
async def test_energy_site_repair_fix_flow(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
) -> None:
|
||||
"""Test the fix flow re-checks metadata and resolves once paired."""
|
||||
assert await async_setup_component(hass, "repairs", {})
|
||||
client = await hass_client()
|
||||
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(False),
|
||||
):
|
||||
entry = await setup_platform(hass, [])
|
||||
issue_id = _energy_issue_id(entry)
|
||||
assert issue_registry.async_get_issue(DOMAIN, issue_id) is not None
|
||||
|
||||
result = await start_repair_fix_flow(client, DOMAIN, issue_id)
|
||||
flow_id = result["flow_id"]
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "confirm"
|
||||
assert result["description_placeholders"] == {
|
||||
"site": "Energy Site",
|
||||
"link": f"https://teslemetry.com/console/energy/{SITE_ID}/setup",
|
||||
}
|
||||
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(None),
|
||||
):
|
||||
result = await process_repair_fix_flow(client, flow_id, json={})
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "not_resolved"}
|
||||
assert issue_registry.async_get_issue(DOMAIN, issue_id) is not None
|
||||
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(True),
|
||||
):
|
||||
result = await process_repair_fix_flow(client, flow_id, json={})
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert issue_registry.async_get_issue(DOMAIN, issue_id) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data",
|
||||
[
|
||||
pytest.param(None, id="no_data"),
|
||||
pytest.param(
|
||||
{"entry_id": "missing", "site_id": SITE_ID, "site": "Site", "link": "x"},
|
||||
id="missing_entry",
|
||||
),
|
||||
pytest.param(
|
||||
{"entry_id": ENTRY_ID, "site_id": str(SITE_ID), "site": "Site"},
|
||||
id="malformed",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_energy_site_repair_invalid_data_returns_confirm_flow(
|
||||
hass: HomeAssistant,
|
||||
data: dict[str, Any] | None,
|
||||
) -> None:
|
||||
"""Test invalid pairing repair data falls back to a confirm flow."""
|
||||
flow = await async_create_fix_flow(
|
||||
hass, f"energy_site_not_paired_{ENTRY_ID}_{SITE_ID}", data
|
||||
)
|
||||
assert isinstance(flow, ConfirmRepairFlow)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Test the Teslemetry services."""
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import time
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
@@ -38,7 +40,7 @@ from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from . import mock_config_entry, setup_platform
|
||||
from .const import COMMAND_ERROR, COMMAND_OK
|
||||
from .const import COMMAND_ERROR, COMMAND_OK, METADATA
|
||||
|
||||
lat = -27.9699373
|
||||
lon = 153.3726526
|
||||
@@ -876,3 +878,103 @@ async def test_dispatch_battery_power_out_of_range(
|
||||
blocking=True,
|
||||
)
|
||||
mock_method.assert_not_called()
|
||||
|
||||
|
||||
def _metadata_with_paired(paired: bool | None) -> dict[str, Any]:
|
||||
"""Return a copy of the metadata with the energy site paired flag set."""
|
||||
metadata = deepcopy(METADATA)
|
||||
metadata["energy_sites"][str(SITE_ID)]["paired"] = paired
|
||||
return metadata
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("service", "data", "method"), LOCAL_BATTERY_SERVICES)
|
||||
@pytest.mark.parametrize(
|
||||
("subentries", "paired", "local_calls", "cloud_calls"),
|
||||
[
|
||||
pytest.param([PAIRED_SITE], False, 1, 0, id="local_only"),
|
||||
pytest.param([], True, 0, 1, id="paired_only"),
|
||||
pytest.param([PAIRED_SITE], True, 1, 0, id="local_and_paired"),
|
||||
],
|
||||
)
|
||||
async def test_battery_services_signed_command_available(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
service: str,
|
||||
data: dict[str, int],
|
||||
method: str,
|
||||
subentries: list[ConfigSubentryData],
|
||||
paired: bool,
|
||||
local_calls: int,
|
||||
cloud_calls: int,
|
||||
) -> None:
|
||||
"""Test the battery services send when the site is local or paired with Teslemetry."""
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(paired),
|
||||
):
|
||||
entry = await _setup_site(hass, subentries)
|
||||
device = device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, str(SITE_ID)), entry.entry_id
|
||||
)
|
||||
assert device
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"tesla_fleet_api.tesla.powerwall.PowerwallClient.{method}"
|
||||
) as mock_local,
|
||||
patch(
|
||||
f"tesla_fleet_api.teslemetry.energysite.TeslemetryEnergySite.{method}",
|
||||
return_value=COMMAND_OK,
|
||||
) as mock_cloud,
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
service,
|
||||
{CommonServiceArgument.DEVICE_ID: device.id, **data},
|
||||
blocking=True,
|
||||
)
|
||||
assert mock_local.await_count == local_calls
|
||||
assert mock_cloud.await_count == cloud_calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("service", "data", "method"), LOCAL_BATTERY_SERVICES)
|
||||
@pytest.mark.parametrize(
|
||||
"paired", [pytest.param(False, id="not_paired"), pytest.param(None, id="unknown")]
|
||||
)
|
||||
async def test_battery_services_refused_without_pairing(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
service: str,
|
||||
data: dict[str, int],
|
||||
method: str,
|
||||
paired: bool | None,
|
||||
) -> None:
|
||||
"""Test the battery services refuse a site neither local nor paired with Teslemetry."""
|
||||
with patch(
|
||||
"tesla_fleet_api.teslemetry.Teslemetry.metadata",
|
||||
return_value=_metadata_with_paired(paired),
|
||||
):
|
||||
entry = await _setup_site(hass, [])
|
||||
device = device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, str(SITE_ID)), entry.entry_id
|
||||
)
|
||||
assert device
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"tesla_fleet_api.teslemetry.energysite.TeslemetryEnergySite.{method}"
|
||||
) as mock_cloud,
|
||||
pytest.raises(ServiceValidationError) as exc_info,
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
service,
|
||||
{CommonServiceArgument.DEVICE_ID: device.id, **data},
|
||||
blocking=True,
|
||||
)
|
||||
assert exc_info.value.translation_key == "energy_site_not_paired"
|
||||
assert str(exc_info.value) == (
|
||||
"Teslemetry is not paired with the Powerwall system for Energy Site, "
|
||||
"pair it in the Teslemetry console or set up local control"
|
||||
)
|
||||
mock_cloud.assert_not_called()
|
||||
|
||||
Reference in New Issue
Block a user