Home Assistant Unofficial Reference 2024.12.1
device_automation.py
Go to the documentation of this file.
1 """Provides device automations for Tasmota."""
2 
3 from __future__ import annotations
4 
5 from hatasmota.const import AUTOMATION_TYPE_TRIGGER
6 from hatasmota.models import DiscoveryHashType
7 from hatasmota.trigger import TasmotaTrigger
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.core import Event, HomeAssistant, callback
12  EVENT_DEVICE_REGISTRY_UPDATED,
13  EventDeviceRegistryUpdatedData,
14 )
15 from homeassistant.helpers.dispatcher import async_dispatcher_connect
16 
17 from . import device_trigger
18 from .const import DATA_REMOVE_DISCOVER_COMPONENT, DATA_UNSUB
19 from .discovery import TASMOTA_DISCOVERY_ENTITY_NEW
20 
21 
22 async def async_remove_automations(hass: HomeAssistant, device_id: str) -> None:
23  """Remove automations for a Tasmota device."""
24  await device_trigger.async_remove_triggers(hass, device_id)
25 
26 
27 async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
28  """Set up Tasmota device automation dynamically through discovery."""
29 
30  async def async_device_removed(
31  event: Event[EventDeviceRegistryUpdatedData],
32  ) -> None:
33  """Handle the removal of a device."""
34  await async_remove_automations(hass, event.data["device_id"])
35 
36  @callback
37  def _async_device_removed_filter(
38  event_data: EventDeviceRegistryUpdatedData,
39  ) -> bool:
40  """Filter device registry events."""
41  return event_data["action"] == "remove"
42 
43  async def async_discover(
44  tasmota_automation: TasmotaTrigger, discovery_hash: DiscoveryHashType
45  ) -> None:
46  """Discover and add a Tasmota device automation."""
47  if tasmota_automation.automation_type == AUTOMATION_TYPE_TRIGGER:
48  await device_trigger.async_setup_trigger(
49  hass, tasmota_automation, config_entry, discovery_hash
50  )
51 
52  hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format("device_automation")] = (
54  hass,
55  TASMOTA_DISCOVERY_ENTITY_NEW.format("device_automation"),
56  async_discover,
57  )
58  )
59  hass.data[DATA_UNSUB].append(
60  hass.bus.async_listen(
61  EVENT_DEVICE_REGISTRY_UPDATED,
62  async_device_removed,
63  event_filter=_async_device_removed_filter,
64  )
65  )
None async_discover(DiscoveryInfo discovery_info)
Definition: sensor.py:217
None async_remove_automations(HomeAssistant hass, str device_id)
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry)
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103