1 """Provides device triggers for BTHome BLE."""
3 from __future__
import annotations
5 from typing
import TYPE_CHECKING, Any
7 import voluptuous
as vol
10 DEVICE_TRIGGER_BASE_SCHEMA,
11 InvalidDeviceAutomationConfig,
28 CONF_DISCOVERED_EVENT_CLASSES,
37 EVENT_TYPES_BY_EVENT_CLASS = {
46 EVENT_CLASS_DIMMER: {
"rotate_left",
"rotate_right"},
49 TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
50 {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str}
55 """Get the supported event classes for a device.
57 Events for BTHome BLE devices are dynamically discovered
58 and stored in the device config entry when they are first seen.
60 device_registry = dr.async_get(hass)
61 device = device_registry.async_get(device_id)
63 assert device
is not None
66 hass.config_entries.async_get_entry(entry_id)
67 for entry_id
in device.config_entries
69 bthome_config_entry = next(
70 entry
for entry
in config_entries
if entry
and entry.domain == DOMAIN
72 return bthome_config_entry.data.get(CONF_DISCOVERED_EVENT_CLASSES, [])
76 """Get the supported event types for an event class.
78 If the device has multiple buttons they will have
79 event classes like button_1 button_2, button_3, etc
80 but if there is only one button then it will be
81 button without a number postfix.
83 return EVENT_TYPES_BY_EVENT_CLASS.get(event_class.split(
"_")[0], set())
87 hass: HomeAssistant, config: ConfigType
89 """Validate trigger config."""
91 event_class = config[CONF_TYPE]
92 event_type = config[CONF_SUBTYPE]
93 device_id = config[CONF_DEVICE_ID]
96 if event_class
not in event_classes:
97 raise InvalidDeviceAutomationConfig(
98 f
"BTHome trigger {event_class} is not valid for device_id '{device_id}'"
102 raise InvalidDeviceAutomationConfig(
103 f
"BTHome trigger {event_type} is not valid for device_id '{device_id}'"
110 hass: HomeAssistant, device_id: str
111 ) -> list[dict[str, Any]]:
112 """Return a list of triggers for BTHome BLE devices."""
117 CONF_PLATFORM:
"device",
118 CONF_DEVICE_ID: device_id,
121 CONF_TYPE: event_class,
122 CONF_SUBTYPE: event_type,
124 for event_class
in event_classes
132 action: TriggerActionType,
133 trigger_info: TriggerInfo,
135 """Attach a trigger."""
136 return await event_trigger.async_attach_trigger(
138 event_trigger.TRIGGER_SCHEMA(
140 event_trigger.CONF_PLATFORM: CONF_EVENT,
141 event_trigger.CONF_EVENT_TYPE: BTHOME_BLE_EVENT,
142 event_trigger.CONF_EVENT_DATA: {
143 CONF_DEVICE_ID: config[CONF_DEVICE_ID],
144 EVENT_CLASS: config[CONF_TYPE],
145 EVENT_TYPE: config[CONF_SUBTYPE],
151 platform_type=
"device",
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)
set[str] get_event_types_by_event_class(str event_class)
ConfigType async_validate_trigger_config(HomeAssistant hass, ConfigType config)
list[str] get_event_classes_by_device_id(HomeAssistant hass, str device_id)
list[dict[str, Any]] async_get_triggers(HomeAssistant hass, str device_id)