Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for Geofency."""
2 
3 from http import HTTPStatus
4 
5 from aiohttp import web
6 import voluptuous as vol
7 
8 from homeassistant.components import webhook
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import (
11  ATTR_LATITUDE,
12  ATTR_LONGITUDE,
13  ATTR_NAME,
14  CONF_WEBHOOK_ID,
15  STATE_NOT_HOME,
16  Platform,
17 )
18 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers import config_entry_flow
21 from homeassistant.helpers.dispatcher import async_dispatcher_send
22 from homeassistant.helpers.typing import ConfigType
23 from homeassistant.util import slugify
24 
25 from .const import DOMAIN
26 
27 PLATFORMS = [Platform.DEVICE_TRACKER]
28 
29 CONF_MOBILE_BEACONS = "mobile_beacons"
30 
31 CONFIG_SCHEMA = vol.Schema(
32  {
33  vol.Optional(DOMAIN): vol.Schema(
34  {
35  vol.Optional(CONF_MOBILE_BEACONS, default=[]): vol.All(
36  cv.ensure_list, [cv.string]
37  )
38  }
39  )
40  },
41  extra=vol.ALLOW_EXTRA,
42 )
43 
44 ATTR_ADDRESS = "address"
45 ATTR_BEACON_ID = "beaconUUID"
46 ATTR_CURRENT_LATITUDE = "currentLatitude"
47 ATTR_CURRENT_LONGITUDE = "currentLongitude"
48 ATTR_DEVICE = "device"
49 ATTR_ENTRY = "entry"
50 
51 BEACON_DEV_PREFIX = "beacon"
52 
53 LOCATION_ENTRY = "1"
54 LOCATION_EXIT = "0"
55 
56 TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
57 
58 
59 def _address(value: str) -> str:
60  r"""Coerce address by replacing '\n' with ' '."""
61  return value.replace("\n", " ")
62 
63 
64 WEBHOOK_SCHEMA = vol.Schema(
65  {
66  vol.Required(ATTR_ADDRESS): vol.All(cv.string, _address),
67  vol.Required(ATTR_DEVICE): vol.All(cv.string, slugify),
68  vol.Required(ATTR_ENTRY): vol.Any(LOCATION_ENTRY, LOCATION_EXIT),
69  vol.Required(ATTR_LATITUDE): cv.latitude,
70  vol.Required(ATTR_LONGITUDE): cv.longitude,
71  vol.Required(ATTR_NAME): vol.All(cv.string, slugify),
72  vol.Optional(ATTR_CURRENT_LATITUDE): cv.latitude,
73  vol.Optional(ATTR_CURRENT_LONGITUDE): cv.longitude,
74  vol.Optional(ATTR_BEACON_ID): cv.string,
75  },
76  extra=vol.ALLOW_EXTRA,
77 )
78 
79 
80 async def async_setup(hass: HomeAssistant, hass_config: ConfigType) -> bool:
81  """Set up the Geofency component."""
82  config = hass_config.get(DOMAIN, {})
83  mobile_beacons = config.get(CONF_MOBILE_BEACONS, [])
84  hass.data[DOMAIN] = {
85  "beacons": [slugify(beacon) for beacon in mobile_beacons],
86  "devices": set(),
87  "unsub_device_tracker": {},
88  }
89  return True
90 
91 
92 async def handle_webhook(
93  hass: HomeAssistant, webhook_id: str, request: web.Request
94 ) -> web.Response:
95  """Handle incoming webhook from Geofency."""
96  try:
97  data = WEBHOOK_SCHEMA(dict(await request.post()))
98  except vol.MultipleInvalid as error:
99  return web.Response(
100  text=error.error_message, status=HTTPStatus.UNPROCESSABLE_ENTITY
101  )
102 
103  if _is_mobile_beacon(data, hass.data[DOMAIN]["beacons"]):
104  return _set_location(hass, data, None)
105  if data["entry"] == LOCATION_ENTRY:
106  location_name = data["name"]
107  else:
108  location_name = STATE_NOT_HOME
109  if ATTR_CURRENT_LATITUDE in data:
110  data[ATTR_LATITUDE] = data[ATTR_CURRENT_LATITUDE]
111  data[ATTR_LONGITUDE] = data[ATTR_CURRENT_LONGITUDE]
112 
113  return _set_location(hass, data, location_name)
114 
115 
116 def _is_mobile_beacon(data, mobile_beacons):
117  """Check if we have a mobile beacon."""
118  return ATTR_BEACON_ID in data and data["name"] in mobile_beacons
119 
120 
121 def _device_name(data):
122  """Return name of device tracker."""
123  if ATTR_BEACON_ID in data:
124  return f"{BEACON_DEV_PREFIX}_{data['name']}"
125  return data["device"]
126 
127 
128 def _set_location(hass, data, location_name):
129  """Fire HA event to set location."""
130  device = _device_name(data)
131 
133  hass,
134  TRACKER_UPDATE,
135  device,
136  (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
137  location_name,
138  data,
139  )
140 
141  return web.Response(text=f"Setting location for {device}")
142 
143 
144 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
145  """Configure based on config entry."""
146  webhook.async_register(
147  hass, DOMAIN, "Geofency", entry.data[CONF_WEBHOOK_ID], handle_webhook
148  )
149 
150  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
151  return True
152 
153 
154 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
155  """Unload a config entry."""
156  webhook.async_unregister(hass, entry.data[CONF_WEBHOOK_ID])
157  hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)()
158  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
159 
160 
161 async_remove_entry = config_entry_flow.webhook_async_remove_entry
bool async_setup(HomeAssistant hass, ConfigType hass_config)
Definition: __init__.py:80
def _set_location(hass, data, location_name)
Definition: __init__.py:128
def _is_mobile_beacon(data, mobile_beacons)
Definition: __init__.py:116
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:154
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:144
web.Response handle_webhook(HomeAssistant hass, str webhook_id, web.Request request)
Definition: __init__.py:94
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:193
str slugify(str|None text, *str separator="_")
Definition: __init__.py:41