Home Assistant Unofficial Reference 2024.12.1
trigger.py
Go to the documentation of this file.
1 """Support for tag triggers."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
7 from homeassistant.const import CONF_PLATFORM
8 from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant
9 from homeassistant.helpers import config_validation as cv
10 from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
11 from homeassistant.helpers.typing import ConfigType
12 
13 from .const import DEVICE_ID, DOMAIN, EVENT_TAG_SCANNED, TAG_ID
14 
15 TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
16  {
17  vol.Required(CONF_PLATFORM): DOMAIN,
18  vol.Required(TAG_ID): vol.All(cv.ensure_list, [cv.string]),
19  vol.Optional(DEVICE_ID): vol.All(cv.ensure_list, [cv.string]),
20  }
21 )
22 
23 
25  hass: HomeAssistant,
26  config: ConfigType,
27  action: TriggerActionType,
28  trigger_info: TriggerInfo,
29 ) -> CALLBACK_TYPE:
30  """Listen for tag_scanned events based on configuration."""
31  trigger_data = trigger_info["trigger_data"]
32  tag_ids: set[str] = set(config[TAG_ID])
33  device_ids: set[str] | None = (
34  set(config[DEVICE_ID]) if DEVICE_ID in config else None
35  )
36 
37  job = HassJob(action)
38 
39  async def handle_event(event: Event) -> None:
40  """Listen for tag scan events and calls the action when data matches."""
41  if event.data.get(TAG_ID) not in tag_ids or (
42  device_ids is not None and event.data.get(DEVICE_ID) not in device_ids
43  ):
44  return
45 
46  task = hass.async_run_hass_job(
47  job,
48  {
49  "trigger": {
50  **trigger_data,
51  "platform": DOMAIN,
52  "event": event,
53  "description": "Tag scanned",
54  }
55  },
56  event.context,
57  )
58 
59  if task:
60  await task
61 
62  return hass.bus.async_listen(EVENT_TAG_SCANNED, handle_event)
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)
Definition: trigger.py:29