Home Assistant Unofficial Reference 2024.12.1
device_action.py
Go to the documentation of this file.
1 """Provides device actions for Network UPS Tools (NUT)."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
7 from homeassistant.components.device_automation import InvalidDeviceAutomationConfig
8 from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_TYPE
9 from homeassistant.core import Context, HomeAssistant
10 from homeassistant.helpers import device_registry as dr
12 from homeassistant.helpers.typing import ConfigType, TemplateVarsType
13 
14 from . import NutRuntimeData
15 from .const import DOMAIN, INTEGRATION_SUPPORTED_COMMANDS
16 
17 ACTION_TYPES = {cmd.replace(".", "_") for cmd in INTEGRATION_SUPPORTED_COMMANDS}
18 
19 ACTION_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
20  {
21  vol.Required(CONF_TYPE): vol.In(ACTION_TYPES),
22  }
23 )
24 
25 
27  hass: HomeAssistant, device_id: str
28 ) -> list[dict[str, str]]:
29  """List device actions for Network UPS Tools (NUT) devices."""
30  if (runtime_data := _get_runtime_data_from_device_id(hass, device_id)) is None:
31  return []
32  base_action = {
33  CONF_DEVICE_ID: device_id,
34  CONF_DOMAIN: DOMAIN,
35  }
36  return [
37  {CONF_TYPE: _get_device_action_name(command_name)} | base_action
38  for command_name in runtime_data.user_available_commands
39  ]
40 
41 
43  hass: HomeAssistant,
44  config: ConfigType,
45  variables: TemplateVarsType,
46  context: Context | None,
47 ) -> None:
48  """Execute a device action."""
49  device_action_name: str = config[CONF_TYPE]
50  command_name = _get_command_name(device_action_name)
51  device_id: str = config[CONF_DEVICE_ID]
52  runtime_data = _get_runtime_data_from_device_id(hass, device_id)
53  if not runtime_data:
55  f"Unable to find a NUT device with id {device_id}"
56  )
57  await runtime_data.data.async_run_command(command_name)
58 
59 
60 def _get_device_action_name(command_name: str) -> str:
61  return command_name.replace(".", "_")
62 
63 
64 def _get_command_name(device_action_name: str) -> str:
65  return device_action_name.replace("_", ".")
66 
67 
69  hass: HomeAssistant, device_id: str
70 ) -> NutRuntimeData | None:
71  device_registry = dr.async_get(hass)
72  if (device := device_registry.async_get(device_id)) is None:
73  return None
74  entry = hass.config_entries.async_get_entry(
75  next(entry_id for entry_id in device.config_entries)
76  )
77  assert entry and isinstance(entry.runtime_data, NutRuntimeData)
78  return entry.runtime_data
list[dict[str, str]] async_get_actions(HomeAssistant hass, str device_id)
None async_call_action_from_config(HomeAssistant hass, ConfigType config, TemplateVarsType variables, Context|None context)
str _get_device_action_name(str command_name)
str _get_command_name(str device_action_name)
NutRuntimeData|None _get_runtime_data_from_device_id(HomeAssistant hass, str device_id)