Home Assistant Unofficial Reference 2024.12.1
service.py
Go to the documentation of this file.
1 """The Synology DSM component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from synology_dsm.exceptions import SynologyDSMException
8 
9 from homeassistant.core import HomeAssistant, ServiceCall
10 
11 from .const import CONF_SERIAL, DOMAIN, SERVICE_REBOOT, SERVICE_SHUTDOWN, SERVICES
12 from .models import SynologyDSMData
13 
14 LOGGER = logging.getLogger(__name__)
15 
16 
17 async def async_setup_services(hass: HomeAssistant) -> None:
18  """Service handler setup."""
19 
20  async def service_handler(call: ServiceCall) -> None:
21  """Handle service call."""
22  serial = call.data.get(CONF_SERIAL)
23  dsm_devices = hass.data[DOMAIN]
24 
25  if serial:
26  dsm_device: SynologyDSMData = hass.data[DOMAIN][serial]
27  elif len(dsm_devices) == 1:
28  dsm_device = next(iter(dsm_devices.values()))
29  serial = next(iter(dsm_devices))
30  else:
31  LOGGER.error(
32  "More than one DSM configured, must specify one of serials %s",
33  sorted(dsm_devices),
34  )
35  return
36 
37  if not dsm_device:
38  LOGGER.error("DSM with specified serial %s not found", serial)
39  return
40 
41  if call.service in [SERVICE_REBOOT, SERVICE_SHUTDOWN]:
42  if serial not in hass.data[DOMAIN]:
43  LOGGER.error("DSM with specified serial %s not found", serial)
44  return
45  LOGGER.debug("%s DSM with serial %s", call.service, serial)
46  LOGGER.warning(
47  (
48  "The %s service is deprecated and will be removed in future"
49  " release. Please use the corresponding button entity"
50  ),
51  call.service,
52  )
53  dsm_device = hass.data[DOMAIN][serial]
54  dsm_api = dsm_device.api
55  try:
56  await getattr(dsm_api, f"async_{call.service}")()
57  except SynologyDSMException as ex:
58  LOGGER.error(
59  "%s of DSM with serial %s not possible, because of %s",
60  call.service,
61  serial,
62  ex,
63  )
64  return
65 
66  for service in SERVICES:
67  hass.services.async_register(DOMAIN, service, service_handler)
None async_setup_services(HomeAssistant hass)
Definition: service.py:17