Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions custom_components/zaptec/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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()

Expand Down
59 changes: 59 additions & 0 deletions custom_components/zaptec/errors.py
Original file line number Diff line number Diff line change
@@ -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,
)
13 changes: 7 additions & 6 deletions custom_components/zaptec/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()

Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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()

Expand Down
17 changes: 9 additions & 8 deletions custom_components/zaptec/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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
Expand Down
10 changes: 5 additions & 5 deletions custom_components/zaptec/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()

Expand All @@ -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()

Expand All @@ -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()

Expand All @@ -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()

Expand Down
21 changes: 21 additions & 0 deletions custom_components/zaptec/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
Expand Down
21 changes: 21 additions & 0 deletions custom_components/zaptec/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
Expand Down
21 changes: 21 additions & 0 deletions custom_components/zaptec/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
Expand Down
21 changes: 21 additions & 0 deletions custom_components/zaptec/translations/nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
Expand Down
21 changes: 21 additions & 0 deletions custom_components/zaptec/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
Expand Down
Loading
Loading