diff --git a/python_chargepoint/session.py b/python_chargepoint/session.py index bdcd885..4c201fe 100644 --- a/python_chargepoint/session.py +++ b/python_chargepoint/session.py @@ -7,7 +7,7 @@ from datetime import datetime, timezone from typing import TYPE_CHECKING, List, Optional, Union -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, Field, ValidationError, field_validator if TYPE_CHECKING: from .client import ChargePoint @@ -16,6 +16,9 @@ from .exceptions import APIError, CommunicationError from .types import ChargingSessionUpdate, PowerUtility, VehicleInfo +_START_SESSION_POLL_INTERVAL = 3 +_START_SESSION_LOOKUP_TIMEOUT = 15 + async def _send_command( client: ChargePoint, @@ -282,14 +285,37 @@ async def stop(self) -> None: @classmethod async def start(cls, device_id: int, client: ChargePoint) -> ChargingSession: await _send_command(client=client, action="start", device_id=device_id) - # So, after wayyy too much trial and error, I noticed that the "sessionId" - # returned by the start session API is significantly higher than normal - # session IDs... I have no clue what it means, so we are just going to - # get the correct session ID from the status API. - status = await client.get_user_charging_status() - if status is None: - raise APIError("No active charging session found after start command.") - session = cls(session_id=status.session_id) - session._client = client - await session.async_refresh() - return session + # The start acknowledgement can arrive before the driver session. + # Only poll for the session here, since another Start can have effects. + try: + return await asyncio.wait_for( + cls._find_started_session(device_id, client), + timeout=_START_SESSION_LOOKUP_TIMEOUT, + ) + except asyncio.TimeoutError as exc: + raise APIError( + "Start was acknowledged, but no active charging session could be " + "confirmed for the requested charger." + ) from exc + + @classmethod + async def _find_started_session( + cls, device_id: int, client: ChargePoint + ) -> ChargingSession: + while True: + status = await client.get_user_charging_status() + if status is not None and status.session_id > 0: + session = cls(session_id=status.session_id) + session._client = client + try: + await session.async_refresh() + except CommunicationError as exc: + if exc.response.status not in (200, 404): + raise + except ValidationError: + # A just-created session can have incomplete details. + pass + else: + if session.device_id == device_id: + return session + await asyncio.sleep(_START_SESSION_POLL_INTERVAL) diff --git a/tests/test_session.py b/tests/test_session.py index 687a746..de39597 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -4,10 +4,10 @@ import pytest -from python_chargepoint import ChargePoint +from python_chargepoint import ChargePoint, session as session_module +from python_chargepoint.exceptions import APIError, CommunicationError from python_chargepoint.global_config import GlobalConfiguration from python_chargepoint.session import ChargingSession, _send_command -from python_chargepoint.exceptions import CommunicationError def _add_start_function_responses( @@ -127,6 +127,70 @@ async def test_start_session( assert "Successfully confirmed start command." in caplog.text +@pytest.mark.parametrize("pending", ["missing", "wrong_device", "missing_details"]) +async def test_start_polls_until_requested_session_is_visible( + aioresponses, + authenticated_client, + user_charging_status_json, + charging_status_json, + monkeypatch, + pending, +): + monkeypatch.setattr(session_module, "_START_SESSION_POLL_INTERVAL", 0) + config = authenticated_client.global_config + _add_start_function_responses(aioresponses, config) + status_url = config.endpoints.mapcache_endpoint / "v2" + session_url = ( + config.endpoints.internal_api_gateway_endpoint / "driver-bff/v1/sessions" + ) + first_status = {} + if pending == "wrong_device": + first_status = { + "charging": {**user_charging_status_json["charging"], "sessionId": 2} + } + aioresponses.post( + session_url / "2", + payload={"charging_status": {**charging_status_json, "device_id": 2}}, + ) + elif pending == "missing_details": + first_status = user_charging_status_json + aioresponses.post( + session_url / "1", + payload={"charging_status": {"error_message": "Session data pending"}}, + ) + aioresponses.post(status_url, payload={"user_status": first_status}) + aioresponses.post(status_url, payload={"user_status": user_charging_status_json}) + aioresponses.post( + session_url / "1", payload={"charging_status": charging_status_json} + ) + + session = await authenticated_client.start_charging_session(device_id=1) + assert (session.session_id, session.device_id) == (1, 1) + start_url = config.endpoints.accounts_endpoint / "v1/driver/station/startsession" + starts = aioresponses.requests[("POST", start_url)] + assert [request.kwargs["json"] for request in starts] == [{"deviceId": 1}] + assert len(aioresponses.requests[("POST", status_url)]) == 2 + + +async def test_acknowledged_start_with_no_session_times_out_without_resending( + aioresponses, authenticated_client, monkeypatch +): + monkeypatch.setattr(session_module, "_START_SESSION_POLL_INTERVAL", 0.005) + monkeypatch.setattr(session_module, "_START_SESSION_LOOKUP_TIMEOUT", 0.05) + config = authenticated_client.global_config + _add_start_function_responses(aioresponses, config) + status_url = config.endpoints.mapcache_endpoint / "v2" + aioresponses.post(status_url, payload={"user_status": {}}, repeat=True) + + with pytest.raises(APIError, match="Start was acknowledged"): + await authenticated_client.start_charging_session(device_id=1) + + start_url = config.endpoints.accounts_endpoint / "v1/driver/station/startsession" + starts = aioresponses.requests[("POST", start_url)] + assert [request.kwargs["json"] for request in starts] == [{"deviceId": 1}] + assert ("POST", status_url) in aioresponses.requests + + async def test_get_charging_session_error( aioresponses, authenticated_client: ChargePoint ):