diff --git a/homeassistant/components/teslemetry/__init__.py b/homeassistant/components/teslemetry/__init__.py index b6f1b47e5947..3e3920d8860a 100644 --- a/homeassistant/components/teslemetry/__init__.py +++ b/homeassistant/components/teslemetry/__init__.py @@ -43,6 +43,11 @@ from homeassistant.components.bluetooth import ( async_address_reachability_diagnostics, async_ble_device_from_address, ) +from homeassistant.components.labs import ( + EventLabsUpdatedData, + async_is_preview_feature_enabled, + async_subscribe_preview_feature, +) from homeassistant.config_entries import ConfigEntry, ConfigEntryState, ConfigSubentry from homeassistant.const import ( CONF_ACCESS_TOKEN, @@ -51,7 +56,7 @@ from homeassistant.const import ( CONF_PASSWORD, Platform, ) -from homeassistant.core import HomeAssistant, callback +from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.exceptions import ( ConfigEntryAuthFailed, ConfigEntryNotReady, @@ -61,6 +66,7 @@ from homeassistant.exceptions import ( from homeassistant.helpers import ( config_validation as cv, device_registry as dr, + entity_registry as er, issue_registry as ir, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -74,10 +80,13 @@ from homeassistant.helpers.update_coordinator import UpdateFailed from .const import ( BLE_DISCONNECT_TIMEOUT, + CHARGE_ON_SOLAR_LOWER_LIMIT_KEY, + CHARGE_ON_SOLAR_SWITCH_KEY, CLIENT_ID, CONF_VIN, DOMAIN, ISSUE_GATEWAY_NOT_FOUND, + LABS_CHARGE_ON_SOLAR_FEATURE, LOGGER, POWERWALL_KEY_FILE, RSA_PARENT_KEY, @@ -99,7 +108,12 @@ from .helpers import ( create_powerwall_client, flatten, ) -from .models import TeslemetryData, TeslemetryEnergyData, TeslemetryVehicleData +from .models import ( + TeslemetryChargeOnSolarStore, + TeslemetryData, + TeslemetryEnergyData, + TeslemetryVehicleData, +) from .services import async_setup_services PLATFORMS: Final = [ @@ -597,6 +611,47 @@ async def _async_rediscover_gateway( return stale_client +async def _async_setup_charge_on_solar( + hass: HomeAssistant, + entry: TeslemetryConfigEntry, + scopes: list[Scope], + vehicles: list[TeslemetryVehicleData], +) -> TeslemetryChargeOnSolarStore | None: + """Load the charge-on-solar store, or remove its entities when unavailable.""" + if ( + async_is_preview_feature_enabled(hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE) + and Scope.VEHICLE_CMDS in scopes + ): + store = TeslemetryChargeOnSolarStore(hass, entry.entry_id) + await store.async_load(vehicles) + return store + + entity_registry = er.async_get(hass) + for entity_entry in er.async_entries_for_config_entry( + entity_registry, entry.entry_id + ): + if (entity_entry.domain, entity_entry.translation_key) in ( + (Platform.SWITCH, CHARGE_ON_SOLAR_SWITCH_KEY), + (Platform.NUMBER, CHARGE_ON_SOLAR_LOWER_LIMIT_KEY), + ): + entity_registry.async_remove(entity_entry.entity_id) + return None + + +@callback +def _async_subscribe_charge_on_solar_labs( + hass: HomeAssistant, entry: TeslemetryConfigEntry +) -> CALLBACK_TYPE: + """Reload the entry so the charge-on-solar entities follow the Labs toggle.""" + + async def _async_handle_labs_update(_event_data: EventLabsUpdatedData) -> None: + hass.config_entries.async_schedule_reload(entry.entry_id) + + return async_subscribe_preview_feature( + hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, _async_handle_labs_update + ) + + async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) -> None: """Set up Teslemetry config.""" @@ -895,12 +950,17 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) - _prune_energy_subentries(hass, entry, scopes, products) + charge_on_solar_store = await _async_setup_charge_on_solar( + hass, entry, scopes, vehicles + ) + entry.runtime_data = TeslemetryData( vehicles=vehicles, energysites=energysites, scopes=scopes, stream=stream, metadata_coordinator=metadata_coordinator, + charge_on_solar_store=charge_on_solar_store, ) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) @@ -922,6 +982,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) - vehicle_metadata, ) + entry.async_on_unload(_async_subscribe_charge_on_solar_labs(hass, entry)) + if stream: entry.async_on_unload(stream.close) # The stream is the only freshness signal for the energy coordinators, so @@ -1118,6 +1180,11 @@ async def async_unload_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) ) +async def async_remove_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) -> None: + """Remove the stored charge-on-solar settings.""" + await TeslemetryChargeOnSolarStore(hass, entry.entry_id).async_remove() + + async def async_migrate_entry( hass: HomeAssistant, config_entry: TeslemetryConfigEntry ) -> None: diff --git a/homeassistant/components/teslemetry/const.py b/homeassistant/components/teslemetry/const.py index d4e04b31ece9..8d82f4fdea9d 100644 --- a/homeassistant/components/teslemetry/const.py +++ b/homeassistant/components/teslemetry/const.py @@ -4,6 +4,11 @@ from enum import StrEnum import logging DOMAIN = "teslemetry" +LABS_CHARGE_ON_SOLAR_FEATURE = "charge_on_solar" +CHARGE_ON_SOLAR_SWITCH_KEY = "charge_on_solar" +CHARGE_ON_SOLAR_LOWER_LIMIT_KEY = "charge_on_solar_lower_limit" +CHARGE_ON_SOLAR_LOWER_LIMIT_DEFAULT = 20 +CHARGE_LIMIT_SOC_KEY = "charge_state_charge_limit_soc" LOGGER = logging.getLogger(__package__) diff --git a/homeassistant/components/teslemetry/entity.py b/homeassistant/components/teslemetry/entity.py index 858c99bdd9eb..4ebb04ab098a 100644 --- a/homeassistant/components/teslemetry/entity.py +++ b/homeassistant/components/teslemetry/entity.py @@ -8,14 +8,15 @@ from tesla_fleet_api.router import VehicleRouter from tesla_fleet_api.tesla import EnergySiteRouter from tesla_fleet_api.teslemetry import EnergySite, Vehicle +from homeassistant.core import callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import device_registry as dr from homeassistant.helpers.device_registry import DeviceInfo -from homeassistant.helpers.entity import Entity +from homeassistant.helpers.entity import Entity, EntityDescription from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity -from .const import DOMAIN +from .const import CHARGE_LIMIT_SOC_KEY, DOMAIN from .coordinator import ( TeslemetryEnergyHistoryCoordinator, TeslemetryEnergySiteInfoCoordinator, @@ -23,7 +24,11 @@ from .coordinator import ( TeslemetryLocalStatusCoordinator, TeslemetryVehicleDataCoordinator, ) -from .models import TeslemetryEnergyData, TeslemetryVehicleData +from .models import ( + TeslemetryChargeOnSolarStore, + TeslemetryEnergyData, + TeslemetryVehicleData, +) class TeslemetryRootEntity(Entity): @@ -320,3 +325,56 @@ class TeslemetryVehicleStreamEntity(TeslemetryVehicleEntity): self.stream = data.stream self.add_field = data.stream.get_vehicle(self.vin).add_field + + +class TeslemetryChargeOnSolarEntity(TeslemetryVehicleStreamEntity): + """Parent class for the charge-on-solar entities, bounded by the charge limit.""" + + _attr_assumed_state = True + api: Vehicle + # Only created when the vehicle commands scope is granted. + scoped = True + + def __init__( + self, + data: TeslemetryVehicleData, + description: EntityDescription, + store: TeslemetryChargeOnSolarStore, + ) -> None: + """Initialize common aspects of a charge-on-solar entity.""" + self.entity_description = description + self._store = store + super().__init__(data, description.key) + + @override + async def async_added_to_hass(self) -> None: + """Handle entity which will be added.""" + await super().async_added_to_hass() + if self.vehicle.polls_charge_limit: + self.async_on_remove( + self.vehicle.coordinator.async_add_listener( + self._async_handle_coordinator_update + ) + ) + self._async_handle_coordinator_update() + return + + self.async_on_remove( + self.vehicle.stream_vehicle.listen_ChargeLimitSoc( + self._async_handle_charge_limit_soc + ) + ) + + @callback + def _async_handle_coordinator_update(self) -> None: + """Take the charge limit from the latest poll.""" + value = self.vehicle.coordinator.data.get(CHARGE_LIMIT_SOC_KEY) + self._async_handle_charge_limit_soc( + int(value) if isinstance(value, int | float) else None + ) + + @callback + def _async_handle_charge_limit_soc(self, value: int | None) -> None: + """Store the latest charge limit.""" + self.vehicle.charge_limit_soc = None if value is None else int(value) + self._store.async_save(self.vehicle) diff --git a/homeassistant/components/teslemetry/helpers.py b/homeassistant/components/teslemetry/helpers.py index 6607849a484b..fd58470f68f0 100644 --- a/homeassistant/components/teslemetry/helpers.py +++ b/homeassistant/components/teslemetry/helpers.py @@ -1,7 +1,7 @@ """Teslemetry helper functions.""" import asyncio -from collections.abc import Awaitable +from collections.abc import Awaitable, Callable from typing import Any, cast from aiohttp import ClientError @@ -9,7 +9,7 @@ from aiopowerwall import PowerwallAuthenticationError, PowerwallClient from tesla_fleet_api.exceptions import TeslaFleetError from tesla_fleet_api.tesla import EnergySiteRouter from tesla_fleet_api.tesla.bluetooth import TeslaBluetooth -from tesla_fleet_api.teslemetry import EnergySite +from tesla_fleet_api.teslemetry import EnergySite, Vehicle from tesla_fleet_api.teslemetry.energysite import TeslemetryEnergySite from homeassistant.core import HomeAssistant, callback @@ -153,6 +153,30 @@ async def handle_vehicle_command(command: Awaitable[dict[str, Any]]) -> Any: return result +async def async_set_charge_on_solar( + send: Callable[[Awaitable[dict[str, Any]]], Awaitable[Any]], + api: Vehicle, + *, + enabled: bool, + lower_charge_limit: int, + charge_limit_soc: int | None, +) -> int: + """Send a charge-on-solar command, omitting the upper bound if it isn't known yet. + + Returns the lower limit actually sent, clamped to the upper bound if it is known. + """ + if charge_limit_soc is not None: + lower_charge_limit = min(lower_charge_limit, charge_limit_soc) + await send( + api.charge_on_solar( + enabled=enabled, + lower_charge_limit=lower_charge_limit, + upper_charge_limit=charge_limit_soc, + ) + ) + return lower_charge_limit + + @callback def async_remove_stale_vehicle_entities( hass: HomeAssistant, diff --git a/homeassistant/components/teslemetry/icons.json b/homeassistant/components/teslemetry/icons.json index 7dbc794ecc49..b908b8a5915b 100644 --- a/homeassistant/components/teslemetry/icons.json +++ b/homeassistant/components/teslemetry/icons.json @@ -769,6 +769,12 @@ } }, "switch": { + "charge_on_solar": { + "default": "mdi:solar-power", + "state": { + "off": "mdi:solar-power-variant-outline" + } + }, "charge_state_charging_state": { "default": "mdi:ev-station" }, diff --git a/homeassistant/components/teslemetry/manifest.json b/homeassistant/components/teslemetry/manifest.json index 78cc9f7684d7..5130062b401a 100644 --- a/homeassistant/components/teslemetry/manifest.json +++ b/homeassistant/components/teslemetry/manifest.json @@ -9,6 +9,13 @@ "integration_type": "hub", "iot_class": "cloud_polling", "loggers": ["aiopowerwall", "tesla_fleet_api", "teslemetry_stream"], + "preview_features": { + "charge_on_solar": { + "feedback_url": "https://community.home-assistant.io", + "learn_more_url": "https://www.home-assistant.io/integrations/teslemetry", + "report_issue_url": "https://github.com/home-assistant/core/issues/new?template=bug_report.yml&integration_link=https://www.home-assistant.io/integrations/teslemetry&integration_name=Teslemetry" + } + }, "quality_scale": "platinum", "requirements": [ "aiopowerwall==0.7.0", diff --git a/homeassistant/components/teslemetry/models.py b/homeassistant/components/teslemetry/models.py index f720e9ec1d8c..e3be3e4e8941 100644 --- a/homeassistant/components/teslemetry/models.py +++ b/homeassistant/components/teslemetry/models.py @@ -2,7 +2,9 @@ import asyncio from dataclasses import dataclass, field +from typing import Any +from tesla_fleet_api import firmware_at_least from tesla_fleet_api.const import Scope from tesla_fleet_api.router import VehicleRouter from tesla_fleet_api.tesla import EnergySiteRouter @@ -11,8 +13,11 @@ from tesla_fleet_api.teslemetry import EnergySite, Vehicle from teslemetry_stream import TeslemetryStream, TeslemetryStreamVehicle from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.storage import Store +from .const import CHARGE_ON_SOLAR_LOWER_LIMIT_DEFAULT, DOMAIN from .coordinator import ( TeslemetryEnergyHistoryCoordinator, TeslemetryEnergySiteInfoCoordinator, @@ -22,6 +27,8 @@ from .coordinator import ( TeslemetryVehicleDataCoordinator, ) +STORAGE_VERSION = 1 + @dataclass class TeslemetryData: @@ -32,6 +39,7 @@ class TeslemetryData: scopes: list[Scope] stream: TeslemetryStream | None metadata_coordinator: TeslemetryMetadataCoordinator + charge_on_solar_store: TeslemetryChargeOnSolarStore | None @dataclass @@ -52,6 +60,56 @@ class TeslemetryVehicleData: ble_address: str | None ble_api: VehicleBluetooth | None wakelock: asyncio.Lock = field(default_factory=asyncio.Lock) + charge_limit_soc: int | None = None + charge_on_solar_lower_limit: int = CHARGE_ON_SOLAR_LOWER_LIMIT_DEFAULT + charge_on_solar_enabled: bool | None = None + charge_on_solar_lock: asyncio.Lock = field(default_factory=asyncio.Lock) + + @property + def polls_charge_limit(self) -> bool: + """Whether this vehicle's charge limit comes from polling rather than the stream.""" + return self.poll or not firmware_at_least(self.firmware, "2024.26") + + +class TeslemetryChargeOnSolarStore: + """Persist each vehicle's charge-on-solar settings for the config entry. + + The switch and lower limit number each send both values, and a registry-disabled + entity's restore state expires, so the settings are stored independently of them. + """ + + def __init__(self, hass: HomeAssistant, entry_id: str) -> None: + """Initialize the store.""" + self._store = Store[dict[str, dict[str, Any]]]( + hass, STORAGE_VERSION, f"{DOMAIN}.charge_on_solar.{entry_id}" + ) + self._data: dict[str, dict[str, Any]] = {} + + async def async_load(self, vehicles: list[TeslemetryVehicleData]) -> None: + """Load the stored settings into each vehicle.""" + self._data = await self._store.async_load() or {} + for vehicle in vehicles: + if stored := self._data.get(vehicle.vin): + vehicle.charge_on_solar_enabled = stored["enabled"] + vehicle.charge_on_solar_lower_limit = stored["lower_limit"] + vehicle.charge_limit_soc = stored["charge_limit_soc"] + + @callback + def async_save(self, vehicle: TeslemetryVehicleData) -> None: + """Schedule saving a vehicle's current settings if they changed.""" + settings = { + "enabled": vehicle.charge_on_solar_enabled, + "lower_limit": vehicle.charge_on_solar_lower_limit, + "charge_limit_soc": vehicle.charge_limit_soc, + } + if self._data.get(vehicle.vin) == settings: + return + self._data[vehicle.vin] = settings + self._store.async_delay_save(lambda: self._data) + + async def async_remove(self) -> None: + """Remove the stored settings.""" + await self._store.async_remove() @dataclass diff --git a/homeassistant/components/teslemetry/number.py b/homeassistant/components/teslemetry/number.py index 85f3514da3a6..50868e48fd47 100644 --- a/homeassistant/components/teslemetry/number.py +++ b/homeassistant/components/teslemetry/number.py @@ -5,7 +5,6 @@ from dataclasses import dataclass from itertools import chain from typing import Any, override -from tesla_fleet_api import firmware_at_least from tesla_fleet_api.const import Scope from tesla_fleet_api.router import VehicleRouter from tesla_fleet_api.tesla import EnergySiteRouter @@ -13,6 +12,7 @@ from tesla_fleet_api.teslemetry import EnergySite, Vehicle from teslemetry_stream import TeslemetryStreamVehicle from homeassistant.components.number import ( + DEFAULT_MAX_VALUE, NumberDeviceClass, NumberEntity, NumberEntityDescription, @@ -26,18 +26,24 @@ from homeassistant.const import ( STATE_UNKNOWN, UnitOfElectricCurrent, ) -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TeslemetryConfigEntry +from .const import CHARGE_LIMIT_SOC_KEY, CHARGE_ON_SOLAR_LOWER_LIMIT_KEY from .entity import ( + TeslemetryChargeOnSolarEntity, TeslemetryEnergyInfoEntity, TeslemetryRootEntity, TeslemetryVehiclePollingEntity, TeslemetryVehicleStreamEntity, ) -from .helpers import handle_command, handle_vehicle_command -from .models import TeslemetryEnergyData, TeslemetryVehicleData +from .helpers import async_set_charge_on_solar, handle_command, handle_vehicle_command +from .models import ( + TeslemetryChargeOnSolarStore, + TeslemetryEnergyData, + TeslemetryVehicleData, +) PARALLEL_UPDATES = 0 @@ -80,7 +86,7 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryNumberVehicleEntityDescription, ...] = ( max_listener=lambda x, y: x.listen_ChargeCurrentRequestMax(y), ), TeslemetryNumberVehicleEntityDescription( - key="charge_state_charge_limit_soc", + key=CHARGE_LIMIT_SOC_KEY, native_step=PRECISION_WHOLE, native_min_value=50, native_max_value=100, @@ -95,6 +101,16 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryNumberVehicleEntityDescription, ...] = ( ) +CHARGE_ON_SOLAR_LOWER_LIMIT_DESCRIPTION = NumberEntityDescription( + key=CHARGE_ON_SOLAR_LOWER_LIMIT_KEY, + native_step=PRECISION_WHOLE, + native_min_value=0, + native_unit_of_measurement=PERCENTAGE, + device_class=NumberDeviceClass.BATTERY, + mode=NumberMode.AUTO, +) + + @dataclass(frozen=True, kw_only=True) class TeslemetryNumberBatteryEntityDescription(NumberEntityDescription): """Describes Teslemetry Number entity.""" @@ -137,19 +153,21 @@ async def async_setup_entry( ) -> None: """Set up the Teslemetry number platform from a config entry.""" - async_add_entities( + entities: list[NumberEntity] = list( chain( ( TeslemetryVehiclePollingNumberEntity( vehicle, description, entry.runtime_data.scopes, + entry.runtime_data.charge_on_solar_store, ) - if vehicle.poll or not firmware_at_least(vehicle.firmware, "2024.26") + if vehicle.polls_charge_limit else TeslemetryStreamingNumberEntity( vehicle, description, entry.runtime_data.scopes, + entry.runtime_data.charge_on_solar_store, ) for vehicle in entry.runtime_data.vehicles for description in VEHICLE_DESCRIPTIONS @@ -168,12 +186,26 @@ async def async_setup_entry( ) ) + if (store := entry.runtime_data.charge_on_solar_store) is not None: + entities.extend( + TeslemetryChargeOnSolarLowerLimitNumberEntity( + vehicle, + CHARGE_ON_SOLAR_LOWER_LIMIT_DESCRIPTION, + store, + ) + for vehicle in entry.runtime_data.vehicles + ) + + async_add_entities(entities) + class TeslemetryVehicleNumberEntity(TeslemetryRootEntity, NumberEntity): """Vehicle number entity base class.""" api: Vehicle | VehicleRouter entity_description: TeslemetryNumberVehicleEntityDescription + vehicle: TeslemetryVehicleData + _charge_on_solar_store: TeslemetryChargeOnSolarStore | None @override async def async_set_native_value(self, value: float) -> None: @@ -181,6 +213,10 @@ class TeslemetryVehicleNumberEntity(TeslemetryRootEntity, NumberEntity): value = int(value) self.raise_for_scope(self.entity_description.scopes[0]) await handle_vehicle_command(self.entity_description.func(self.api, value)) + if self.entity_description.key == CHARGE_LIMIT_SOC_KEY: + self.vehicle.charge_limit_soc = value + if self._charge_on_solar_store is not None: + self._charge_on_solar_store.async_save(self.vehicle) self._attr_native_value = value self.async_write_ha_state() @@ -195,9 +231,11 @@ class TeslemetryVehiclePollingNumberEntity( data: TeslemetryVehicleData, description: TeslemetryNumberVehicleEntityDescription, scopes: list[Scope], + charge_on_solar_store: TeslemetryChargeOnSolarStore | None, ) -> None: """Initialize the number entity.""" self.scoped = any(scope in scopes for scope in description.scopes) + self._charge_on_solar_store = charge_on_solar_store self.entity_description = description super().__init__( data, @@ -227,9 +265,11 @@ class TeslemetryStreamingNumberEntity( data: TeslemetryVehicleData, description: TeslemetryNumberVehicleEntityDescription, scopes: list[Scope], + charge_on_solar_store: TeslemetryChargeOnSolarStore | None, ) -> None: """Initialize the Number entity.""" self.scoped = any(scope in scopes for scope in description.scopes) + self._charge_on_solar_store = charge_on_solar_store self.entity_description = description self._attr_native_max_value = self.entity_description.native_max_value super().__init__(data, description.key) @@ -310,3 +350,59 @@ class TeslemetryEnergyInfoNumberSensorEntity(TeslemetryEnergyInfoEntity, NumberE self._attr_native_value = value self.coordinator.async_set_command_value(self.key, value) self.async_write_ha_state() + + +class TeslemetryChargeOnSolarLowerLimitNumberEntity( + TeslemetryChargeOnSolarEntity, NumberEntity +): + """Number entity for the lower charge limit of Tesla's charge-on-solar mode.""" + + @property + @override + def native_max_value(self) -> float: + """Bound the lower limit by the charge limit.""" + value = self.vehicle.charge_limit_soc + return value if value is not None else DEFAULT_MAX_VALUE + + @override + async def async_added_to_hass(self) -> None: + """Handle entity which will be added.""" + self._attr_native_value = self.vehicle.charge_on_solar_lower_limit + await super().async_added_to_hass() + + @callback + @override + def _async_handle_charge_limit_soc(self, value: int | None) -> None: + """Store the latest charge limit and cap the lower limit to it.""" + super()._async_handle_charge_limit_soc(value) + upper_limit = int(self.native_max_value) + if self.vehicle.charge_on_solar_lower_limit > upper_limit: + self._async_store_lower_limit(upper_limit) + self.async_write_ha_state() + + def _async_store_lower_limit(self, value: int) -> None: + """Share the lower limit with the switch and persist it.""" + self._attr_native_value = value + self.vehicle.charge_on_solar_lower_limit = value + self._store.async_save(self.vehicle) + + @override + async def async_set_native_value(self, value: float) -> None: + """Set new value.""" + value = int(value) + + async with self.vehicle.charge_on_solar_lock: + if not self.vehicle.charge_on_solar_enabled: + self._async_store_lower_limit(value) + self.async_write_ha_state() + return + + sent_value = await async_set_charge_on_solar( + handle_vehicle_command, + self.api, + enabled=True, + lower_charge_limit=value, + charge_limit_soc=self.vehicle.charge_limit_soc, + ) + self._async_store_lower_limit(sent_value) + self.async_write_ha_state() diff --git a/homeassistant/components/teslemetry/strings.json b/homeassistant/components/teslemetry/strings.json index 29c877d599c5..7b58ef4ca5d3 100644 --- a/homeassistant/components/teslemetry/strings.json +++ b/homeassistant/components/teslemetry/strings.json @@ -481,6 +481,9 @@ "backup_reserve_percent": { "name": "Backup reserve" }, + "charge_on_solar_lower_limit": { + "name": "Charge on solar lower limit" + }, "charge_state_charge_current_request": { "name": "Charge current" }, @@ -1219,6 +1222,9 @@ } }, "switch": { + "charge_on_solar": { + "name": "Charge on solar" + }, "charge_state_charging_state": { "name": "Charge" }, @@ -1395,6 +1401,14 @@ "title": "Enable data streaming for {vehicle}" } }, + "preview_features": { + "charge_on_solar": { + "description": "Adds a vehicle switch to enable and disable Tesla's charge on solar mode, and a number entity to set its lower charge limit. The existing charge limit number entity is reused as the upper charge limit.\n\nThis feature does not currently expose a reliable state from the API, so the switch and lower limit use an assumed state.", + "disable_confirmation": "The charge-on-solar switch and lower limit will be removed from your Teslemetry vehicles.", + "enable_confirmation": "The charge-on-solar switch and lower limit will be added to your Teslemetry vehicles.", + "name": "Charge on solar" + } + }, "selector": { "days_of_week": { "options": { diff --git a/homeassistant/components/teslemetry/switch.py b/homeassistant/components/teslemetry/switch.py index bae023901abf..050f1d0f5042 100644 --- a/homeassistant/components/teslemetry/switch.py +++ b/homeassistant/components/teslemetry/switch.py @@ -21,13 +21,15 @@ from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import StateType from . import TeslemetryConfigEntry +from .const import CHARGE_ON_SOLAR_SWITCH_KEY from .entity import ( + TeslemetryChargeOnSolarEntity, TeslemetryEnergyInfoEntity, TeslemetryRootEntity, TeslemetryVehiclePollingEntity, TeslemetryVehicleStreamEntity, ) -from .helpers import handle_command, handle_vehicle_command +from .helpers import async_set_charge_on_solar, handle_command, handle_vehicle_command from .models import TeslemetryEnergyData, TeslemetryVehicleData PARALLEL_UPDATES = 0 @@ -152,6 +154,11 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetrySwitchEntityDescription, ...] = ( ), ) +CHARGE_ON_SOLAR_SWITCH_DESCRIPTION = SwitchEntityDescription( + key=CHARGE_ON_SOLAR_SWITCH_KEY, + device_class=SwitchDeviceClass.SWITCH, +) + async def async_setup_entry( hass: HomeAssistant, @@ -195,6 +202,16 @@ async def async_setup_entry( if energysite.info_coordinator.data.get("components_storm_mode_capable") ) + if (store := entry.runtime_data.charge_on_solar_store) is not None: + entities.extend( + TeslemetryChargeOnSolarSwitchEntity( + vehicle, + CHARGE_ON_SOLAR_SWITCH_DESCRIPTION, + store, + ) + for vehicle in entry.runtime_data.vehicles + ) + async_add_entities(entities) @@ -381,3 +398,38 @@ class TeslemetryStormModeSwitchEntity(TeslemetryEnergyInfoEntity, SwitchEntity): self._attr_is_on = False self.coordinator.async_set_command_value(self.key, False) self.async_write_ha_state() + + +class TeslemetryChargeOnSolarSwitchEntity(TeslemetryChargeOnSolarEntity, SwitchEntity): + """Switch entity for Tesla charge-on-solar mode.""" + + @override + async def async_added_to_hass(self) -> None: + """Handle entity which will be added.""" + await super().async_added_to_hass() + self._attr_is_on = self.vehicle.charge_on_solar_enabled + + async def _async_set_charge_on_solar(self, enabled: bool) -> None: + """Set charge-on-solar mode, omitting the upper bound if it isn't known yet.""" + async with self.vehicle.charge_on_solar_lock: + await async_set_charge_on_solar( + handle_vehicle_command, + self.api, + enabled=enabled, + lower_charge_limit=self.vehicle.charge_on_solar_lower_limit, + charge_limit_soc=self.vehicle.charge_limit_soc, + ) + self.vehicle.charge_on_solar_enabled = enabled + self._store.async_save(self.vehicle) + self._attr_is_on = enabled + self.async_write_ha_state() + + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Turn on charge-on-solar mode.""" + await self._async_set_charge_on_solar(enabled=True) + + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Turn off charge-on-solar mode.""" + await self._async_set_charge_on_solar(enabled=False) diff --git a/homeassistant/generated/labs.py b/homeassistant/generated/labs.py index d4609aec5599..549a2030a2da 100644 --- a/homeassistant/generated/labs.py +++ b/homeassistant/generated/labs.py @@ -39,4 +39,11 @@ LABS_PREVIEW_FEATURES = { "report_issue_url": "https://github.com/home-assistant/core/issues/new?template=bug_report.yml&integration_link=https://www.home-assistant.io/integrations/kitchen_sink&integration_name=Kitchen%20Sink", }, }, + "teslemetry": { + "charge_on_solar": { + "feedback_url": "https://community.home-assistant.io", + "learn_more_url": "https://www.home-assistant.io/integrations/teslemetry", + "report_issue_url": "https://github.com/home-assistant/core/issues/new?template=bug_report.yml&integration_link=https://www.home-assistant.io/integrations/teslemetry&integration_name=Teslemetry", + }, + }, } diff --git a/tests/components/teslemetry/conftest.py b/tests/components/teslemetry/conftest.py index f919bc094803..ff62764694e6 100644 --- a/tests/components/teslemetry/conftest.py +++ b/tests/components/teslemetry/conftest.py @@ -20,6 +20,7 @@ from .const import ( METADATA, METADATA_ENERGY, METADATA_LEGACY, + METADATA_OLD_FIRMWARE, POWERWALL_STATUS, PRODUCTS, PRODUCTS_ENERGY, @@ -94,6 +95,16 @@ def mock_legacy(): yield mock_products +@pytest.fixture +def mock_old_firmware(): + """Mock a non-polling vehicle whose firmware predates ChargeLimitSoc streaming.""" + with patch( + "tesla_fleet_api.teslemetry.Teslemetry.metadata", + return_value=METADATA_OLD_FIRMWARE, + ) as mock_products: + yield mock_products + + @pytest.fixture(autouse=True) def mock_wake_up(): """Mock Tesla Fleet API Vehicle Specific wake_up method.""" diff --git a/tests/components/teslemetry/const.py b/tests/components/teslemetry/const.py index 8fe038a922b3..5e30114e33c8 100644 --- a/tests/components/teslemetry/const.py +++ b/tests/components/teslemetry/const.py @@ -6,6 +6,7 @@ from homeassistant.components.teslemetry.const import DOMAIN, TeslemetryState from homeassistant.const import CONF_ACCESS_TOKEN UNIQUE_ID = "abc-123" +VIN = "LRW3F7EK4NC700000" CONFIG_V1 = {CONF_ACCESS_TOKEN: "abc-123"} # The vehicle in products.json, and the Bluetooth address a subentry pairs it at. @@ -165,6 +166,39 @@ METADATA_LEGACY = { } }, } +METADATA_OLD_FIRMWARE = { + "uid": UNIQUE_ID, + "region": "NA", + "scopes": [ + "openid", + "offline_access", + "user_data", + "vehicle_device_data", + "vehicle_cmds", + "vehicle_charging_cmds", + "vehicle_location", + "energy_device_data", + "energy_cmds", + ], + "vehicles": { + "LRW3F7EK4NC700000": { + "proxy": True, + "access": True, + "polling": False, + "firmware": "2024.20", + "discounted": False, + "fleet_telemetry": "1.0.2", + "name": "Home Assistant", + "config": VEHICLE_CONFIG, + } + }, + "energy_sites": { + "123456": { + "access": True, + "name": "Energy Site", + } + }, +} METADATA_NOSCOPE = { "uid": UNIQUE_ID, "region": "NA", diff --git a/tests/components/teslemetry/test_init.py b/tests/components/teslemetry/test_init.py index 6d18a723c165..508e87693267 100644 --- a/tests/components/teslemetry/test_init.py +++ b/tests/components/teslemetry/test_init.py @@ -57,6 +57,7 @@ from homeassistant.components.homeassistant import ( DOMAIN as HOMEASSISTANT_DOMAIN, SERVICE_UPDATE_ENTITY, ) +from homeassistant.components.labs import async_update_preview_feature from homeassistant.components.lock import LockState from homeassistant.components.number import ( ATTR_VALUE, @@ -79,6 +80,7 @@ from homeassistant.components.teslemetry.const import ( CONF_SITE_ID, CONF_VIN, DOMAIN, + LABS_CHARGE_ON_SOLAR_FEATURE, SUBENTRY_TYPE_ENERGY_SITE, SUBENTRY_TYPE_VEHICLE, ) @@ -3143,6 +3145,52 @@ async def test_user_subentry_persists_across_reload(hass: HomeAssistant) -> None assert subentries[0].data == {CONF_VIN: VIN, CONF_ADDRESS: ADDRESS} +async def test_labs_charge_on_solar_toggle_triggers_reload( + hass: HomeAssistant, +) -> None: + """Test labs charge-on-solar feature toggle schedules an integration reload.""" + assert await async_setup_component(hass, "labs", {}) + entry = await setup_platform(hass) + assert entry.state is ConfigEntryState.LOADED + + with patch.object(hass.config_entries, "async_schedule_reload") as mock_reload: + await async_update_preview_feature( + hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, True + ) + await hass.async_block_till_done() + + mock_reload.assert_called_once_with(entry.entry_id) + + +async def test_charge_on_solar_settings_removed_with_entry( + hass: HomeAssistant, + hass_storage: dict[str, Any], +) -> None: + """Test the charge-on-solar settings are stored per entry and removed with it.""" + assert await async_setup_component(hass, "labs", {}) + await async_update_preview_feature(hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, True) + entry = await setup_platform(hass, [Platform.NUMBER]) + storage_key = f"{DOMAIN}.charge_on_solar.{entry.entry_id}" + + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 35}, + blocking=True, + ) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert hass_storage[storage_key]["data"] == { + VIN: {"enabled": None, "lower_limit": 35, "charge_limit_soc": None} + } + + await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + + assert storage_key not in hass_storage + + # A paired site's local live_status reading. _LOCAL_LIVE_STATUS = { "response": { diff --git a/tests/components/teslemetry/test_number.py b/tests/components/teslemetry/test_number.py index 15f21827c193..f32d698874fe 100644 --- a/tests/components/teslemetry/test_number.py +++ b/tests/components/teslemetry/test_number.py @@ -1,24 +1,53 @@ """Test the Teslemetry number platform.""" -from unittest.mock import AsyncMock, patch +import asyncio +from copy import deepcopy +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch +from freezegun.api import FrozenDateTimeFactory import pytest +from pytest_homeassistant.common import async_fire_time_changed from syrupy.assertion import SnapshotAssertion from tesla_fleet_api.exceptions import InvalidCommand from teslemetry_stream import Signal +from homeassistant.components.labs import async_update_preview_feature from homeassistant.components.number import ( ATTR_VALUE, DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE, ) +from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_ON +from homeassistant.components.teslemetry.const import ( + DOMAIN, + LABS_CHARGE_ON_SOLAR_FEATURE, +) +from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL +from homeassistant.components.teslemetry.number import ( + TeslemetryChargeOnSolarLowerLimitNumberEntity, +) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant -from homeassistant.exceptions import HomeAssistantError +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import entity_registry as er +from homeassistant.setup import async_setup_component -from . import assert_entities, reload_platform, setup_platform -from .const import COMMAND_ERRORS, COMMAND_OK, VEHICLE_DATA_ALT +from . import assert_entities, mock_config_entry, reload_platform, setup_platform +from .const import ( + COMMAND_ERRORS, + COMMAND_OK, + METADATA_NOSCOPE, + VEHICLE_DATA, + VEHICLE_DATA_ALT, + VIN, +) + + +async def _async_enable_charge_on_solar_preview_feature(hass: HomeAssistant) -> None: + """Enable the Teslemetry charge-on-solar preview feature.""" + assert await async_setup_component(hass, "labs", {}) + await async_update_preview_feature(hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, True) @pytest.mark.usefixtures("entity_registry_enabled_by_default") @@ -178,3 +207,754 @@ async def test_number_streaming( # Assert the entities restored their values with concrete assertions assert hass.states.get("number.test_charge_current").state == "24" assert hass.states.get("number.test_charge_limit").state == "99" + + +async def test_charge_on_solar_lower_limit_disabled_by_default( + hass: HomeAssistant, +) -> None: + """Test charge-on-solar lower limit is disabled by default.""" + await setup_platform(hass, [Platform.NUMBER]) + + assert hass.states.get("number.test_charge_on_solar_lower_limit") is None + + +async def test_charge_on_solar_lower_limit_enabled_by_labs( + hass: HomeAssistant, +) -> None: + """Test charge-on-solar lower limit appears when Labs feature is enabled.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.NUMBER]) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.state == "20" + assert state.attributes["assumed_state"] is True + + +async def test_charge_on_solar_lower_limit_capped_by_charge_limit( + hass: HomeAssistant, +) -> None: + """Test the lower limit's max value tracks the current charge limit SOC.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + await setup_platform(hass, [Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](70) + await hass.async_block_till_done() + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 70 + + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 60}, + blocking=True, + ) + + # A subsequent drop below the stored value clamps it down too + for call in listener.call_args_list: + call.args[0](50) + await hass.async_block_till_done() + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 50 + assert state.state == "50" + + +async def test_charge_on_solar_lower_limit_capped_by_charge_limit_polling( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_vehicle_data: AsyncMock, + mock_legacy: AsyncMock, +) -> None: + """Test the polling lower limit's max value tracks the coordinator charge limit.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.NUMBER]) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 80 + + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 70}, + blocking=True, + ) + + lowered_data = deepcopy(VEHICLE_DATA) + lowered_data["response"]["charge_state"]["charge_limit_soc"] = 50 + mock_vehicle_data.return_value = lowered_data + freezer.tick(VEHICLE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 50 + assert state.state == "50" + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_old_firmware") +async def test_charge_on_solar_lower_limit_old_firmware_follows_polled_charge_limit( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a stream-only vehicle on pre-streaming firmware is capped by the polled charge limit.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.NUMBER]) + + # This vehicle's raw poll flag is off, so its coordinator gets no initial + # refresh; the linked charge-limit entity has no value yet, so max falls + # back to its default. + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 100 + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 90}, + blocking=True, + ) + + freezer.tick(VEHICLE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert hass.states.get("number.test_charge_limit").state == "80" + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 80 + assert state.state == "80" + with pytest.raises(ServiceValidationError): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 90}, + blocking=True, + ) + + +async def test_charge_on_solar_lower_limit_restores_max_value( + hass: HomeAssistant, +) -> None: + """Test the lower limit's max value survives a reload without new telemetry.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + entry = await setup_platform(hass, [Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](70) + await hass.async_block_till_done() + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 70 + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc", + return_value=lambda: None, + ): + await reload_platform(hass, entry, [Platform.NUMBER]) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 70 + + +async def test_charge_on_solar_lower_limit_set_value_while_disabled( + hass: HomeAssistant, +) -> None: + """Test setting the lower limit while charge-on-solar is off updates state only.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.NUMBER]) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 35}, + blocking=True, + ) + command.assert_not_called() + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.state == "35" + + +async def test_charge_on_solar_lower_limit_set_value_while_enabled( + hass: HomeAssistant, +) -> None: + """Test setting the lower limit while charge-on-solar is on sends the command.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](91) + await hass.async_block_till_done() + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 35}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=35, + upper_charge_limit=91, + ) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.state == "35" + + +async def test_charge_on_solar_lower_limit_reaches_vehicle_when_switch_disabled( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, +) -> None: + """Test a number change still reaches the vehicle once the switch entity is registry-disabled.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + entry = await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + + entity_registry.async_update_entity( + "switch.test_charge_on_solar", + disabled_by=er.RegistryEntryDisabler.USER, + ) + await hass.async_block_till_done() + + await reload_platform(hass, entry, [Platform.SWITCH, Platform.NUMBER]) + + assert hass.states.get("switch.test_charge_on_solar") is None + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 45}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=45, + upper_charge_limit=None, + ) + + +async def test_charge_on_solar_lower_limit_uses_stored_state_when_switch_disabled( + hass: HomeAssistant, + hass_storage: dict[str, Any], + entity_registry: er.EntityRegistry, +) -> None: + """Test a number change reaches the vehicle after a restart with the switch long disabled.""" + await _async_enable_charge_on_solar_preview_feature(hass) + entry = mock_config_entry() + entry.add_to_hass(hass) + # No restore state exists for the disabled switch, as once it has expired. + hass_storage[f"{DOMAIN}.charge_on_solar.{entry.entry_id}"] = { + "version": 1, + "data": {VIN: {"enabled": True, "lower_limit": 35, "charge_limit_soc": None}}, + } + entity_registry.async_get_or_create( + SWITCH_DOMAIN, + DOMAIN, + f"{VIN}-charge_on_solar", + config_entry=entry, + disabled_by=er.RegistryEntryDisabler.USER, + ) + + with patch( + "homeassistant.components.teslemetry.PLATFORMS", + [Platform.SWITCH, Platform.NUMBER], + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get("switch.test_charge_on_solar") is None + assert (state := hass.states.get("number.test_charge_on_solar_lower_limit")) + assert state.state == "35" + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 45}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=45, + upper_charge_limit=None, + ) + + +async def test_charge_on_solar_lower_limit_uses_live_charge_limit( + hass: HomeAssistant, +) -> None: + """Test the lower limit command carries the live charge limit, not a stale cache.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](91) + await hass.async_block_till_done() + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + + # The owner raises the charge limit with no stream or poll update following it. + with patch( + "tesla_fleet_api.teslemetry.Vehicle.set_charge_limit", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_limit", ATTR_VALUE: 95}, + blocking=True, + ) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 35}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=35, + upper_charge_limit=95, + ) + + +async def test_charge_on_solar_lower_limit_rejects_stale_max_while_disabled( + hass: HomeAssistant, +) -> None: + """Test the lower limit's advertised max tracks a locally lowered charge limit.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.NUMBER]) + + # The owner lowers the charge limit locally with no stream or poll update following it. + with patch( + "tesla_fleet_api.teslemetry.Vehicle.set_charge_limit", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_limit", ATTR_VALUE: 50}, + blocking=True, + ) + + with pytest.raises(ServiceValidationError): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 60}, + blocking=True, + ) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.state == "20" + + +async def test_charge_on_solar_switch_and_lower_limit_are_serialized( + hass: HomeAssistant, +) -> None: + """Test a concurrent switch turn-on and lower-limit set don't diverge from the vehicle.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](80) + await hass.async_block_till_done() + + switch_call_started = asyncio.Event() + release_switch_call = asyncio.Event() + lower_limit_reached_lock = asyncio.Event() + + async def slow_charge_on_solar(**kwargs: Any) -> dict[str, Any]: + switch_call_started.set() + await release_switch_call.wait() + return COMMAND_OK + + set_native_value = ( + TeslemetryChargeOnSolarLowerLimitNumberEntity.async_set_native_value + ) + + async def tracked_set_native_value( + self: TeslemetryChargeOnSolarLowerLimitNumberEntity, value: float + ) -> None: + lower_limit_reached_lock.set() + await set_native_value(self, value) + + with ( + patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + side_effect=slow_charge_on_solar, + ) as command, + # The lock is taken first thing in the set, so once it is entered the number + # either waits on the lock or runs ahead of the switch. + patch.object( + TeslemetryChargeOnSolarLowerLimitNumberEntity, + "async_set_native_value", + tracked_set_native_value, + ), + ): + turn_on = hass.async_create_task( + hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ), + "test turn on charge-on-solar", + ) + await switch_call_started.wait() + + set_lower_limit = hass.async_create_task( + hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + { + ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", + ATTR_VALUE: 35, + }, + blocking=True, + ), + "test set charge-on-solar lower limit", + ) + + await lower_limit_reached_lock.wait() + assert command.call_count == 1 + + release_switch_call.set() + await turn_on + await set_lower_limit + + assert command.call_count == 2 + command.assert_called_with( + enabled=True, + lower_charge_limit=35, + upper_charge_limit=80, + ) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.state == "35" + + +async def test_charge_on_solar_lower_limit_set_value_command_failure( + hass: HomeAssistant, +) -> None: + """Test a failed command leaves the previous value intact, not the optimistic one.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](91) + await hass.async_block_till_done() + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + + with ( + patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + side_effect=InvalidCommand, + ), + pytest.raises(HomeAssistantError), + ): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 35}, + blocking=True, + ) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.state == "20" + + +async def test_disable_charge_on_solar_preview_removes_lower_limit( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, +) -> None: + """Test disabling preview removes the lower limit from entity registry.""" + await _async_enable_charge_on_solar_preview_feature(hass) + entry = await setup_platform(hass, [Platform.NUMBER]) + + assert ( + entity_registry.async_get("number.test_charge_on_solar_lower_limit") is not None + ) + + with patch.object(hass.config_entries, "async_schedule_reload"): + await async_update_preview_feature( + hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, False + ) + await hass.async_block_till_done() + + await reload_platform(hass, entry, [Platform.NUMBER]) + + assert entity_registry.async_get("number.test_charge_on_solar_lower_limit") is None + + +async def test_charge_on_solar_lower_limit_removed_without_command_scope( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_metadata: MagicMock, +) -> None: + """Test the lower limit is removed when the vehicle commands scope is revoked.""" + await _async_enable_charge_on_solar_preview_feature(hass) + entry = await setup_platform(hass, [Platform.NUMBER]) + + assert ( + entity_registry.async_get("number.test_charge_on_solar_lower_limit") is not None + ) + + mock_metadata.return_value = METADATA_NOSCOPE + await reload_platform(hass, entry, [Platform.NUMBER]) + + assert entity_registry.async_get("number.test_charge_on_solar_lower_limit") is None + + +@pytest.mark.parametrize( + "charge_limit_echo", + [ + pytest.param((90,), id="echoed"), + pytest.param((), id="not_echoed"), + ], +) +async def test_charge_on_solar_locally_set_charge_limit_survives_reload( + hass: HomeAssistant, + charge_limit_echo: tuple[int, ...], +) -> None: + """Test a charge limit set from Home Assistant survives a reload, echoed or not.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + entry = await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + for call in listener.call_args_list: + call.args[0](80) + await hass.async_block_till_done() + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.set_charge_limit", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_limit", ATTR_VALUE: 90}, + blocking=True, + ) + + # The vehicle may or may not echo the new limit on the stream before the reload. + for value in charge_limit_echo: + for call in listener.call_args_list: + call.args[0](value) + await hass.async_block_till_done() + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc", + return_value=lambda: None, + ): + await reload_platform(hass, entry, [Platform.SWITCH, Platform.NUMBER]) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=90, + ) + + +async def test_charge_on_solar_switch_uses_locally_set_charge_limit( + hass: HomeAssistant, +) -> None: + """Test the switch sends a charge limit set from Home Assistant as the upper bound.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch( + "teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc" + ) as listener: + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](80) + await hass.async_block_till_done() + + # The owner raises the charge limit with no stream or poll update following it. + with patch( + "tesla_fleet_api.teslemetry.Vehicle.set_charge_limit", + return_value=COMMAND_OK, + ): + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_limit", ATTR_VALUE: 95}, + blocking=True, + ) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=95, + ) + + +@pytest.mark.usefixtures("mock_legacy") +async def test_charge_on_solar_unknown_polled_charge_limit( + hass: HomeAssistant, + mock_vehicle_data: AsyncMock, +) -> None: + """Test a polled vehicle without a charge limit leaves the upper bound unset.""" + vehicle_data = deepcopy(VEHICLE_DATA) + vehicle_data["response"]["charge_state"]["charge_limit_soc"] = None + mock_vehicle_data.return_value = vehicle_data + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + state = hass.states.get("number.test_charge_on_solar_lower_limit") + assert state is not None + assert state.attributes["max"] == 100 + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=None, + ) diff --git a/tests/components/teslemetry/test_switch.py b/tests/components/teslemetry/test_switch.py index 66401034d338..230615c3c1d5 100644 --- a/tests/components/teslemetry/test_switch.py +++ b/tests/components/teslemetry/test_switch.py @@ -1,24 +1,51 @@ """Test the Teslemetry switch platform.""" +from typing import Any from unittest.mock import AsyncMock, patch +from freezegun.api import FrozenDateTimeFactory import pytest +from pytest_homeassistant.common import async_fire_time_changed from syrupy.assertion import SnapshotAssertion from tesla_fleet_api.exceptions import InvalidCommand, InvalidRequest, TeslaFleetError from teslemetry_stream import Signal +from homeassistant.components.labs import async_update_preview_feature +from homeassistant.components.number import ( + ATTR_VALUE, + DOMAIN as NUMBER_DOMAIN, + SERVICE_SET_VALUE, +) from homeassistant.components.switch import ( DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) +from homeassistant.components.teslemetry.const import ( + DOMAIN, + LABS_CHARGE_ON_SOLAR_FEATURE, +) +from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er +from homeassistant.setup import async_setup_component -from . import assert_entities, assert_entities_alt, reload_platform, setup_platform -from .const import COMMAND_ERRORS, COMMAND_OK, VEHICLE_DATA_ALT +from . import ( + assert_entities, + assert_entities_alt, + mock_config_entry, + reload_platform, + setup_platform, +) +from .const import COMMAND_ERRORS, COMMAND_OK, VEHICLE_DATA_ALT, VIN + + +async def _async_enable_charge_on_solar_preview_feature(hass: HomeAssistant) -> None: + """Enable the Teslemetry charge-on-solar preview feature.""" + assert await async_setup_component(hass, "labs", {}) + await async_update_preview_feature(hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, True) async def test_switch( @@ -287,3 +314,363 @@ async def test_switch_streaming( assert hass.states.get("switch.test_auto_steering_wheel_heater").state == STATE_ON assert hass.states.get("switch.test_defrost").state == STATE_OFF assert hass.states.get("switch.test_charge").state == STATE_ON + + +async def test_charge_on_solar_switch_disabled_by_default( + hass: HomeAssistant, +) -> None: + """Test charge-on-solar switch is disabled by default.""" + await setup_platform(hass, [Platform.SWITCH]) + + assert hass.states.get("switch.test_charge_on_solar") is None + + +async def test_charge_on_solar_switch_enabled_by_labs( + hass: HomeAssistant, +) -> None: + """Test charge-on-solar switch appears when Labs feature is enabled.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.SWITCH]) + + assert (state := hass.states.get("switch.test_charge_on_solar")) is not None + assert state.attributes["assumed_state"] is True + + +@pytest.mark.parametrize( + ("service", "enabled", "expected_state"), + [ + (SERVICE_TURN_ON, True, STATE_ON), + (SERVICE_TURN_OFF, False, STATE_OFF), + ], +) +async def test_charge_on_solar_switch_services( + hass: HomeAssistant, + service: str, + enabled: bool, + expected_state: str, +) -> None: + """Test charge-on-solar switch service calls use the default lower limit.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch("teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc") as ( + listener + ): + listener.return_value = lambda: None + entry = await setup_platform(hass, [Platform.SWITCH]) + + for call in listener.call_args_list: + call.args[0](91) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + service, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=enabled, + lower_charge_limit=20, + upper_charge_limit=91, + ) + + assert (state := hass.states.get("switch.test_charge_on_solar")) is not None + assert state.state == expected_state + assert state.attributes["assumed_state"] is True + + await reload_platform(hass, entry, [Platform.SWITCH]) + + assert (restored := hass.states.get("switch.test_charge_on_solar")) is not None + assert restored.state == expected_state + assert restored.attributes["assumed_state"] is True + + +async def test_charge_on_solar_switch_services_polling( + hass: HomeAssistant, + mock_legacy: AsyncMock, +) -> None: + """Test charge-on-solar switch service calls fetch the polled charge limit.""" + await _async_enable_charge_on_solar_preview_feature(hass) + await setup_platform(hass, [Platform.SWITCH]) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=80, + ) + + assert (state := hass.states.get("switch.test_charge_on_solar")) is not None + assert state.state == STATE_ON + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_old_firmware") +async def test_charge_on_solar_switch_services_old_firmware( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a non-polling vehicle below the streaming firmware still fetches the polled charge limit.""" + await _async_enable_charge_on_solar_preview_feature(hass) + # The charge limit number is the polling entity that keeps the coordinator running. + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + # This vehicle's raw poll flag is off, so its coordinator gets no initial + # refresh; wait for the first poll so the charge limit is known. + freezer.tick(VEHICLE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=80, + ) + + assert (state := hass.states.get("switch.test_charge_on_solar")) is not None + assert state.state == STATE_ON + + +async def test_charge_on_solar_switch_uses_lower_limit_number( + hass: HomeAssistant, +) -> None: + """Test the switch sends the value set on the lower limit number entity.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch("teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc") as ( + listener + ): + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + for call in listener.call_args_list: + call.args[0](91) + await hass.async_block_till_done() + + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", ATTR_VALUE: 40}, + blocking=True, + ) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=40, + upper_charge_limit=91, + ) + + +async def test_charge_on_solar_switch_turn_on_uses_restored_charge_limit( + hass: HomeAssistant, +) -> None: + """Test turning on after a restart uses the restored charge limit, not a guess.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch("teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc") as ( + listener + ): + listener.return_value = lambda: None + entry = await setup_platform(hass, [Platform.SWITCH]) + + for call in listener.call_args_list: + call.args[0](65) + + await reload_platform(hass, entry, [Platform.SWITCH]) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=65, + ) + + +async def test_charge_on_solar_switch_uses_limit_when_number_disabled( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, +) -> None: + """Test the switch still sends the user's limit once the number entity is registry-disabled.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch("teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc") as ( + listener + ): + listener.return_value = lambda: None + entry = await setup_platform(hass, [Platform.SWITCH, Platform.NUMBER]) + + await hass.services.async_call( + NUMBER_DOMAIN, + SERVICE_SET_VALUE, + { + ATTR_ENTITY_ID: "number.test_charge_on_solar_lower_limit", + ATTR_VALUE: 35, + }, + blocking=True, + ) + + entity_registry.async_update_entity( + "number.test_charge_on_solar_lower_limit", + disabled_by=er.RegistryEntryDisabler.USER, + ) + await hass.async_block_till_done() + + await reload_platform(hass, entry, [Platform.SWITCH, Platform.NUMBER]) + + assert hass.states.get("number.test_charge_on_solar_lower_limit") is None + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=35, + upper_charge_limit=None, + ) + + +async def test_charge_on_solar_switch_uses_stored_limit_when_number_disabled( + hass: HomeAssistant, + hass_storage: dict[str, Any], + entity_registry: er.EntityRegistry, +) -> None: + """Test the switch sends the stored limit after a restart with the number long disabled.""" + await _async_enable_charge_on_solar_preview_feature(hass) + entry = mock_config_entry() + entry.add_to_hass(hass) + # No restore state exists for the disabled number, as once it has expired. + hass_storage[f"{DOMAIN}.charge_on_solar.{entry.entry_id}"] = { + "version": 1, + "data": {VIN: {"enabled": False, "lower_limit": 35, "charge_limit_soc": None}}, + } + entity_registry.async_get_or_create( + NUMBER_DOMAIN, + DOMAIN, + f"{VIN}-charge_on_solar_lower_limit", + config_entry=entry, + disabled_by=er.RegistryEntryDisabler.USER, + ) + + with patch( + "homeassistant.components.teslemetry.PLATFORMS", + [Platform.SWITCH, Platform.NUMBER], + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get("number.test_charge_on_solar_lower_limit") is None + assert (state := hass.states.get("switch.test_charge_on_solar")) is not None + assert state.state == STATE_OFF + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=35, + upper_charge_limit=None, + ) + + +async def test_charge_on_solar_switch_turn_on_omits_unknown_charge_limit( + hass: HomeAssistant, +) -> None: + """Test turning on omits the upper limit rather than guessing when unknown.""" + await _async_enable_charge_on_solar_preview_feature(hass) + + with patch("teslemetry_stream.TeslemetryStreamVehicle.listen_ChargeLimitSoc") as ( + listener + ): + listener.return_value = lambda: None + await setup_platform(hass, [Platform.SWITCH]) + + with patch( + "tesla_fleet_api.teslemetry.Vehicle.charge_on_solar", + return_value=COMMAND_OK, + ) as command: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_charge_on_solar"}, + blocking=True, + ) + command.assert_called_once_with( + enabled=True, + lower_charge_limit=20, + upper_charge_limit=None, + ) + + +async def test_disable_charge_on_solar_preview_removes_registry_entries( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, +) -> None: + """Test disabling preview removes charge-on-solar switch from entity registry.""" + await _async_enable_charge_on_solar_preview_feature(hass) + entry = await setup_platform(hass, [Platform.SWITCH]) + + assert entity_registry.async_get("switch.test_charge_on_solar") is not None + + with patch.object(hass.config_entries, "async_schedule_reload"): + await async_update_preview_feature( + hass, DOMAIN, LABS_CHARGE_ON_SOLAR_FEATURE, False + ) + await hass.async_block_till_done() + + await reload_platform(hass, entry, [Platform.SWITCH]) + + assert entity_registry.async_get("switch.test_charge_on_solar") is None