-
-
Notifications
You must be signed in to change notification settings - Fork 32k
/
Copy path__init__.py
502 lines (424 loc) · 15.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
"""Helpers for device automations."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping
from dataclasses import dataclass
from enum import Enum
from functools import wraps
import logging
from types import ModuleType
from typing import TYPE_CHECKING, Any, Literal, overload
import voluptuous as vol
import voluptuous_serialize
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api import ActiveConnection
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_PLATFORM,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.loader import IntegrationNotFound
from homeassistant.requirements import (
RequirementsNotFound,
async_get_integration_with_requirements,
)
from .const import ( # noqa: F401
CONF_IS_OFF,
CONF_IS_ON,
CONF_TURNED_OFF,
CONF_TURNED_ON,
)
from .exceptions import DeviceNotFound, EntityNotFound, InvalidDeviceAutomationConfig
if TYPE_CHECKING:
from .action import DeviceAutomationActionProtocol
from .condition import DeviceAutomationConditionProtocol
from .trigger import DeviceAutomationTriggerProtocol
type DeviceAutomationPlatformType = (
ModuleType
| DeviceAutomationTriggerProtocol
| DeviceAutomationConditionProtocol
| DeviceAutomationActionProtocol
)
DOMAIN = "device_automation"
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
DEVICE_TRIGGER_BASE_SCHEMA: vol.Schema = cv.TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_PLATFORM): "device",
vol.Required(CONF_DOMAIN): str,
vol.Required(CONF_DEVICE_ID): str,
vol.Remove("metadata"): dict,
}
)
@dataclass
class DeviceAutomationDetails:
"""Details for device automation."""
section: str
get_automations_func: str
get_capabilities_func: str
class DeviceAutomationType(Enum):
"""Device automation type."""
TRIGGER = DeviceAutomationDetails(
"device_trigger",
"async_get_triggers",
"async_get_trigger_capabilities",
)
CONDITION = DeviceAutomationDetails(
"device_condition",
"async_get_conditions",
"async_get_condition_capabilities",
)
ACTION = DeviceAutomationDetails(
"device_action",
"async_get_actions",
"async_get_action_capabilities",
)
# TYPES is deprecated as of Home Assistant 2022.2, use DeviceAutomationType instead
TYPES = {
"trigger": DeviceAutomationType.TRIGGER.value,
"condition": DeviceAutomationType.CONDITION.value,
"action": DeviceAutomationType.ACTION.value,
}
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up device automation."""
websocket_api.async_register_command(hass, websocket_device_automation_list_actions)
websocket_api.async_register_command(
hass, websocket_device_automation_list_conditions
)
websocket_api.async_register_command(
hass, websocket_device_automation_list_triggers
)
websocket_api.async_register_command(
hass, websocket_device_automation_get_action_capabilities
)
websocket_api.async_register_command(
hass, websocket_device_automation_get_condition_capabilities
)
websocket_api.async_register_command(
hass, websocket_device_automation_get_trigger_capabilities
)
return True
@overload
async def async_get_device_automation_platform(
hass: HomeAssistant,
domain: str,
automation_type: Literal[DeviceAutomationType.TRIGGER],
) -> DeviceAutomationTriggerProtocol: ...
@overload
async def async_get_device_automation_platform(
hass: HomeAssistant,
domain: str,
automation_type: Literal[DeviceAutomationType.CONDITION],
) -> DeviceAutomationConditionProtocol: ...
@overload
async def async_get_device_automation_platform(
hass: HomeAssistant,
domain: str,
automation_type: Literal[DeviceAutomationType.ACTION],
) -> DeviceAutomationActionProtocol: ...
@overload
async def async_get_device_automation_platform(
hass: HomeAssistant, domain: str, automation_type: DeviceAutomationType
) -> DeviceAutomationPlatformType: ...
async def async_get_device_automation_platform(
hass: HomeAssistant, domain: str, automation_type: DeviceAutomationType
) -> DeviceAutomationPlatformType:
"""Load device automation platform for integration.
Throws InvalidDeviceAutomationConfig if the integration is not found or does not support device automation.
"""
platform_name = automation_type.value.section
try:
integration = await async_get_integration_with_requirements(hass, domain)
platform = await integration.async_get_platform(platform_name)
except IntegrationNotFound as err:
raise InvalidDeviceAutomationConfig(
f"Integration '{domain}' not found"
) from err
except RequirementsNotFound as err:
raise InvalidDeviceAutomationConfig(
f"Integration '{domain}' could not be loaded"
) from err
except ImportError as err:
raise InvalidDeviceAutomationConfig(
f"Integration '{domain}' does not support device automation "
f"{automation_type.name.lower()}s"
) from err
return platform
@callback
def _async_set_entity_device_automation_metadata(
hass: HomeAssistant, automation: dict[str, Any]
) -> None:
"""Set device automation metadata based on entity registry entry data."""
if "metadata" not in automation:
automation["metadata"] = {}
if ATTR_ENTITY_ID not in automation or "secondary" in automation["metadata"]:
return
entity_registry = er.async_get(hass)
# Guard against the entry being removed before this is called
if not (entry := entity_registry.async_get(automation[ATTR_ENTITY_ID])):
return
automation["metadata"]["secondary"] = bool(entry.entity_category or entry.hidden_by)
async def _async_get_device_automations_from_domain(
hass: HomeAssistant,
domain: str,
automation_type: DeviceAutomationType,
device_ids: Iterable[str],
return_exceptions: bool,
) -> list[list[dict[str, Any]] | Exception]:
"""List device automations."""
try:
platform = await async_get_device_automation_platform(
hass, domain, automation_type
)
except InvalidDeviceAutomationConfig:
return []
function_name = automation_type.value.get_automations_func
return await asyncio.gather( # type: ignore[no-any-return]
*(
getattr(platform, function_name)(hass, device_id)
for device_id in device_ids
),
return_exceptions=return_exceptions,
)
async def async_get_device_automations(
hass: HomeAssistant,
automation_type: DeviceAutomationType,
device_ids: Iterable[str] | None = None,
) -> Mapping[str, list[dict[str, Any]]]:
"""List device automations."""
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
domain_devices: dict[str, set[str]] = {}
device_entities_domains: dict[str, set[str]] = {}
match_device_ids = set(device_ids or device_registry.devices)
combined_results: dict[str, list[dict[str, Any]]] = {}
for device_id in match_device_ids:
for entry in entity_registry.entities.get_entries_for_device_id(device_id):
device_entities_domains.setdefault(device_id, set()).add(entry.domain)
for device_id in match_device_ids:
combined_results[device_id] = []
if (device := device_registry.async_get(device_id)) is None:
raise DeviceNotFound
for entry_id in device.config_entries:
if config_entry := hass.config_entries.async_get_entry(entry_id):
domain_devices.setdefault(config_entry.domain, set()).add(device_id)
for domain in device_entities_domains.get(device_id, []):
domain_devices.setdefault(domain, set()).add(device_id)
# If specific device ids were requested, we allow
# InvalidDeviceAutomationConfig to be thrown, otherwise we skip
# devices that do not have valid triggers
return_exceptions = not bool(device_ids)
for domain_results in await asyncio.gather(
*(
_async_get_device_automations_from_domain(
hass, domain, automation_type, domain_device_ids, return_exceptions
)
for domain, domain_device_ids in domain_devices.items()
)
):
for device_results in domain_results:
if device_results is None or isinstance(
device_results, InvalidDeviceAutomationConfig
):
continue
if isinstance(device_results, Exception):
logging.getLogger(__name__).error(
"Unexpected error fetching device %ss",
automation_type.name.lower(),
exc_info=device_results,
)
continue
for automation in device_results:
_async_set_entity_device_automation_metadata(hass, automation)
combined_results[automation["device_id"]].append(automation)
return combined_results
async def _async_get_device_automation_capabilities(
hass: HomeAssistant,
automation_type: DeviceAutomationType,
automation: Mapping[str, Any],
) -> dict[str, Any]:
"""List device automations."""
try:
platform = await async_get_device_automation_platform(
hass, automation[CONF_DOMAIN], automation_type
)
except InvalidDeviceAutomationConfig:
return {}
function_name = automation_type.value.get_capabilities_func
if not hasattr(platform, function_name):
# The device automation has no capabilities
return {}
try:
capabilities = await getattr(platform, function_name)(hass, automation)
except (EntityNotFound, InvalidDeviceAutomationConfig):
return {}
capabilities = capabilities.copy()
if (extra_fields := capabilities.get("extra_fields")) is None:
capabilities["extra_fields"] = []
else:
capabilities["extra_fields"] = voluptuous_serialize.convert(
extra_fields, custom_serializer=cv.custom_serializer
)
return capabilities # type: ignore[no-any-return]
@callback
def async_get_entity_registry_entry_or_raise(
hass: HomeAssistant, entity_registry_id: str
) -> er.RegistryEntry:
"""Get an entity registry entry from entry ID or raise."""
entity_registry = er.async_get(hass)
entry = entity_registry.async_get(entity_registry_id)
if entry is None:
raise EntityNotFound
return entry
@callback
def async_validate_entity_schema(
hass: HomeAssistant, config: ConfigType, schema: VolSchemaType
) -> ConfigType:
"""Validate schema and resolve entity registry entry id to entity_id."""
config = schema(config)
registry = er.async_get(hass)
if CONF_ENTITY_ID in config:
config[CONF_ENTITY_ID] = er.async_resolve_entity_id(
registry, config[CONF_ENTITY_ID]
)
return config
def handle_device_errors(
func: Callable[[HomeAssistant, ActiveConnection, dict[str, Any]], Awaitable[None]],
) -> Callable[
[HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any, None]
]:
"""Handle device automation errors."""
@wraps(func)
async def with_error_handling(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
try:
await func(hass, connection, msg)
except DeviceNotFound:
connection.send_error(
msg["id"], websocket_api.ERR_NOT_FOUND, "Device not found"
)
return with_error_handling
@websocket_api.websocket_command(
{
vol.Required("type"): "device_automation/action/list",
vol.Required("device_id"): str,
}
)
@websocket_api.async_response
@handle_device_errors
async def websocket_device_automation_list_actions(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for device actions."""
device_id = msg["device_id"]
actions = (
await async_get_device_automations(
hass, DeviceAutomationType.ACTION, [device_id]
)
).get(device_id)
connection.send_result(msg["id"], actions)
@websocket_api.websocket_command(
{
vol.Required("type"): "device_automation/condition/list",
vol.Required("device_id"): str,
}
)
@websocket_api.async_response
@handle_device_errors
async def websocket_device_automation_list_conditions(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for device conditions."""
device_id = msg["device_id"]
conditions = (
await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, [device_id]
)
).get(device_id)
connection.send_result(msg["id"], conditions)
@websocket_api.websocket_command(
{
vol.Required("type"): "device_automation/trigger/list",
vol.Required("device_id"): str,
}
)
@websocket_api.async_response
@handle_device_errors
async def websocket_device_automation_list_triggers(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for device triggers."""
device_id = msg["device_id"]
triggers = (
await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, [device_id]
)
).get(device_id)
connection.send_result(msg["id"], triggers)
@websocket_api.websocket_command(
{
vol.Required("type"): "device_automation/action/capabilities",
vol.Required("action"): dict,
}
)
@websocket_api.async_response
@handle_device_errors
async def websocket_device_automation_get_action_capabilities(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for device action capabilities."""
action = msg["action"]
capabilities = await _async_get_device_automation_capabilities(
hass, DeviceAutomationType.ACTION, action
)
connection.send_result(msg["id"], capabilities)
@websocket_api.websocket_command(
{
vol.Required("type"): "device_automation/condition/capabilities",
vol.Required("condition"): cv.DEVICE_CONDITION_BASE_SCHEMA.extend(
{}, extra=vol.ALLOW_EXTRA
),
}
)
@websocket_api.async_response
@handle_device_errors
async def websocket_device_automation_get_condition_capabilities(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for device condition capabilities."""
condition = msg["condition"]
capabilities = await _async_get_device_automation_capabilities(
hass, DeviceAutomationType.CONDITION, condition
)
connection.send_result(msg["id"], capabilities)
@websocket_api.websocket_command(
{
vol.Required("type"): "device_automation/trigger/capabilities",
# The frontend responds with `trigger` as key, while the
# `DEVICE_TRIGGER_BASE_SCHEMA` expects `platform1` as key.
vol.Required("trigger"): vol.All(
cv._trigger_pre_validator, # noqa: SLF001
DEVICE_TRIGGER_BASE_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA),
),
}
)
@websocket_api.async_response
@handle_device_errors
async def websocket_device_automation_get_trigger_capabilities(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for device trigger capabilities."""
trigger = msg["trigger"]
capabilities = await _async_get_device_automation_capabilities(
hass, DeviceAutomationType.TRIGGER, trigger
)
connection.send_result(msg["id"], capabilities)