diff --git a/custom_components/zaptec/button.py b/custom_components/zaptec/button.py index 4a65fdd..fc52d19 100644 --- a/custom_components/zaptec/button.py +++ b/custom_components/zaptec/button.py @@ -8,10 +8,10 @@ from homeassistant import const from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.core import HomeAssistant -from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddEntitiesCallback from .entity import ZaptecBaseEntity +from .errors import api_call_error from .manager import ZaptecConfigEntry, ZaptecEntityDescription from .zaptec import Charger @@ -37,7 +37,7 @@ async def async_press(self) -> None: try: await self.zaptec_obj.command(self.key) except Exception as exc: - raise HomeAssistantError(f"Running command '{self.key}' failed") from exc + raise api_call_error(exc, f"Running command '{self.key}'") from exc await self.trigger_poll() diff --git a/custom_components/zaptec/errors.py b/custom_components/zaptec/errors.py new file mode 100644 index 0000000..2badbc2 --- /dev/null +++ b/custom_components/zaptec/errors.py @@ -0,0 +1,59 @@ +"""Translated Home Assistant errors for failed Zaptec API calls.""" + +from __future__ import annotations + +from homeassistant.exceptions import HomeAssistantError + +from .const import DOMAIN +from .zaptec.exceptions import RequestError +from .zaptec.zconst import ZCONST + +# Zaptec error codes (see `ErrorCodes` in the API constants) that need wording +# of their own because the API sends no Details along with them. +CODE_DEVICE_COMMAND_REJECTED = 528 +CODE_OPERATION_FAILED_DUE_TO_CHARGER_STATE = 538 + +# Details phrases Zaptec sends when the installation's charging mode blocks an +# update: "Automatic" (managed by Zaptec Sense) and "Scheduled" in the Zaptec +# app. Matched on the phrase so that any other reason falls through and is +# shown verbatim rather than being attributed to the wrong mode. +APM_IN_USE = "when using APM" +SCHEDULED_IN_USE = "scheduled power management" + + +def api_call_error(exc: Exception, action: str) -> HomeAssistantError: + """Return a translated error explaining why a Zaptec API call failed. + + Zaptec reports the reason for a rejected call as an error code in the body + of an HTTP 500, sometimes with human-readable Details. `action` describes + what was attempted, e.g. "Set current limit to 6.0". + """ + code = exc.zaptec_code if isinstance(exc, RequestError) else None + details = exc.zaptec_details if isinstance(exc, RequestError) else None + if not isinstance(details, str): + details = None # Details comes straight from the API, so don't trust its type + + placeholders = {"action": action} + if code == CODE_DEVICE_COMMAND_REJECTED: + key = "api_error_command_rejected" + elif code == CODE_OPERATION_FAILED_DUE_TO_CHARGER_STATE: + key = "api_error_charger_state" + elif details and APM_IN_USE in details: + # Zaptec calls it APM in the API, but users know it as Zaptec Sense. + key = "api_error_apm" + elif details and SCHEDULED_IN_USE in details: + key = "api_error_scheduled" + elif details: + key = "api_error_details" + placeholders["details"] = details + elif code is not None: + key = "api_error_code" + placeholders["reason"] = ZCONST.type_error_code(code) + else: + key = "api_error" + + return HomeAssistantError( + translation_domain=DOMAIN, + translation_key=key, + translation_placeholders=placeholders, + ) diff --git a/custom_components/zaptec/number.py b/custom_components/zaptec/number.py index 92b751a..82339ce 100644 --- a/custom_components/zaptec/number.py +++ b/custom_components/zaptec/number.py @@ -17,6 +17,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback from .entity import ZaptecBaseEntity +from .errors import api_call_error from .manager import ZaptecConfigEntry, ZaptecEntityDescription from .zaptec import Charger, Installation, ZaptecBase @@ -66,7 +67,7 @@ async def async_set_native_value(self, value: float) -> None: try: await self.zaptec_obj.set_limit_current(availableCurrent=value) except Exception as exc: - raise HomeAssistantError(f"Set current limit to {value} failed") from exc + raise api_call_error(exc, f"Set current limit to {value}") from exc await self.trigger_poll() @@ -82,8 +83,8 @@ async def async_set_native_value(self, value: float) -> None: try: await self.zaptec_obj.set_three_to_one_phase_switch_current(value) except Exception as exc: - raise HomeAssistantError( - f"Setting three to one phase switch current to {value} failed" + raise api_call_error( + exc, f"Setting three to one phase switch current to {value}" ) from exc await self.trigger_poll() @@ -109,8 +110,8 @@ async def async_set_native_value(self, value: float) -> None: try: await self.zaptec_obj.set_settings({self.entity_description.setting: value}) except Exception as exc: - raise HomeAssistantError( - f"Setting {self.entity_description.setting} to {value} failed" + raise api_call_error( + exc, f"Setting {self.entity_description.setting} to {value}" ) from exc await self.trigger_poll() @@ -135,7 +136,7 @@ async def async_set_native_value(self, value: float) -> None: try: await self.zaptec_obj.set_hmi_brightness(value / 100) except Exception as exc: - raise HomeAssistantError(f"Set HmiBrightness to {value} failed") from exc + raise api_call_error(exc, f"Set HmiBrightness to {value}") from exc await self.trigger_poll() diff --git a/custom_components/zaptec/services.py b/custom_components/zaptec/services.py index ac406ca..6186c7a 100644 --- a/custom_components/zaptec/services.py +++ b/custom_components/zaptec/services.py @@ -13,6 +13,7 @@ import voluptuous as vol from .const import DOMAIN +from .errors import api_call_error from .zaptec import Charger, Installation if TYPE_CHECKING: @@ -202,7 +203,7 @@ async def service_handle_stop_charging(service_call: ServiceCall) -> None: try: await obj.command("stop_charging_final") except Exception as exc: - raise HomeAssistantError(f"Command 'stop_charging_final' failed: {exc}") from exc + raise api_call_error(exc, "Command 'stop_charging_final'") from exc await coordinator.trigger_poll() async def service_handle_resume_charging(service_call: ServiceCall) -> None: @@ -216,7 +217,7 @@ async def service_handle_resume_charging(service_call: ServiceCall) -> None: try: await obj.command("resume_charging") except Exception as exc: - raise HomeAssistantError(f"Command 'resume_charging' failed: {exc}") from exc + raise api_call_error(exc, "Command 'resume_charging'") from exc await coordinator.trigger_poll() async def service_handle_authorize_charging(service_call: ServiceCall) -> None: @@ -230,7 +231,7 @@ async def service_handle_authorize_charging(service_call: ServiceCall) -> None: try: await obj.authorize_charge() except Exception as exc: - raise HomeAssistantError(f"Command 'authorize_charge' failed: {exc}") from exc + raise api_call_error(exc, "Command 'authorize_charge'") from exc await coordinator.trigger_poll() async def service_handle_deauthorize_charging(service_call: ServiceCall) -> None: @@ -244,7 +245,7 @@ async def service_handle_deauthorize_charging(service_call: ServiceCall) -> None try: await obj.command("deauthorize_and_stop") except Exception as exc: - raise HomeAssistantError(f"Command 'deauthorize_and_stop' failed: {exc}") from exc + raise api_call_error(exc, "Command 'deauthorize_and_stop'") from exc await coordinator.trigger_poll() async def service_handle_restart_charger(service_call: ServiceCall) -> None: @@ -258,7 +259,7 @@ async def service_handle_restart_charger(service_call: ServiceCall) -> None: try: await obj.command("restart_charger") except Exception as exc: - raise HomeAssistantError(f"Command 'restart_charger' failed: {exc}") from exc + raise api_call_error(exc, "Command 'restart_charger'") from exc await coordinator.trigger_poll() async def service_handle_upgrade_firmware(service_call: ServiceCall) -> None: @@ -272,7 +273,7 @@ async def service_handle_upgrade_firmware(service_call: ServiceCall) -> None: try: await obj.command("upgrade_firmware") except Exception as exc: - raise HomeAssistantError(f"Command 'upgrade_firmware' failed: {exc}") from exc + raise api_call_error(exc, "Command 'upgrade_firmware'") from exc await coordinator.trigger_poll() async def service_handle_limit_current(service_call: ServiceCall) -> None: @@ -298,7 +299,7 @@ async def service_handle_limit_current(service_call: ServiceCall) -> None: try: await obj.set_limit_current(**limit_args) except Exception as exc: - raise HomeAssistantError(f"Limit current failed: {exc}") from exc + raise api_call_error(exc, "Limit current") from exc await coordinator.trigger_poll() async def service_handle_send_command(service_call: ServiceCall) -> None: @@ -311,7 +312,7 @@ async def service_handle_send_command(service_call: ServiceCall) -> None: try: await obj.command(command) except Exception as exc: - raise HomeAssistantError(f"Command '{command}' failed: {exc}") from exc + raise api_call_error(exc, f"Command '{command}'") from exc await coordinator.trigger_poll() # LIST OF SERVICES diff --git a/custom_components/zaptec/switch.py b/custom_components/zaptec/switch.py index 9d2dd19..9f7ffc2 100644 --- a/custom_components/zaptec/switch.py +++ b/custom_components/zaptec/switch.py @@ -13,10 +13,10 @@ ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant, callback -from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddEntitiesCallback from .entity import ZaptecBaseEntity +from .errors import api_call_error from .manager import ZaptecConfigEntry, ZaptecEntityDescription from .zaptec import Charger @@ -67,7 +67,7 @@ async def async_turn_on(self, **kwargs: Any) -> None: # pylint: disable=unused- try: await self.zaptec_obj.command("resume_charging") except Exception as exc: - raise HomeAssistantError("Resuming charging failed") from exc + raise api_call_error(exc, "Resuming charging") from exc await self.trigger_poll() @@ -82,7 +82,7 @@ async def async_turn_off(self, **kwargs: Any) -> None: # pylint: disable=unused try: await self.zaptec_obj.command("stop_charging_final") except Exception as exc: - raise HomeAssistantError("Stop/pausing charging failed") from exc + raise api_call_error(exc, "Stop/pausing charging") from exc await self.trigger_poll() @@ -101,7 +101,7 @@ async def async_turn_off(self, **kwargs: Any) -> None: try: await self.zaptec_obj.set_permanent_cable_lock(False) except Exception as exc: - raise HomeAssistantError("Removing permanent cable lock failed") from exc + raise api_call_error(exc, "Removing permanent cable lock") from exc await self.trigger_poll() @@ -116,7 +116,7 @@ async def async_turn_on(self, **kwargs: Any) -> None: try: await self.zaptec_obj.set_permanent_cable_lock(True) except Exception as exc: - raise HomeAssistantError("Setting permanent cable lock failed") from exc + raise api_call_error(exc, "Setting permanent cable lock") from exc await self.trigger_poll() diff --git a/custom_components/zaptec/translations/de.json b/custom_components/zaptec/translations/de.json index d9cfd3e..c742528 100644 --- a/custom_components/zaptec/translations/de.json +++ b/custom_components/zaptec/translations/de.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} fehlgeschlagen." + }, + "api_error_apm": { + "message": "{action} fehlgeschlagen: Die angeforderte Einstellung kann nicht geändert werden, solange sich die Installation im Modus „Automatisches Laden“ befindet (Zaptec Sense oder eine ähnliche Laststeuerung)." + }, + "api_error_charger_state": { + "message": "{action} fehlgeschlagen: Der aktuelle Zustand der Ladestation lässt diesen Vorgang nicht zu." + }, + "api_error_code": { + "message": "{action} fehlgeschlagen: Zaptec meldete den Fehler {reason}." + }, + "api_error_command_rejected": { + "message": "{action} fehlgeschlagen: Die Ladestation hat den Befehl abgelehnt. Möglicherweise wurde er dennoch ausgeführt." + }, + "api_error_details": { + "message": "{action} fehlgeschlagen: {details}" + }, + "api_error_scheduled": { + "message": "{action} fehlgeschlagen: Die angeforderte Einstellung kann nicht geändert werden, solange sich die Installation im Modus „Geplantes Laden“ befindet." + }, "no_devices_found": { "message": "Keine Zaptec-Installationen oder -Ladegeräte für das Konto {username} gefunden. Prüfe über Neu konfigurieren, ob dies das richtige Zaptec-Konto ist und ob die ausgewählten Ladegeräte noch existieren." } diff --git a/custom_components/zaptec/translations/en.json b/custom_components/zaptec/translations/en.json index fde733c..3274e69 100644 --- a/custom_components/zaptec/translations/en.json +++ b/custom_components/zaptec/translations/en.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} failed." + }, + "api_error_apm": { + "message": "{action} failed: cannot change the requested setting while the installation is in \"Automatic charging\" mode (Zaptec Sense or similar power management)." + }, + "api_error_charger_state": { + "message": "{action} failed: the charger's current state does not allow this operation." + }, + "api_error_code": { + "message": "{action} failed: Zaptec reported the error {reason}." + }, + "api_error_command_rejected": { + "message": "{action} failed: the charger rejected the command. It may still have been carried out." + }, + "api_error_details": { + "message": "{action} failed: {details}" + }, + "api_error_scheduled": { + "message": "{action} failed: cannot change the requested setting while the installation is in \"Scheduled charging\" mode." + }, "no_devices_found": { "message": "No Zaptec installations or chargers found for account {username}. Check that this is the right Zaptec account and that the selected chargers still exist, using Reconfigure." } diff --git a/custom_components/zaptec/translations/fr.json b/custom_components/zaptec/translations/fr.json index 0d1ed26..708c173 100644 --- a/custom_components/zaptec/translations/fr.json +++ b/custom_components/zaptec/translations/fr.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} a échoué." + }, + "api_error_apm": { + "message": "{action} a échoué : impossible de modifier le réglage demandé tant que l'installation est en mode « Recharge automatique » (Zaptec Sense ou une gestion d'énergie similaire)." + }, + "api_error_charger_state": { + "message": "{action} a échoué : l'état actuel de la borne n'autorise pas cette opération." + }, + "api_error_code": { + "message": "{action} a échoué : Zaptec a signalé l'erreur {reason}." + }, + "api_error_command_rejected": { + "message": "{action} a échoué : la borne a refusé la commande. Il est possible qu'elle ait tout de même été exécutée." + }, + "api_error_details": { + "message": "{action} a échoué : {details}" + }, + "api_error_scheduled": { + "message": "{action} a échoué : impossible de modifier le réglage demandé tant que l'installation est en mode « Recharge programmée »." + }, "no_devices_found": { "message": "Aucune installation ni borne Zaptec trouvée pour le compte {username}. Vérifiez via Reconfigurer qu'il s'agit du bon compte Zaptec et que les bornes sélectionnées existent toujours." } diff --git a/custom_components/zaptec/translations/nb.json b/custom_components/zaptec/translations/nb.json index ad9c2c8..af1310a 100644 --- a/custom_components/zaptec/translations/nb.json +++ b/custom_components/zaptec/translations/nb.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} mislyktes." + }, + "api_error_apm": { + "message": "{action} mislyktes: den forespurte innstillingen kan ikke endres mens installasjonen er i modusen «Automatisk lading» (Zaptec Sense eller lignende effektstyring)." + }, + "api_error_charger_state": { + "message": "{action} mislyktes: laderens nåværende tilstand tillater ikke denne handlingen." + }, + "api_error_code": { + "message": "{action} mislyktes: Zaptec rapporterte feilen {reason}." + }, + "api_error_command_rejected": { + "message": "{action} mislyktes: laderen avviste kommandoen. Den kan likevel ha blitt utført." + }, + "api_error_details": { + "message": "{action} mislyktes: {details}" + }, + "api_error_scheduled": { + "message": "{action} mislyktes: den forespurte innstillingen kan ikke endres mens installasjonen er i modusen «Planlagt lading»." + }, "no_devices_found": { "message": "Fant ingen Zaptec-installasjoner eller -ladere for kontoen {username}. Bruk Rekonfigurer for å sjekke at dette er riktig Zaptec-konto og at de valgte laderne fortsatt finnes." } diff --git a/custom_components/zaptec/translations/nl.json b/custom_components/zaptec/translations/nl.json index 48ddf79..df6cf66 100644 --- a/custom_components/zaptec/translations/nl.json +++ b/custom_components/zaptec/translations/nl.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} is mislukt." + }, + "api_error_apm": { + "message": "{action} is mislukt: de gevraagde instelling kan niet worden gewijzigd zolang de installatie in de modus \"Automatisch laden\" staat (Zaptec Sense of vergelijkbaar energiebeheer)." + }, + "api_error_charger_state": { + "message": "{action} is mislukt: de huidige status van het laadstation staat deze bewerking niet toe." + }, + "api_error_code": { + "message": "{action} is mislukt: Zaptec meldde de fout {reason}." + }, + "api_error_command_rejected": { + "message": "{action} is mislukt: het laadstation heeft de opdracht geweigerd. Mogelijk is deze toch uitgevoerd." + }, + "api_error_details": { + "message": "{action} is mislukt: {details}" + }, + "api_error_scheduled": { + "message": "{action} is mislukt: de gevraagde instelling kan niet worden gewijzigd zolang de installatie in de modus \"Gepland laden\" staat." + }, "no_devices_found": { "message": "Geen Zaptec-installaties of -laders gevonden voor account {username}. Controleer via Opnieuw configureren of dit het juiste Zaptec-account is en of de geselecteerde laders nog bestaan." } diff --git a/custom_components/zaptec/translations/nn.json b/custom_components/zaptec/translations/nn.json index fb4a2e3..3dbe24d 100644 --- a/custom_components/zaptec/translations/nn.json +++ b/custom_components/zaptec/translations/nn.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} mislukkast." + }, + "api_error_apm": { + "message": "{action} mislukkast: den førespurde innstillinga kan ikkje endrast medan installasjonen er i modusen «Automatisk lading» (Zaptec Sense eller liknande effektstyring)." + }, + "api_error_charger_state": { + "message": "{action} mislukkast: den noverande tilstanden til ladaren tillèt ikkje denne handlinga." + }, + "api_error_code": { + "message": "{action} mislukkast: Zaptec rapporterte feilen {reason}." + }, + "api_error_command_rejected": { + "message": "{action} mislukkast: ladaren avviste kommandoen. Han kan likevel ha blitt utført." + }, + "api_error_details": { + "message": "{action} mislukkast: {details}" + }, + "api_error_scheduled": { + "message": "{action} mislukkast: den førespurde innstillinga kan ikkje endrast medan installasjonen er i modusen «Planlagd lading»." + }, "no_devices_found": { "message": "Fann ingen Zaptec-installasjonar eller -ladarar for kontoen {username}. Bruk Rekonfigurer for å sjekke at dette er rett Zaptec-konto og at dei valde ladarane framleis finst." } diff --git a/custom_components/zaptec/translations/pl.json b/custom_components/zaptec/translations/pl.json index c501ba0..cc90949 100644 --- a/custom_components/zaptec/translations/pl.json +++ b/custom_components/zaptec/translations/pl.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} nie powiodło się." + }, + "api_error_apm": { + "message": "{action} nie powiodło się: nie można zmienić żądanego ustawienia, gdy instalacja działa w trybie „Ładowanie automatyczne” (Zaptec Sense lub podobnego zarządzania mocą)." + }, + "api_error_charger_state": { + "message": "{action} nie powiodło się: bieżący stan ładowarki nie pozwala na tę operację." + }, + "api_error_code": { + "message": "{action} nie powiodło się: Zaptec zgłosił błąd {reason}." + }, + "api_error_command_rejected": { + "message": "{action} nie powiodło się: ładowarka odrzuciła polecenie. Mogło ono jednak zostać wykonane." + }, + "api_error_details": { + "message": "{action} nie powiodło się: {details}" + }, + "api_error_scheduled": { + "message": "{action} nie powiodło się: nie można zmienić żądanego ustawienia, gdy instalacja działa w trybie „Ładowanie zaplanowane”." + }, "no_devices_found": { "message": "Nie znaleziono instalacji ani ładowarek Zaptec dla konta {username}. Sprawdź za pomocą Zmień konfigurację, czy to właściwe konto Zaptec i czy wybrane ładowarki nadal istnieją." } diff --git a/custom_components/zaptec/translations/sv.json b/custom_components/zaptec/translations/sv.json index 200f66a..626308b 100644 --- a/custom_components/zaptec/translations/sv.json +++ b/custom_components/zaptec/translations/sv.json @@ -207,6 +207,27 @@ } }, "exceptions": { + "api_error": { + "message": "{action} misslyckades." + }, + "api_error_apm": { + "message": "{action} misslyckades: den begärda inställningen kan inte ändras medan installationen är i läget ”Automatisk laddning” (Zaptec Sense eller liknande effektstyrning)." + }, + "api_error_charger_state": { + "message": "{action} misslyckades: laddarens nuvarande tillstånd tillåter inte den här åtgärden." + }, + "api_error_code": { + "message": "{action} misslyckades: Zaptec rapporterade felet {reason}." + }, + "api_error_command_rejected": { + "message": "{action} misslyckades: laddaren avvisade kommandot. Det kan ändå ha utförts." + }, + "api_error_details": { + "message": "{action} misslyckades: {details}" + }, + "api_error_scheduled": { + "message": "{action} misslyckades: den begärda inställningen kan inte ändras medan installationen är i läget ”Schemalagd laddning”." + }, "no_devices_found": { "message": "Inga Zaptec-installationer eller laddare hittades för kontot {username}. Kontrollera via Konfigurera om att detta är rätt Zaptec-konto och att de valda laddarna fortfarande finns." } diff --git a/custom_components/zaptec/update.py b/custom_components/zaptec/update.py index a0a141f..9e6d2fc 100644 --- a/custom_components/zaptec/update.py +++ b/custom_components/zaptec/update.py @@ -13,10 +13,10 @@ UpdateEntityDescription, ) from homeassistant.core import HomeAssistant, callback -from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddEntitiesCallback from .entity import ZaptecBaseEntity +from .errors import api_call_error from .manager import ZaptecConfigEntry, ZaptecEntityDescription from .zaptec import Charger @@ -50,7 +50,7 @@ async def async_install(self, version: str | None, backup: bool, **kwargs: Any) try: await self.zaptec_obj.command("upgrade_firmware") except Exception as exc: - raise HomeAssistantError("Sending update firmware command failed") from exc + raise api_call_error(exc, "Sending update firmware command") from exc await self.trigger_poll() diff --git a/custom_components/zaptec/zaptec/api.py b/custom_components/zaptec/zaptec/api.py index 9f853f4..ca20c2c 100644 --- a/custom_components/zaptec/zaptec/api.py +++ b/custom_components/zaptec/zaptec/api.py @@ -1255,11 +1255,18 @@ async def request( # GET request gets logged and then retried, while POST and # PUT requests are not retried. if response.status == HTTPStatus.INTERNAL_SERVER_ERROR: + # Zaptec provides the reason for the failure in the response + # body on 500, as an error code with optional details. + text = await response.text(errors="replace") + try: + payload = json.loads(text) + except json.JSONDecodeError: + payload = None + if isinstance(payload, dict): + error.zaptec_code = payload.get("Code") + error.zaptec_details = payload.get("Details") log_exc(error) # Log the error if DEBUG_API_CALLS: - # There are additional details in the response that Zaptec - # provides on 500. Let's log it. - text = await response.text() if len(text) > MAX_DEBUG_TEXT_LEN_ON_500: text = text[:MAX_DEBUG_TEXT_LEN_ON_500] + "..." _LOGGER.debug(" PAYLOAD %r", text) diff --git a/custom_components/zaptec/zaptec/exceptions.py b/custom_components/zaptec/zaptec/exceptions.py index 75f6a96..c1719b1 100644 --- a/custom_components/zaptec/zaptec/exceptions.py +++ b/custom_components/zaptec/zaptec/exceptions.py @@ -12,10 +12,23 @@ class AuthenticationError(ZaptecApiError): class RequestError(ZaptecApiError): """Failed to get the results from the API.""" - def __init__(self, message: str, error_code: int) -> None: - """Initialize the RequestError.""" + def __init__( + self, + message: str, + error_code: int, + zaptec_code: int | None = None, + zaptec_details: str | None = None, + ) -> None: + """Initialize the RequestError. + + `error_code` is the HTTP status. `zaptec_code` is Zaptec's own error + code from the response body, which is only sent on HTTP 500, and + `zaptec_details` its optional human-readable explanation. + """ super().__init__(message) self.error_code = error_code + self.zaptec_code = zaptec_code + self.zaptec_details = zaptec_details class RequestConnectionError(ZaptecApiError): diff --git a/custom_components/zaptec/zaptec/zconst.py b/custom_components/zaptec/zaptec/zconst.py index dc8e79a..3940f5e 100644 --- a/custom_components/zaptec/zaptec/zconst.py +++ b/custom_components/zaptec/zaptec/zconst.py @@ -167,6 +167,11 @@ def type_device_type(self, val: int) -> str: modes = {str(v): k for k, v in self.get("DeviceTypes", {}).items()} return modes.get(str(val), str(val)) + def type_error_code(self, val: int) -> str: + """Convert the error code to a string.""" + codes = {str(v): k for k, v in self.get("ErrorCodes", {}).items()} + return codes.get(str(val), str(val)) + def type_installation_type(self, val: int) -> str: """Convert the installation type to a string.""" modes = { diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000..ba4e1e6 --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,104 @@ +"""Tests for custom_components.zaptec.errors.""" + +from http import HTTPStatus + +import pytest + +from custom_components.zaptec.const import DOMAIN +from custom_components.zaptec.errors import api_call_error +from custom_components.zaptec.zaptec.exceptions import RequestError + + +def _request_error(zaptec_code: int | None, details: str | None = None) -> RequestError: + """Return a RequestError as api.py raises it for an HTTP 500.""" + return RequestError( + "POST request failed", + HTTPStatus.INTERNAL_SERVER_ERROR, + zaptec_code=zaptec_code, + zaptec_details=details, + ) + + +def test_details_are_shown_when_zaptec_sends_them() -> None: + """A 500 carrying Details surfaces that text verbatim.""" + err = api_call_error(_request_error(527, "Some other reason"), "Set X") + + assert err.translation_domain == DOMAIN + assert err.translation_key == "api_error_details" + assert err.translation_placeholders == {"action": "Set X", "details": "Some other reason"} + + +def test_apm_is_reworded_as_zaptec_sense() -> None: + """Issue #363: "APM" is Zaptec-internal jargon users won't recognise.""" + err = api_call_error( + _request_error(527, "Cannot update installation when using APM"), "Set X" + ) + + assert err.translation_key == "api_error_apm" + assert err.translation_placeholders == {"action": "Set X"} + + +def test_non_string_details_do_not_crash() -> None: + """Details is server-controlled; a non-string must not break error handling.""" + err = api_call_error(_request_error(999999, 123), "Set X") # type: ignore[arg-type] + + assert err.translation_key == "api_error_code" + assert err.translation_placeholders == {"action": "Set X", "reason": "999999"} + + +def test_scheduled_charging_has_its_own_message() -> None: + """Scheduled charging blocks installation updates with its own 527 reason.""" + err = api_call_error( + _request_error(527, "Cannot update installation when using scheduled power management"), + "Set X", + ) + + assert err.translation_key == "api_error_scheduled" + assert err.translation_placeholders == {"action": "Set X"} + + +def test_unrelated_apm_mention_is_not_claimed_to_be_sense() -> None: + """Only the known sentence maps to Sense; other APM reasons show verbatim.""" + err = api_call_error(_request_error(527, "APM device is offline"), "Set X") + + assert err.translation_key == "api_error_details" + assert err.translation_placeholders == {"action": "Set X", "details": "APM device is offline"} + + +def test_command_rejected_is_hedged() -> None: + """528 gets its own key, since the command may still have been carried out.""" + err = api_call_error(_request_error(528), "Press Y") + + assert err.translation_key == "api_error_command_rejected" + assert err.translation_placeholders == {"action": "Press Y"} + + +def test_charger_state_has_its_own_message() -> None: + """538 means the charger's state forbids the operation.""" + err = api_call_error(_request_error(538), "Press Y") + + assert err.translation_key == "api_error_charger_state" + assert err.translation_placeholders == {"action": "Press Y"} + + +def test_unknown_zaptec_code_falls_back_to_the_decoded_name() -> None: + """An unrecognised code still names itself rather than vanishing.""" + err = api_call_error(_request_error(999999), "Set X") + + assert err.translation_key == "api_error_code" + assert err.translation_placeholders == {"action": "Set X", "reason": "999999"} + + +@pytest.mark.parametrize( + "exc", + [ + RequestError("not found", HTTPStatus.NOT_FOUND), + ValueError("something else entirely"), + ], +) +def test_errors_without_a_zaptec_code_use_the_plain_message(exc: Exception) -> None: + """Non-500 and non-API failures keep today's generic wording.""" + err = api_call_error(exc, "Set X") + + assert err.translation_key == "api_error" + assert err.translation_placeholders == {"action": "Set X"} diff --git a/tests/zaptec/test_api.py b/tests/zaptec/test_api.py index 5cf0818..78aa36e 100644 --- a/tests/zaptec/test_api.py +++ b/tests/zaptec/test_api.py @@ -75,12 +75,14 @@ def __init__( read_data: bytes = b"", text_data: str = "", headers: dict | None = None, + undecodable: bool = False, ) -> None: """Store the canned response data.""" self.status = status self._json_data = json_data self._read_data = read_data self._text_data = text_data + self._undecodable = undecodable self.headers = headers or {} async def json(self, content_type: str | None = None) -> object: @@ -93,8 +95,12 @@ async def read(self) -> bytes: """Return the canned raw body.""" return self._read_data - async def text(self) -> str: - """Return the canned text body.""" + async def text(self, errors: str = "strict") -> str: + """Return the canned text body, honouring aiohttp's `errors` handling.""" + if self._undecodable: + if errors == "strict": + raise UnicodeDecodeError("utf-8", bytes([255]), 0, 1, "invalid start byte") + return "�" return self._text_data @@ -212,6 +218,73 @@ async def test_request_500_on_post_raises_immediately() -> None: assert len(session.calls) == 1 +@pytest.mark.asyncio +async def test_request_500_carries_zaptec_error_code_and_details() -> None: + """A 500 body with Code/Details exposes both on the raised RequestError.""" + zap, _ = _make_zaptec( + [ + FakeResponse( + HTTPStatus.INTERNAL_SERVER_ERROR, + text_data='{"Code":527,"Details":"Cannot update installation when using APM"}', + ) + ] + ) + with pytest.raises(RequestError) as excinfo: + await zap.request("unregistered/url", method="post") + assert excinfo.value.zaptec_code == 527 # noqa: PLR2004 + assert excinfo.value.zaptec_details == "Cannot update installation when using APM" + + +@pytest.mark.asyncio +async def test_request_500_carries_code_when_details_is_null() -> None: + """Charger-level 500s send a null Details; the code must still come through.""" + zap, _ = _make_zaptec( + [ + FakeResponse( + HTTPStatus.INTERNAL_SERVER_ERROR, + text_data='{"Code":528,"Details":null,"StackTrace":null}', + ) + ] + ) + with pytest.raises(RequestError) as excinfo: + await zap.request("unregistered/url", method="post") + assert excinfo.value.zaptec_code == 528 # noqa: PLR2004 + assert excinfo.value.zaptec_details is None + + +@pytest.mark.asyncio +async def test_request_500_without_json_body_has_no_zaptec_code() -> None: + """A non-JSON 500 body leaves the Zaptec code unset instead of raising.""" + zap, _ = _make_zaptec( + [FakeResponse(HTTPStatus.INTERNAL_SERVER_ERROR, text_data="server error")] + ) + with pytest.raises(RequestError) as excinfo: + await zap.request("unregistered/url", method="post") + assert excinfo.value.zaptec_code is None + assert excinfo.value.zaptec_details is None + + +@pytest.mark.asyncio +async def test_request_500_with_non_object_json_has_no_zaptec_code() -> None: + """A JSON 500 body that isn't an object leaves the Zaptec fields unset.""" + zap, _ = _make_zaptec([FakeResponse(HTTPStatus.INTERNAL_SERVER_ERROR, text_data="[1, 2]")]) + with pytest.raises(RequestError) as excinfo: + await zap.request("unregistered/url", method="post") + assert excinfo.value.zaptec_code is None + assert excinfo.value.zaptec_details is None + + +@pytest.mark.asyncio +async def test_request_500_with_undecodable_body_still_retries_on_get() -> None: + """An undecodable 500 body must not escape the retry handling on a GET.""" + zap, session = _make_zaptec( + [FakeResponse(HTTPStatus.INTERNAL_SERVER_ERROR, undecodable=True)], max_time=0.001 + ) + with pytest.raises(RequestRetryError): + await zap.request("unregistered/url") + assert len(session.calls) == API_RETRIES + + @pytest.mark.asyncio async def test_request_500_on_get_retries_then_raises_retry_error() -> None: """A persistent 500 on a GET is retried until exhaustion (RequestRetryError).""" diff --git a/tests/zaptec/test_zconst.py b/tests/zaptec/test_zconst.py index 5735143..a8dac06 100644 --- a/tests/zaptec/test_zconst.py +++ b/tests/zaptec/test_zconst.py @@ -206,3 +206,13 @@ def test_completed_session_corrupted_or_no_signed_session() -> None: def test_update_ids_from_schema() -> None: """Test update_ids_from_schema.""" ZCONST.update_ids_from_schema(set("Apollo")) + + +def test_error_codes() -> None: + """Test the error code conversion.""" + assert ZCONST.type_error_code(527) == "NotSupported" + assert ZCONST.type_error_code(528) == "DeviceCommandRejected" + assert ZCONST.type_error_code(538) == "OperationFailedDueToChargerState" + + # Unknown codes fall back to the numeric value, like the other type_* lookups. + assert ZCONST.type_error_code(999999) == "999999"