diff --git a/homeassistant/components/keba/__init__.py b/homeassistant/components/keba/__init__.py index 92b7d3405e8f..b185f2df81cb 100644 --- a/homeassistant/components/keba/__init__.py +++ b/homeassistant/components/keba/__init__.py @@ -175,21 +175,13 @@ class KebaHandler(KebaKeContact): async def async_set_energy(self, param): """Set energy target in async way.""" - try: - energy = param[KebaServiceArgument.ENERGY] - await self.set_energy(float(energy)) - self._set_fast_polling() - except (KeyError, ValueError) as ex: - _LOGGER.warning("Energy value is not correct. %s", ex) + await self.set_energy(param[KebaServiceArgument.ENERGY]) + self._set_fast_polling() async def async_set_current(self, param): """Set current maximum in async way.""" - try: - current = param[KebaServiceArgument.CURRENT] - await self.set_current(float(current)) - # No fast polling as this function might be called regularly - except (KeyError, ValueError) as ex: - _LOGGER.warning("Current value is not correct. %s", ex) + await self.set_current(param[KebaServiceArgument.CURRENT]) + # No fast polling as this function might be called regularly async def async_start(self, param=None): """Authorize EV in async way.""" @@ -213,17 +205,9 @@ class KebaHandler(KebaKeContact): async def async_set_failsafe(self, param=None): """Set failsafe mode in async way.""" - try: - timeout = param[KebaServiceArgument.FAILSAFE_TIMEOUT] - fallback = param[KebaServiceArgument.FAILSAFE_FALLBACK] - persist = param[KebaServiceArgument.FAILSAFE_PERSIST] - await self.set_failsafe(int(timeout), float(fallback), int(persist)) - self._set_fast_polling() - except (KeyError, ValueError) as ex: - _LOGGER.warning( - ( - "Values are not correct for: failsafe_timeout, failsafe_fallback" - " and/or failsafe_persist: %s" - ), - ex, - ) + await self.set_failsafe( + param[KebaServiceArgument.FAILSAFE_TIMEOUT], + param[KebaServiceArgument.FAILSAFE_FALLBACK], + param[KebaServiceArgument.FAILSAFE_PERSIST], + ) + self._set_fast_polling() diff --git a/homeassistant/components/keba/services.py b/homeassistant/components/keba/services.py index 2584040dc4b6..550e5012a19a 100644 --- a/homeassistant/components/keba/services.py +++ b/homeassistant/components/keba/services.py @@ -1,30 +1,75 @@ """Support for KEBA charging station services.""" +import probatio + from homeassistant.core import HomeAssistant, ServiceCall, callback -from .const import DOMAIN, KebaService +from .const import DOMAIN, KebaService, KebaServiceArgument -_SERVICE_MAP: dict[str, str] = { - KebaService.REQUEST_DATA: "async_request_data", - KebaService.SET_ENERGY: "async_set_energy", - KebaService.SET_CURRENT: "async_set_current", - KebaService.AUTHORIZE: "async_start", - KebaService.DEAUTHORIZE: "async_stop", - KebaService.ENABLE: "async_enable_ev", - KebaService.DISABLE: "async_disable_ev", - KebaService.SET_FAILSAFE: "async_set_failsafe", + +def _whole_number(value: float) -> int: + """Convert a float to an int, rejecting fractions instead of truncating them.""" + if not value.is_integer(): + raise probatio.Invalid("expected a whole number") + return int(value) + + +# The ranges are the ones keba-kecontact checks before sending a command. +SET_ENERGY_SCHEMA = probatio.Schema( + { + probatio.Required(KebaServiceArgument.ENERGY): probatio.All( + probatio.Coerce(float), + probatio.Any(0, probatio.Range(min=1, max=10000, max_included=False)), + ) + } +) +SET_CURRENT_SCHEMA = probatio.Schema( + { + probatio.Required(KebaServiceArgument.CURRENT): probatio.All( + probatio.Coerce(float), + probatio.Any(0, probatio.Range(min=6, max=63, max_included=False)), + ) + } +) +SET_FAILSAFE_SCHEMA = probatio.Schema( + { + probatio.Required(KebaServiceArgument.FAILSAFE_TIMEOUT): probatio.All( + probatio.Coerce(float), + _whole_number, + probatio.Any(0, probatio.Range(min=10, max=600)), + ), + probatio.Required(KebaServiceArgument.FAILSAFE_FALLBACK): probatio.All( + probatio.Coerce(float), probatio.Any(0, probatio.Range(min=6, max=63)) + ), + probatio.Required(KebaServiceArgument.FAILSAFE_PERSIST): probatio.All( + probatio.Coerce(float), _whole_number, probatio.In([0, 1]) + ), + } +) + +_SERVICE_MAP: dict[str, tuple[str, probatio.Schema | None]] = { + KebaService.REQUEST_DATA: ("async_request_data", None), + KebaService.SET_ENERGY: ("async_set_energy", SET_ENERGY_SCHEMA), + KebaService.SET_CURRENT: ("async_set_current", SET_CURRENT_SCHEMA), + KebaService.AUTHORIZE: ("async_start", None), + KebaService.DEAUTHORIZE: ("async_stop", None), + KebaService.ENABLE: ("async_enable_ev", None), + KebaService.DISABLE: ("async_disable_ev", None), + KebaService.SET_FAILSAFE: ("async_set_failsafe", SET_FAILSAFE_SCHEMA), } async def _async_execute_service(call: ServiceCall) -> None: """Execute a service to KEBA charging station.""" keba = call.hass.data[DOMAIN] - function_call = getattr(keba, _SERVICE_MAP[call.service]) + function_call = getattr(keba, _SERVICE_MAP[call.service][0]) await function_call(call.data) @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the KEBA services.""" - for service in _SERVICE_MAP: - hass.services.async_register(DOMAIN, service, _async_execute_service) + for service, (_, schema) in _SERVICE_MAP.items(): + hass.services.async_register( + DOMAIN, service, _async_execute_service, schema=schema + ) diff --git a/homeassistant/components/keba/services.yaml b/homeassistant/components/keba/services.yaml index daa1749a34ca..4961cb61e865 100644 --- a/homeassistant/components/keba/services.yaml +++ b/homeassistant/components/keba/services.yaml @@ -32,8 +32,8 @@ set_failsafe: default: 30 selector: number: - min: 1 - max: 3600 + min: 0 + max: 600 unit_of_measurement: seconds failsafe_fallback: default: 6 diff --git a/tests/components/keba/test_services.py b/tests/components/keba/test_services.py index 15616ae34adc..96199cefb2e7 100644 --- a/tests/components/keba/test_services.py +++ b/tests/components/keba/test_services.py @@ -4,6 +4,7 @@ from typing import Any from unittest.mock import MagicMock from freezegun.api import FrozenDateTimeFactory +import probatio import pytest from homeassistant.components.keba.const import DOMAIN, KebaService, KebaServiceArgument @@ -40,7 +41,25 @@ FAILSAFE = { (KebaService.DEAUTHORIZE, {}, "stop", ("00845500",), 2), (KebaService.ENABLE, {}, "enable", (True,), 2), (KebaService.DISABLE, {}, "enable", (False,), 2), + ( + KebaService.SET_ENERGY, + {KebaServiceArgument.ENERGY: 0}, + "set_energy", + (0.0,), + 2, + ), (KebaService.SET_FAILSAFE, FAILSAFE, "set_failsafe", (30, 6.0, 1), 2), + ( + KebaService.SET_FAILSAFE, + { + KebaServiceArgument.FAILSAFE_TIMEOUT: 0, + KebaServiceArgument.FAILSAFE_FALLBACK: 0, + KebaServiceArgument.FAILSAFE_PERSIST: 0, + }, + "set_failsafe", + (0, 0.0, 0), + 2, + ), ], ) async def test_action( @@ -94,88 +113,76 @@ async def test_request_data( @pytest.mark.parametrize( - ("service", "data", "method", "message"), + ("service", "data", "method"), [ - (KebaService.SET_ENERGY, {}, "set_energy", "Energy value is not correct"), - ( - KebaService.SET_ENERGY, - {KebaServiceArgument.ENERGY: "lots"}, - "set_energy", - "Energy value is not correct", - ), - (KebaService.SET_CURRENT, {}, "set_current", "Current value is not correct"), - ( - KebaService.SET_CURRENT, - {KebaServiceArgument.CURRENT: "max"}, - "set_current", - "Current value is not correct", - ), - (KebaService.SET_FAILSAFE, {}, "set_failsafe", "Values are not correct for"), + (KebaService.SET_ENERGY, {}, "set_energy"), + (KebaService.SET_ENERGY, {KebaServiceArgument.ENERGY: "lots"}, "set_energy"), + (KebaService.SET_ENERGY, {KebaServiceArgument.ENERGY: 0.5}, "set_energy"), + (KebaService.SET_ENERGY, {KebaServiceArgument.ENERGY: 10000}, "set_energy"), + (KebaService.SET_CURRENT, {}, "set_current"), + (KebaService.SET_CURRENT, {KebaServiceArgument.CURRENT: "max"}, "set_current"), + (KebaService.SET_CURRENT, {KebaServiceArgument.CURRENT: 5}, "set_current"), + (KebaService.SET_CURRENT, {KebaServiceArgument.CURRENT: 63}, "set_current"), + (KebaService.SET_FAILSAFE, {}, "set_failsafe"), ( KebaService.SET_FAILSAFE, {**FAILSAFE, KebaServiceArgument.FAILSAFE_TIMEOUT: "x"}, "set_failsafe", - "Values are not correct for", - ), - ], -) -async def test_invalid_value_is_logged( - hass: HomeAssistant, - setup_keba: MagicMock, - caplog: pytest.LogCaptureFixture, - service: KebaService, - data: dict[str, Any], - method: str, - message: str, -) -> None: - """Test a missing or non-numeric value logs a warning and calls nothing.""" - mock = getattr(setup_keba, method) - mock.reset_mock() - - await hass.services.async_call(DOMAIN, service, data, blocking=True) - - mock.assert_not_awaited() - assert message in caplog.text - - -@pytest.mark.parametrize( - ("service", "data", "method", "message"), - [ - ( - KebaService.SET_ENERGY, - {KebaServiceArgument.ENERGY: 0.5}, - "set_energy", - "Energy value is not correct", - ), - ( - KebaService.SET_CURRENT, - {KebaServiceArgument.CURRENT: 63}, - "set_current", - "Current value is not correct", ), ( KebaService.SET_FAILSAFE, {**FAILSAFE, KebaServiceArgument.FAILSAFE_TIMEOUT: 5}, "set_failsafe", - "Values are not correct for", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_TIMEOUT: 30.5}, + "set_failsafe", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_TIMEOUT: None}, + "set_failsafe", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_FALLBACK: 64}, + "set_failsafe", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_PERSIST: 0.5}, + "set_failsafe", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_PERSIST: 2}, + "set_failsafe", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_PERSIST: None}, + "set_failsafe", + ), + ( + KebaService.SET_FAILSAFE, + {**FAILSAFE, KebaServiceArgument.FAILSAFE_PERSIST: [1]}, + "set_failsafe", ), ], ) -async def test_library_rejection_is_logged( +async def test_invalid_value_is_rejected( hass: HomeAssistant, setup_keba: MagicMock, - freezer: FrozenDateTimeFactory, - caplog: pytest.LogCaptureFixture, service: KebaService, data: dict[str, Any], method: str, - message: str, ) -> None: - """Test a value the library rejects logs a warning, without fast polling.""" - getattr(setup_keba, method).side_effect = ValueError("rejected by the library") + """Test a missing, non-numeric or out-of-range value is rejected and calls nothing.""" + mock = getattr(setup_keba, method) + mock.reset_mock() - await hass.services.async_call(DOMAIN, service, data, blocking=True) - await async_settle(hass) + with pytest.raises(probatio.Invalid): + await hass.services.async_call(DOMAIN, service, data, blocking=True) - assert message in caplog.text - assert await async_seconds_until_poll(hass, freezer, setup_keba) == 5 + mock.assert_not_awaited()