Migrate geofency over to the Webhook component (#18951)

* Migrate geofency over to the Webhook component

* Return web.Response correctly

* Fix test

* Lint

* Fix error that tests caught
This commit is contained in:
Rohan Kapoor authored and Paulus Schoutsen committed 2019-01-08 20:47:05 -08:00
1 parent 23382ab199
commit 2bdbf6955d
5 files changed
+186 -106

No files matched your search

@@ -0,0 +1,18 @@
{
"config": {
"title": "Geofency Webhook",
"step": {
"user": {
"title": "Set up the Geofency Webhook",
"description": "Are you sure you want to set up the Geofency Webhook?"
}
},
"abort": {
"one_instance_allowed": "Only a single instance is necessary.",
"not_internet_accessible": "Your Home Assistant instance needs to be accessible from the internet to receive messages from Geofency."
},
"create_entry": {
"default": "To send events to Home Assistant, you will need to setup the webhook feature in Geofency.\n\nFill in the following info:\n\n- URL: `{webhook_url}`\n- Method: POST\n\nSee [the documentation]({docs_url}) for further details."
}
}
}
+104 -89
View File
@@ -7,11 +7,12 @@ https://home-assistant.io/components/geofency/
import logging
import voluptuous as vol
from aiohttp import web
import homeassistant.helpers.config_validation as cv
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import HTTP_UNPROCESSABLE_ENTITY, STATE_NOT_HOME, \
ATTR_LATITUDE, ATTR_LONGITUDE
ATTR_LATITUDE, ATTR_LONGITUDE, CONF_WEBHOOK_ID, HTTP_OK
from homeassistant.helpers import config_entry_flow
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.util import slugify
@@ -19,7 +20,7 @@ from homeassistant.util import slugify
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'geofency'
DEPENDENCIES = ['http']
DEPENDENCIES = ['webhook']
CONF_MOBILE_BEACONS = 'mobile_beacons'
@@ -40,8 +41,6 @@ BEACON_DEV_PREFIX = 'beacon'
LOCATION_ENTRY = '1'
LOCATION_EXIT = '0'
URL = '/api/geofency'
TRACKER_UPDATE = '{}_tracker_update'.format(DOMAIN)
@@ -50,7 +49,6 @@ async def async_setup(hass, hass_config):
config = hass_config[DOMAIN]
mobile_beacons = config[CONF_MOBILE_BEACONS]
hass.data[DOMAIN] = [slugify(beacon) for beacon in mobile_beacons]
hass.http.register_view(GeofencyView(hass.data[DOMAIN]))
hass.async_create_task(
async_load_platform(hass, 'device_tracker', DOMAIN, {}, hass_config)
@@ -58,89 +56,106 @@ async def async_setup(hass, hass_config):
return True
class GeofencyView(HomeAssistantView):
"""View to handle Geofency requests."""
async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook with Mailgun inbound messages."""
data = _validate_data(await request.post())
url = URL
name = 'api:geofency'
def __init__(self, mobile_beacons):
"""Initialize Geofency url endpoints."""
self.mobile_beacons = mobile_beacons
async def post(self, request):
"""Handle Geofency requests."""
data = await request.post()
hass = request.app['hass']
data = self._validate_data(data)
if not data:
return "Invalid data", HTTP_UNPROCESSABLE_ENTITY
if self._is_mobile_beacon(data):
return await self._set_location(hass, data, None)
if data['entry'] == LOCATION_ENTRY:
location_name = data['name']
else:
location_name = STATE_NOT_HOME
if ATTR_CURRENT_LATITUDE in data:
data[ATTR_LATITUDE] = data[ATTR_CURRENT_LATITUDE]
data[ATTR_LONGITUDE] = data[ATTR_CURRENT_LONGITUDE]
return await self._set_location(hass, data, location_name)
@staticmethod
def _validate_data(data):
"""Validate POST payload."""
data = data.copy()
required_attributes = ['address', 'device', 'entry',
'latitude', 'longitude', 'name']
valid = True
for attribute in required_attributes:
if attribute not in data:
valid = False
_LOGGER.error("'%s' not specified in message", attribute)
if not valid:
return {}
data['address'] = data['address'].replace('\n', ' ')
data['device'] = slugify(data['device'])
data['name'] = slugify(data['name'])
gps_attributes = [ATTR_LATITUDE, ATTR_LONGITUDE,
ATTR_CURRENT_LATITUDE, ATTR_CURRENT_LONGITUDE]
for attribute in gps_attributes:
if attribute in data:
data[attribute] = float(data[attribute])
return data
def _is_mobile_beacon(self, data):
"""Check if we have a mobile beacon."""
return 'beaconUUID' in data and data['name'] in self.mobile_beacons
@staticmethod
def _device_name(data):
"""Return name of device tracker."""
if 'beaconUUID' in data:
return "{}_{}".format(BEACON_DEV_PREFIX, data['name'])
return data['device']
async def _set_location(self, hass, data, location_name):
"""Fire HA event to set location."""
device = self._device_name(data)
async_dispatcher_send(
hass,
TRACKER_UPDATE,
device,
(data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
location_name,
data
if not data:
return web.Response(
body="Invalid data",
status=HTTP_UNPROCESSABLE_ENTITY
)
return "Setting location for {}".format(device)
if _is_mobile_beacon(data, hass.data[DOMAIN]):
return _set_location(hass, data, None)
if data['entry'] == LOCATION_ENTRY:
location_name = data['name']
else:
location_name = STATE_NOT_HOME
if ATTR_CURRENT_LATITUDE in data:
data[ATTR_LATITUDE] = data[ATTR_CURRENT_LATITUDE]
data[ATTR_LONGITUDE] = data[ATTR_CURRENT_LONGITUDE]
return _set_location(hass, data, location_name)
def _validate_data(data):
"""Validate POST payload."""
data = data.copy()
required_attributes = ['address', 'device', 'entry',
'latitude', 'longitude', 'name']
valid = True
for attribute in required_attributes:
if attribute not in data:
valid = False
_LOGGER.error("'%s' not specified in message", attribute)
if not valid:
return {}
data['address'] = data['address'].replace('\n', ' ')
data['device'] = slugify(data['device'])
data['name'] = slugify(data['name'])
gps_attributes = [ATTR_LATITUDE, ATTR_LONGITUDE,
ATTR_CURRENT_LATITUDE, ATTR_CURRENT_LONGITUDE]
for attribute in gps_attributes:
if attribute in data:
data[attribute] = float(data[attribute])
return data
def _is_mobile_beacon(data, mobile_beacons):
"""Check if we have a mobile beacon."""
return 'beaconUUID' in data and data['name'] in mobile_beacons
def _device_name(data):
"""Return name of device tracker."""
if 'beaconUUID' in data:
return "{}_{}".format(BEACON_DEV_PREFIX, data['name'])
return data['device']
def _set_location(hass, data, location_name):
"""Fire HA event to set location."""
device = _device_name(data)
async_dispatcher_send(
hass,
TRACKER_UPDATE,
device,
(data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
location_name,
data
)
return web.Response(
body="Setting location for {}".format(device),
status=HTTP_OK
)
async def async_setup_entry(hass, entry):
"""Configure based on config entry."""
hass.components.webhook.async_register(
DOMAIN, 'Geofency', entry.data[CONF_WEBHOOK_ID], handle_webhook)
return True
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID])
return True
config_entry_flow.register_webhook_flow(
DOMAIN,
'Geofency Webhook',
{
'docs_url': 'https://www.home-assistant.io/components/geofency/'
}
)
@@ -0,0 +1,18 @@
{
"config": {
"title": "Geofency Webhook",
"step": {
"user": {
"title": "Set up the Geofency Webhook",
"description": "Are you sure you want to set up the Geofency Webhook?"
}
},
"abort": {
"one_instance_allowed": "Only a single instance is necessary.",
"not_internet_accessible": "Your Home Assistant instance needs to be accessible from the internet to receive messages from Geofency."
},
"create_entry": {
"default": "To send events to Home Assistant, you will need to setup the webhook feature in Geofency.\n\nFill in the following info:\n\n- URL: `{webhook_url}`\n- Method: POST\n\nSee [the documentation]({docs_url}) for further details."
}
}
}