diff --git a/homeassistant/components/spin_ble/__init__.py b/homeassistant/components/spin_ble/__init__.py index a0f0ecd5425a..5961fbd6b8a4 100644 --- a/homeassistant/components/spin_ble/__init__.py +++ b/homeassistant/components/spin_ble/__init__.py @@ -10,10 +10,10 @@ from .coordinator import SpinEvConfigEntry, SpinEvCoordinator async def async_setup_entry(hass: HomeAssistant, entry: SpinEvConfigEntry) -> None: """Set up a charger from a config entry.""" coordinator = SpinEvCoordinator(hass, entry) - entry.async_on_unload(coordinator.async_release) + # The coordinator shuts itself down on unload, but not on stop. async def _async_stop(event: Event) -> None: - await coordinator.async_release() + await coordinator.async_shutdown() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop) diff --git a/homeassistant/components/spin_ble/const.py b/homeassistant/components/spin_ble/const.py index 69c9ace24bb4..93c370406003 100644 --- a/homeassistant/components/spin_ble/const.py +++ b/homeassistant/components/spin_ble/const.py @@ -11,7 +11,7 @@ DOMAIN: Final = "spin_ble" MANUFACTURER: Final = "Exicom" MODEL: Final = "Spin" -PLATFORMS: Final = [Platform.SENSOR] +PLATFORMS: Final = [Platform.SENSOR, Platform.SWITCH] CONF_CONNECTION_MODE: Final = "connection_mode" CONF_SERIAL: Final = "serial" @@ -34,3 +34,6 @@ CHARGING_INTERVAL: Final = timedelta(seconds=60) #: Poll interval while idle. Kept long so the charger's single Bluetooth slot #: is left free for the phone app for long stretches. IDLE_INTERVAL: Final = timedelta(seconds=300) +#: Wait before re-reading after a command. The charger acknowledges at once but +#: takes about a second to report the new state. +COMMAND_SETTLE_TIME: Final = timedelta(seconds=2) diff --git a/homeassistant/components/spin_ble/coordinator.py b/homeassistant/components/spin_ble/coordinator.py index 468ddd1946c6..be1bb7c31213 100644 --- a/homeassistant/components/spin_ble/coordinator.py +++ b/homeassistant/components/spin_ble/coordinator.py @@ -1,22 +1,33 @@ """Coordinator for the Spin EV Charger integration.""" +import asyncio +from collections.abc import Awaitable, Callable import logging from typing import override from bleak.backends.device import BLEDevice from bleak_retry_connector import close_stale_connections_by_address from habluetooth import HaBleakClientWrapper -from spinev_ble import BleTransport, ChargerStatus, SpinEvCharger, SpinEvError +from spinev_ble import ( + BleTransport, + ChargerStatus, + SpinEvCharger, + SpinEvCommandRejectedError, + SpinEvError, +) from homeassistant.components import bluetooth from homeassistant.components.bluetooth import BluetoothReachabilityIntent from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ADDRESS from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( CHARGING_INTERVAL, + COMMAND_SETTLE_TIME, CONF_CONNECTION_MODE, DEFAULT_CONNECTION_MODE, DOMAIN, @@ -54,6 +65,12 @@ class SpinEvCoordinator(DataUpdateCoordinator[ChargerStatus]): config_entry=entry, name=DOMAIN, update_interval=CHARGING_INTERVAL, + request_refresh_debouncer=Debouncer( + hass, + _LOGGER, + cooldown=COMMAND_SETTLE_TIME.total_seconds(), + immediate=False, + ), ) self.address: str = entry.data[CONF_ADDRESS] self._keep_connected = ( @@ -61,6 +78,12 @@ class SpinEvCoordinator(DataUpdateCoordinator[ChargerStatus]): == ConnectionMode.PERSISTENT ) self._charger: SpinEvCharger | None = None + # A command and a poll must not share the one link at the same time, + # or one releases it from under the other. + self._link = asyncio.Lock() + # Loop time before which a read still sees the state from before the + # last command. + self._settled_at = 0.0 @override async def _async_setup(self) -> None: @@ -70,20 +93,25 @@ class SpinEvCoordinator(DataUpdateCoordinator[ChargerStatus]): @override async def _async_update_data(self) -> ChargerStatus: """Read a full status snapshot.""" - charger = await self._async_charger() - try: - await charger.async_connect() - status = await charger.async_get_status() - except SpinEvError as err: - await self.async_release() - raise UpdateFailed( - translation_domain=DOMAIN, - translation_key="cannot_read", - translation_placeholders={"error": str(err)}, - ) from err - finally: - if not self._keep_connected: + async with self._link: + # Covers a scheduled poll as well as the post-command refresh, since + # a poll cancels that refresh when it runs first. + if (settling := self._settled_at - self.hass.loop.time()) > 0: + await asyncio.sleep(settling) + charger = await self._async_charger() + try: + await charger.async_connect() + status = await charger.async_get_status() + except SpinEvError as err: await self.async_release() + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="cannot_read", + translation_placeholders={"error": str(err)}, + ) from err + finally: + if not self._keep_connected: + await self.async_release() # A suspended session can resume without a command, so it is polled at # the charging rate rather than the idle one. @@ -93,6 +121,57 @@ class SpinEvCoordinator(DataUpdateCoordinator[ChargerStatus]): self.update_interval = CHARGING_INTERVAL if session_open else IDLE_INTERVAL return status + async def async_start_charging(self) -> None: + """Start a charging session.""" + await self._async_execute(lambda charger: charger.async_start_charging()) + + async def async_stop_charging(self) -> None: + """Stop the charging session.""" + await self._async_execute(lambda charger: charger.async_stop_charging()) + + async def _async_execute( + self, action: Callable[[SpinEvCharger], Awaitable[None]] + ) -> None: + """Send a command over the same link a poll uses, then refresh.""" + async with self._link: + # A command queued behind teardown would otherwise reconnect after + # the entry is gone and, when held, keep the slot claimed. + if self._shutdown_requested: + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="unloading" + ) + charger = await self._async_charger() + try: + await charger.async_connect() + await action(charger) + except SpinEvCommandRejectedError as err: + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="command_rejected" + ) from err + except SpinEvError as err: + await self.async_release() + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="cannot_send", + translation_placeholders={"error": str(err)}, + ) from err + else: + self._settled_at = ( + self.hass.loop.time() + COMMAND_SETTLE_TIME.total_seconds() + ) + finally: + if not self._keep_connected: + await self.async_release() + + await self.async_request_refresh() + + @override + async def async_shutdown(self) -> None: + """Stop polling, then drop the link once whatever holds it is done.""" + await super().async_shutdown() + async with self._link: + await self.async_release() + async def async_release(self) -> None: """Drop the link so another client can reach the charger.""" charger, self._charger = self._charger, None diff --git a/homeassistant/components/spin_ble/icons.json b/homeassistant/components/spin_ble/icons.json index 7d997ada388b..fa05b0256af1 100644 --- a/homeassistant/components/spin_ble/icons.json +++ b/homeassistant/components/spin_ble/icons.json @@ -4,6 +4,11 @@ "state": { "default": "mdi:ev-station" } + }, + "switch": { + "charging": { + "default": "mdi:ev-plug-type2" + } } } } diff --git a/homeassistant/components/spin_ble/quality_scale.yaml b/homeassistant/components/spin_ble/quality_scale.yaml index c7cf6beffeb4..6697730a993e 100644 --- a/homeassistant/components/spin_ble/quality_scale.yaml +++ b/homeassistant/components/spin_ble/quality_scale.yaml @@ -32,9 +32,7 @@ rules: unique-config-entry: done # Silver - action-exceptions: - status: exempt - comment: The integration only reads from the charger. + action-exceptions: done config-entry-unloading: done docs-configuration-parameters: done docs-installation-parameters: diff --git a/homeassistant/components/spin_ble/strings.json b/homeassistant/components/spin_ble/strings.json index 199702a49648..2258e49c9303 100644 --- a/homeassistant/components/spin_ble/strings.json +++ b/homeassistant/components/spin_ble/strings.json @@ -47,14 +47,28 @@ "starting": "Starting" } } + }, + "switch": { + "charging": { + "name": "Charging" + } } }, "exceptions": { "cannot_read": { "message": "Could not read the charger: {error}" }, + "cannot_send": { + "message": "Could not send the command to the charger: {error}" + }, + "command_rejected": { + "message": "The charger refused the command. It will not start charging without a vehicle plugged in, or stop with no session in progress." + }, "device_not_found": { "message": "Could not find the charger with address {address}. {reason}" + }, + "unloading": { + "message": "The command was not sent because the integration is unloading." } }, "options": { diff --git a/homeassistant/components/spin_ble/switch.py b/homeassistant/components/spin_ble/switch.py new file mode 100644 index 000000000000..ab12ab01f891 --- /dev/null +++ b/homeassistant/components/spin_ble/switch.py @@ -0,0 +1,51 @@ +"""Switches for the Spin EV Charger integration.""" + +from typing import Any, override + +from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from .coordinator import SpinEvConfigEntry +from .entity import SpinEvEntity + +PARALLEL_UPDATES = 1 + +CHARGING_DESCRIPTION = SwitchEntityDescription( + key="charging", + translation_key="charging", +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SpinEvConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the charger switches.""" + async_add_entities([SpinEvChargingSwitch(entry.runtime_data, CHARGING_DESCRIPTION)]) + + +class SpinEvChargingSwitch(SpinEvEntity, SwitchEntity): + """Start and stop charging.""" + + @property + @override + def is_on(self) -> bool | None: + """Return True while a session is open.""" + state = self.coordinator.data.state + if state is None: + return None + # A vehicle pausing resumes without a command, so a suspended session + # stays on rather than flapping mid-charge. + return state.is_charging or state.is_suspended + + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Start charging.""" + await self.coordinator.async_start_charging() + + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Stop charging.""" + await self.coordinator.async_stop_charging() diff --git a/tests/components/spin_ble/__init__.py b/tests/components/spin_ble/__init__.py index 0e0d0c65f655..3c73dec4db05 100644 --- a/tests/components/spin_ble/__init__.py +++ b/tests/components/spin_ble/__init__.py @@ -2,6 +2,7 @@ from pytest_homeassistant.common import MockConfigEntry +from homeassistant.components.spin_ble.const import CONF_CONNECTION_MODE, ConnectionMode from homeassistant.core import HomeAssistant @@ -10,3 +11,14 @@ async def setup_integration(hass: HomeAssistant, entry: MockConfigEntry) -> None entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() + + +async def setup_persistent(hass: HomeAssistant, entry: MockConfigEntry) -> None: + """Set the integration up with the charger's Bluetooth slot held open.""" + entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + entry, + options={**entry.options, CONF_CONNECTION_MODE: ConnectionMode.PERSISTENT}, + ) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() diff --git a/tests/components/spin_ble/snapshots/test_switch.ambr b/tests/components/spin_ble/snapshots/test_switch.ambr new file mode 100644 index 000000000000..e40a0123a461 --- /dev/null +++ b/tests/components/spin_ble/snapshots/test_switch.ambr @@ -0,0 +1,51 @@ +# serializer version: 1 +# name: test_switches[switch.123456789012_charging-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.123456789012_charging', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Charging', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Charging', + 'platform': 'spin_ble', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'charging', + 'unique_id': 'AA:BB:CC:DD:EE:FF_charging', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[switch.123456789012_charging-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : '123456789012 Charging', + }), + 'context': , + 'entity_id': 'switch.123456789012_charging', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/spin_ble/test_init.py b/tests/components/spin_ble/test_init.py index cf3a85826c50..15cc99dbde1c 100644 --- a/tests/components/spin_ble/test_init.py +++ b/tests/components/spin_ble/test_init.py @@ -18,21 +18,10 @@ from homeassistant.config_entries import ConfigEntryState from homeassistant.const import EVENT_HOMEASSISTANT_STOP, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant -from . import setup_integration +from . import setup_integration, setup_persistent from .const import IDLE_STATUS, STATE_SENSOR, STATUS -async def setup_persistent(hass: HomeAssistant, entry: MockConfigEntry) -> None: - """Set the integration up with the charger's Bluetooth slot held open.""" - entry.add_to_hass(hass) - hass.config_entries.async_update_entry( - entry, - options={**entry.options, CONF_CONNECTION_MODE: ConnectionMode.PERSISTENT}, - ) - assert await hass.config_entries.async_setup(entry.entry_id) - await hass.async_block_till_done() - - @pytest.mark.usefixtures("mock_charger") async def test_setup_and_unload( hass: HomeAssistant, mock_config_entry: MockConfigEntry diff --git a/tests/components/spin_ble/test_sensor.py b/tests/components/spin_ble/test_sensor.py index e449aec15382..fb79af615080 100644 --- a/tests/components/spin_ble/test_sensor.py +++ b/tests/components/spin_ble/test_sensor.py @@ -1,13 +1,15 @@ """Snapshot tests for the Spin EV Charger sensors.""" +from collections.abc import Generator from dataclasses import replace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, patch import pytest from pytest_homeassistant.common import MockConfigEntry, snapshot_platform from spinev_ble import ChargerState from syrupy.assertion import SnapshotAssertion +from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -15,6 +17,13 @@ from . import setup_integration from .const import IDLE_STATUS, STATE_SENSOR +@pytest.fixture(autouse=True) +def platforms() -> Generator[None]: + """Set up only the sensor platform.""" + with patch("homeassistant.components.spin_ble.PLATFORMS", [Platform.SENSOR]): + yield + + @pytest.mark.usefixtures("mock_charger") async def test_sensors( hass: HomeAssistant, diff --git a/tests/components/spin_ble/test_switch.py b/tests/components/spin_ble/test_switch.py new file mode 100644 index 000000000000..f9bf0e1de12f --- /dev/null +++ b/tests/components/spin_ble/test_switch.py @@ -0,0 +1,413 @@ +"""Tests for the Spin EV Charger charging switch.""" + +import asyncio +from collections.abc import Generator +from dataclasses import replace +from datetime import timedelta +from unittest.mock import AsyncMock, patch + +from freezegun.api import FrozenDateTimeFactory +import pytest +from pytest_homeassistant.common import ( + MockConfigEntry, + async_fire_time_changed, + snapshot_platform, +) +from spinev_ble import ( + ChargerState, + ChargerStatus, + SpinEvCommandRejectedError, + SpinEvError, +) +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.spin_ble.const import ( + CHARGING_INTERVAL, + COMMAND_SETTLE_TIME, + IDLE_INTERVAL, +) +from homeassistant.components.switch import ( + DOMAIN as SWITCH_DOMAIN, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, +) +from homeassistant.const import ( + ATTR_ENTITY_ID, + STATE_OFF, + STATE_ON, + STATE_UNKNOWN, + Platform, +) +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er + +from . import setup_integration, setup_persistent +from .const import IDLE_STATUS, STATUS + +CHARGING_SWITCH = "switch.123456789012_charging" + + +@pytest.fixture(autouse=True) +def platforms() -> Generator[None]: + """Set up only the switch platform.""" + with patch("homeassistant.components.spin_ble.PLATFORMS", [Platform.SWITCH]): + yield + + +@pytest.mark.usefixtures("mock_charger") +async def test_switches( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """The switch platform registers the entities it is expected to.""" + await setup_integration(hass, mock_config_entry) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + ("state", "expected"), + [ + pytest.param(ChargerState.AVAILABLE, STATE_OFF, id="available"), + pytest.param(ChargerState.IDLE, STATE_OFF, id="idle"), + pytest.param(ChargerState.STARTING, STATE_ON, id="starting"), + pytest.param(ChargerState.CHARGING, STATE_ON, id="charging"), + # A vehicle pausing resumes without a command, so the switch stays on + # rather than flapping mid-session. + pytest.param(ChargerState.EV_SUSPENDED, STATE_ON, id="ev_suspended"), + pytest.param(ChargerState.EVSE_SUSPENDED, STATE_ON, id="evse_suspended"), + pytest.param(ChargerState.FINISHING, STATE_OFF, id="finishing"), + # The charger still answers with a state the library does not know, so + # the switch is unknown rather than unavailable. + pytest.param(None, STATE_UNKNOWN, id="unrecognised"), + ], +) +async def test_the_switch_follows_the_session( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: AsyncMock, + state: ChargerState | None, + expected: str, +) -> None: + """The switch is on for a whole session, including while it is paused.""" + mock_charger.async_get_status.return_value = replace(IDLE_STATUS, state=state) + await setup_integration(hass, mock_config_entry) + + assert hass.states.get(CHARGING_SWITCH).state == expected + + +@pytest.mark.parametrize( + ("service", "before", "after", "command", "expected"), + [ + pytest.param( + SERVICE_TURN_ON, + IDLE_STATUS, + replace(IDLE_STATUS, state=ChargerState.STARTING), + "async_start_charging", + STATE_ON, + id="turn_on", + ), + pytest.param( + SERVICE_TURN_OFF, + STATUS, + IDLE_STATUS, + "async_stop_charging", + STATE_OFF, + id="turn_off", + ), + ], +) +async def test_commands_reach_the_charger( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: AsyncMock, + freezer: FrozenDateTimeFactory, + service: str, + before: ChargerStatus, + after: ChargerStatus, + command: str, + expected: str, +) -> None: + """A command is sent, the link handed back, and the charger re-read.""" + mock_charger.async_get_status.return_value = before + await setup_integration(hass, mock_config_entry) + mock_charger.async_get_status.reset_mock() + mock_charger.async_disconnect.reset_mock() + + await hass.services.async_call( + SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: CHARGING_SWITCH}, blocking=True + ) + + getattr(mock_charger, command).assert_awaited_once() + mock_charger.async_disconnect.assert_awaited() + # The charger reports the old state for a moment after acknowledging. + mock_charger.async_get_status.assert_not_awaited() + + mock_charger.async_get_status.return_value = after + freezer.tick(COMMAND_SETTLE_TIME) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + mock_charger.async_get_status.assert_awaited_once() + assert hass.states.get(CHARGING_SWITCH).state == expected + + +async def test_a_poll_right_after_a_command_waits_for_the_charger( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """A poll due just after a command reads only once the charger has settled.""" + mock_charger.async_get_status.return_value = IDLE_STATUS + await setup_integration(hass, mock_config_entry) + freezer.tick(IDLE_INTERVAL - timedelta(seconds=1)) + async_fire_time_changed(hass) + await hass.services.async_call( + SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: CHARGING_SWITCH}, blocking=True + ) + mock_charger.async_get_status.reset_mock() + + # The poll falls due inside the settle time and cancels the pending refresh. + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + mock_charger.async_get_status.assert_not_awaited() + + mock_charger.async_get_status.return_value = replace( + IDLE_STATUS, state=ChargerState.STARTING + ) + freezer.tick(COMMAND_SETTLE_TIME) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_charger.async_get_status.assert_awaited_once() + assert hass.states.get(CHARGING_SWITCH).state == STATE_ON + + +async def test_a_persistent_link_is_held_through_a_command( + hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_charger: AsyncMock +) -> None: + """A command does not give up a slot the user chose to keep.""" + await setup_persistent(hass, mock_config_entry) + + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + + mock_charger.async_stop_charging.assert_awaited_once() + mock_charger.async_disconnect.assert_not_awaited() + + +@pytest.mark.parametrize( + ("error", "translation_key", "released"), + [ + # The charger answered, so a held link is still good. + pytest.param( + SpinEvCommandRejectedError("refused"), + "command_rejected", + False, + id="rejected", + ), + pytest.param(SpinEvError("no reply"), "cannot_send", True, id="no_reply"), + ], +) +async def test_a_failed_command_raises( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: AsyncMock, + error: SpinEvError, + translation_key: str, + released: bool, +) -> None: + """A command the charger refuses or never answers surfaces to the user.""" + mock_charger.async_get_status.return_value = IDLE_STATUS + mock_charger.async_start_charging.side_effect = error + await setup_persistent(hass, mock_config_entry) + + with pytest.raises(HomeAssistantError) as err: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + + assert err.value.translation_key == translation_key + assert mock_charger.async_disconnect.await_count == int(released) + + +async def test_teardown_waits_for_a_command_in_flight( + hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_charger: AsyncMock +) -> None: + """Unloading hands the link back only once a running command is done.""" + await setup_persistent(hass, mock_config_entry) + started = asyncio.Event() + finish = asyncio.Event() + order: list[str] = [] + + async def start_charging() -> None: + started.set() + await finish.wait() + order.append("start") + + mock_charger.async_start_charging.side_effect = start_charging + mock_charger.async_disconnect.side_effect = lambda: order.append("disconnect") + + command = hass.async_create_task( + hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + ) + await started.wait() + # Unload callbacks run newest first and the shutdown starts eagerly, so a + # shutdown that does not wait disconnects before the command resumes. + mock_config_entry.async_on_unload(finish.set) + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await command + + assert order == ["start", "disconnect"] + + +async def test_a_command_queued_behind_teardown_is_refused( + hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_charger: AsyncMock +) -> None: + """A command that only gets the link after unloading never reconnects.""" + await setup_persistent(hass, mock_config_entry) + started = asyncio.Event() + finish = asyncio.Event() + + async def start_charging() -> None: + started.set() + await finish.wait() + + mock_charger.async_start_charging.side_effect = start_charging + + running = hass.async_create_task( + hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + ) + await started.wait() + mock_charger.async_connect.reset_mock() + queued = hass.async_create_task( + hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + ) + mock_config_entry.async_on_unload(finish.set) + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await running + + with pytest.raises(HomeAssistantError) as err: + await queued + + assert err.value.translation_key == "unloading" + mock_charger.async_connect.assert_not_awaited() + mock_charger.async_stop_charging.assert_not_awaited() + + +async def test_a_poll_waits_for_a_command_holding_the_link( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """A poll arriving mid-command neither reads nor drops the link until it ends.""" + await setup_integration(hass, mock_config_entry) + started = asyncio.Event() + finish = asyncio.Event() + + async def start_charging() -> None: + started.set() + await finish.wait() + + mock_charger.async_start_charging.side_effect = start_charging + mock_charger.async_get_status.reset_mock() + mock_charger.async_disconnect.reset_mock() + + command = hass.async_create_task( + hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + ) + await started.wait() + freezer.tick(CHARGING_INTERVAL) + # The poll starts eagerly, so one that does not wait is already through. + async_fire_time_changed(hass) + # Always lets the command finish, so a missing lock fails the test rather + # than hanging it. + try: + mock_charger.async_get_status.assert_not_awaited() + mock_charger.async_disconnect.assert_not_awaited() + finally: + finish.set() + await command + freezer.tick(COMMAND_SETTLE_TIME) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_charger.async_get_status.assert_awaited() + + +async def test_a_command_waits_for_a_poll_holding_the_link( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """A command arriving mid-poll neither sends nor drops the link until it ends.""" + await setup_integration(hass, mock_config_entry) + started = asyncio.Event() + finish = asyncio.Event() + + async def get_status() -> ChargerStatus: + started.set() + await finish.wait() + return IDLE_STATUS + + mock_charger.async_get_status.side_effect = get_status + mock_charger.async_disconnect.reset_mock() + + freezer.tick(CHARGING_INTERVAL) + async_fire_time_changed(hass) + await started.wait() + # The command starts eagerly, so one that does not wait is already sent. + command = hass.async_create_task( + hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: CHARGING_SWITCH}, + blocking=True, + ) + ) + # Always lets the poll finish, so a missing lock fails the test rather than + # hanging it. + try: + mock_charger.async_start_charging.assert_not_awaited() + mock_charger.async_disconnect.assert_not_awaited() + finally: + finish.set() + await command + await hass.async_block_till_done() + + mock_charger.async_start_charging.assert_awaited_once()