|
| 1 | +"""Define services for the Stookwijzer integration.""" |
| 2 | + |
| 3 | +from typing import Required, TypedDict, cast |
| 4 | + |
| 5 | +import voluptuous as vol |
| 6 | + |
| 7 | +from homeassistant.config_entries import ConfigEntryState |
| 8 | +from homeassistant.core import ( |
| 9 | + HomeAssistant, |
| 10 | + ServiceCall, |
| 11 | + ServiceResponse, |
| 12 | + SupportsResponse, |
| 13 | +) |
| 14 | +from homeassistant.exceptions import ServiceValidationError |
| 15 | + |
| 16 | +from .const import ATTR_CONFIG_ENTRY_ID, DOMAIN, SERVICE_GET_FORECAST |
| 17 | +from .coordinator import StookwijzerConfigEntry |
| 18 | + |
| 19 | +SERVICE_GET_FORECAST_SCHEMA = vol.Schema( |
| 20 | + { |
| 21 | + vol.Required(ATTR_CONFIG_ENTRY_ID): str, |
| 22 | + } |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +class Forecast(TypedDict): |
| 27 | + """Typed Stookwijzer forecast dict.""" |
| 28 | + |
| 29 | + datetime: Required[str] |
| 30 | + advice: str | None |
| 31 | + final: bool | None |
| 32 | + |
| 33 | + |
| 34 | +def async_get_entry( |
| 35 | + hass: HomeAssistant, config_entry_id: str |
| 36 | +) -> StookwijzerConfigEntry: |
| 37 | + """Get the Overseerr config entry.""" |
| 38 | + if not (entry := hass.config_entries.async_get_entry(config_entry_id)): |
| 39 | + raise ServiceValidationError( |
| 40 | + translation_domain=DOMAIN, |
| 41 | + translation_key="integration_not_found", |
| 42 | + translation_placeholders={"target": DOMAIN}, |
| 43 | + ) |
| 44 | + if entry.state is not ConfigEntryState.LOADED: |
| 45 | + raise ServiceValidationError( |
| 46 | + translation_domain=DOMAIN, |
| 47 | + translation_key="not_loaded", |
| 48 | + translation_placeholders={"target": entry.title}, |
| 49 | + ) |
| 50 | + return cast(StookwijzerConfigEntry, entry) |
| 51 | + |
| 52 | + |
| 53 | +def setup_services(hass: HomeAssistant) -> None: |
| 54 | + """Set up the services for the Stookwijzer integration.""" |
| 55 | + |
| 56 | + async def async_get_forecast(call: ServiceCall) -> ServiceResponse | None: |
| 57 | + """Get the forecast from API endpoint.""" |
| 58 | + entry = async_get_entry(hass, call.data[ATTR_CONFIG_ENTRY_ID]) |
| 59 | + client = entry.runtime_data.client |
| 60 | + |
| 61 | + return cast( |
| 62 | + ServiceResponse, |
| 63 | + { |
| 64 | + "forecast": cast( |
| 65 | + list[Forecast], await client.async_get_forecast() or [] |
| 66 | + ), |
| 67 | + }, |
| 68 | + ) |
| 69 | + |
| 70 | + hass.services.async_register( |
| 71 | + DOMAIN, |
| 72 | + SERVICE_GET_FORECAST, |
| 73 | + async_get_forecast, |
| 74 | + schema=SERVICE_GET_FORECAST_SCHEMA, |
| 75 | + supports_response=SupportsResponse.ONLY, |
| 76 | + ) |
0 commit comments