Home Assistant Unofficial Reference 2024.12.1
services.py
Go to the documentation of this file.
1 """Define services for the Swiss public transport integration."""
2 
3 import voluptuous as vol
4 
5 from homeassistant.config_entries import ConfigEntryState
6 from homeassistant.core import (
7  HomeAssistant,
8  ServiceCall,
9  ServiceResponse,
10  SupportsResponse,
11 )
12 from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
14  NumberSelector,
15  NumberSelectorConfig,
16  NumberSelectorMode,
17 )
18 from homeassistant.helpers.update_coordinator import UpdateFailed
19 
20 from .const import (
21  ATTR_CONFIG_ENTRY_ID,
22  ATTR_LIMIT,
23  CONNECTIONS_COUNT,
24  CONNECTIONS_MAX,
25  DOMAIN,
26  SERVICE_FETCH_CONNECTIONS,
27 )
28 from .coordinator import SwissPublicTransportConfigEntry
29 
30 SERVICE_FETCH_CONNECTIONS_SCHEMA = vol.Schema(
31  {
32  vol.Required(ATTR_CONFIG_ENTRY_ID): str,
33  vol.Optional(ATTR_LIMIT, default=CONNECTIONS_COUNT): NumberSelector(
35  min=1, max=CONNECTIONS_MAX, mode=NumberSelectorMode.BOX
36  )
37  ),
38  }
39 )
40 
41 
43  hass: HomeAssistant, config_entry_id: str
44 ) -> SwissPublicTransportConfigEntry:
45  """Get the Swiss public transport config entry."""
46  if not (entry := hass.config_entries.async_get_entry(config_entry_id)):
48  translation_domain=DOMAIN,
49  translation_key="config_entry_not_found",
50  translation_placeholders={"target": config_entry_id},
51  )
52  if entry.state is not ConfigEntryState.LOADED:
54  translation_domain=DOMAIN,
55  translation_key="not_loaded",
56  translation_placeholders={"target": entry.title},
57  )
58  return entry
59 
60 
61 def setup_services(hass: HomeAssistant) -> None:
62  """Set up the services for the Swiss public transport integration."""
63 
64  async def async_fetch_connections(
65  call: ServiceCall,
66  ) -> ServiceResponse:
67  """Fetch a set of connections."""
68  config_entry = async_get_entry(hass, call.data[ATTR_CONFIG_ENTRY_ID])
69 
70  limit = call.data.get(ATTR_LIMIT) or CONNECTIONS_COUNT
71  try:
72  connections = await config_entry.runtime_data.fetch_connections_as_json(
73  limit=int(limit)
74  )
75  except UpdateFailed as e:
76  raise HomeAssistantError(
77  translation_domain=DOMAIN,
78  translation_key="cannot_connect",
79  translation_placeholders={
80  "error": str(e),
81  },
82  ) from e
83  return {"connections": connections}
84 
85  hass.services.async_register(
86  DOMAIN,
87  SERVICE_FETCH_CONNECTIONS,
88  async_fetch_connections,
89  schema=SERVICE_FETCH_CONNECTIONS_SCHEMA,
90  supports_response=SupportsResponse.ONLY,
91  )
SwissPublicTransportConfigEntry async_get_entry(HomeAssistant hass, str config_entry_id)
Definition: services.py:44