Compare commits

..

5 Commits

Author SHA1 Message Date
Pascal Vizeli 704cdac874 Bumped version to 0.94.0b5 2019-06-03 08:36:38 +00:00
Paulus Schoutsen 89d7c0af91 Add restore state to Geofency (#24268)
* Add restore state to Geofency

* Lint
2019-06-03 08:35:44 +00:00
Paulus Schoutsen 5f3bcedbba Mobile app device tracker to restore state (#24266) 2019-06-03 08:35:43 +00:00
Paulus Schoutsen d2d3f27f85 Add restore state to OwnTracks device tracker (#24256)
* Add restore state to OwnTracks device tracker

* Lint

* Also store entity devices

* Update test_device_tracker.py
2019-06-03 08:35:43 +00:00
Paulus Schoutsen a8c73ffb93 Updated frontend to 20190602.0 2019-06-02 14:00:52 -07:00
12 changed files with 289 additions and 105 deletions
@@ -3,7 +3,7 @@
"name": "Home Assistant Frontend",
"documentation": "https://www.home-assistant.io/components/frontend",
"requirements": [
"home-assistant-frontend==20190601.0"
"home-assistant-frontend==20190602.0"
],
"dependencies": [
"api",
@@ -1,12 +1,18 @@
"""Support for the Geofency device tracker platform."""
import logging
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
)
from homeassistant.core import callback
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.components.device_tracker.config_entry import (
DeviceTrackerEntity
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers import device_registry
from . import DOMAIN as GF_DOMAIN, TRACKER_UPDATE
@@ -30,15 +36,28 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
hass.data[GF_DOMAIN]['unsub_device_tracker'][config_entry.entry_id] = \
async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
# Restore previously loaded devices
dev_reg = await device_registry.async_get_registry(hass)
dev_ids = {
identifier[1]
for device in dev_reg.devices.values()
for identifier in device.identifiers
if identifier[0] == GF_DOMAIN
}
if dev_ids:
hass.data[GF_DOMAIN]['devices'].update(dev_ids)
async_add_entities(GeofencyEntity(dev_id) for dev_id in dev_ids)
return True
class GeofencyEntity(DeviceTrackerEntity):
class GeofencyEntity(DeviceTrackerEntity, RestoreEntity):
"""Represent a tracked device."""
def __init__(self, device, gps, location_name, attributes):
def __init__(self, device, gps=None, location_name=None, attributes=None):
"""Set up Geofency entity."""
self._attributes = attributes
self._attributes = attributes or {}
self._name = device
self._location_name = location_name
self._gps = gps
@@ -95,12 +114,27 @@ class GeofencyEntity(DeviceTrackerEntity):
async def async_added_to_hass(self):
"""Register state update callback."""
await super().async_added_to_hass()
self._unsub_dispatcher = async_dispatcher_connect(
self.hass, TRACKER_UPDATE, self._async_receive_data)
if self._attributes:
return
state = await self.async_get_last_state()
if state is None:
self._gps = (None, None)
return
attr = state.attributes
self._gps = (attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE))
async def async_will_remove_from_hass(self):
"""Clean up after entity before removal."""
await super().async_will_remove_from_hass()
self._unsub_dispatcher()
self.hass.data[GF_DOMAIN]['devices'].remove(self._unique_id)
@callback
def _async_receive_data(self, device, gps, location_name, attributes):
@@ -7,7 +7,7 @@ from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from .const import (ATTR_DEVICE_ID, ATTR_DEVICE_NAME,
ATTR_MANUFACTURER, ATTR_MODEL, ATTR_OS_VERSION,
DATA_BINARY_SENSOR, DATA_CONFIG_ENTRIES, DATA_DELETED_IDS,
DATA_DEVICES, DATA_DEVICE_TRACKER, DATA_SENSOR, DATA_STORE,
DATA_DEVICES, DATA_SENSOR, DATA_STORE,
DOMAIN, STORAGE_KEY, STORAGE_VERSION)
from .http_api import RegistrationsView
@@ -34,7 +34,6 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType):
DATA_CONFIG_ENTRIES: {},
DATA_DELETED_IDS: app_config.get(DATA_DELETED_IDS, []),
DATA_DEVICES: {},
DATA_DEVICE_TRACKER: {},
DATA_SENSOR: app_config.get(DATA_SENSOR, {}),
DATA_STORE: store,
}
@@ -25,7 +25,6 @@ DATA_BINARY_SENSOR = 'binary_sensor'
DATA_CONFIG_ENTRIES = 'config_entries'
DATA_DELETED_IDS = 'deleted_ids'
DATA_DEVICES = 'devices'
DATA_DEVICE_TRACKER = 'device_tracker'
DATA_SENSOR = 'sensor'
DATA_STORE = 'store'
@@ -2,14 +2,17 @@
import logging
from homeassistant.core import callback
from homeassistant.components.device_tracker.const import (
DOMAIN, SOURCE_TYPE_GPS)
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_BATTERY_LEVEL,
)
from homeassistant.components.device_tracker.const import SOURCE_TYPE_GPS
from homeassistant.components.device_tracker.config_entry import (
DeviceTrackerEntity
)
from homeassistant.helpers.restore_state import RestoreEntity
from .const import (
DOMAIN as MA_DOMAIN,
ATTR_ALTITUDE,
ATTR_BATTERY,
ATTR_COURSE,
@@ -26,37 +29,29 @@ from .const import (
from .helpers import device_info
_LOGGER = logging.getLogger(__name__)
ATTR_KEYS = (
ATTR_ALTITUDE,
ATTR_COURSE,
ATTR_SPEED,
ATTR_VERTICAL_ACCURACY
)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up OwnTracks based off an entry."""
@callback
def _receive_data(data):
"""Receive set location."""
dev_id = entry.data[ATTR_DEVICE_ID]
device = hass.data[MA_DOMAIN][DOMAIN].get(dev_id)
if device is not None:
device.update_data(data)
return
device = hass.data[MA_DOMAIN][DOMAIN][dev_id] = MobileAppEntity(
entry, data
)
async_add_entities([device])
hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_LOCATION_UPDATE.format(entry.entry_id), _receive_data)
entity = MobileAppEntity(entry)
async_add_entities([entity])
return True
class MobileAppEntity(DeviceTrackerEntity):
class MobileAppEntity(DeviceTrackerEntity, RestoreEntity):
"""Represent a tracked device."""
def __init__(self, entry, data):
def __init__(self, entry, data=None):
"""Set up OwnTracks entity."""
self._entry = entry
self._data = data
self._dispatch_unsub = None
@property
def unique_id(self):
@@ -72,8 +67,7 @@ class MobileAppEntity(DeviceTrackerEntity):
def device_state_attributes(self):
"""Return device specific attributes."""
attrs = {}
for key in (ATTR_ALTITUDE, ATTR_COURSE,
ATTR_SPEED, ATTR_VERTICAL_ACCURACY):
for key in ATTR_KEYS:
value = self._data.get(key)
if value is not None:
attrs[key] = value
@@ -130,6 +124,42 @@ class MobileAppEntity(DeviceTrackerEntity):
"""Return the device info."""
return device_info(self._entry.data)
async def async_added_to_hass(self):
"""Call when entity about to be added to Home Assistant."""
await super().async_added_to_hass()
self._dispatch_unsub = \
self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_LOCATION_UPDATE.format(self._entry.entry_id),
self.update_data
)
# Don't restore if we got set up with data.
if self._data is not None:
return
state = await self.async_get_last_state()
if state is None:
self._data = {}
return
attr = state.attributes
data = {
ATTR_GPS: (attr[ATTR_LATITUDE], attr[ATTR_LONGITUDE]),
ATTR_GPS_ACCURACY: attr[ATTR_GPS_ACCURACY],
ATTR_BATTERY: attr[ATTR_BATTERY_LEVEL],
}
data.update({key: attr[key] for key in attr if key in ATTR_KEYS})
self._data = data
async def async_will_remove_from_hass(self):
"""Call when entity is being removed from hass."""
await super().async_will_remove_from_hass()
if self._dispatch_unsub:
self._dispatch_unsub()
self._dispatch_unsub = None
@callback
def update_data(self, data):
"""Mark the device as seen."""
@@ -2,10 +2,19 @@
import logging
from homeassistant.core import callback
from homeassistant.components.device_tracker.const import ENTITY_ID_FORMAT
from homeassistant.const import (
ATTR_GPS_ACCURACY,
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_BATTERY_LEVEL,
)
from homeassistant.components.device_tracker.const import (
ENTITY_ID_FORMAT, ATTR_SOURCE_TYPE)
from homeassistant.components.device_tracker.config_entry import (
DeviceTrackerEntity
)
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers import device_registry
from . import DOMAIN as OT_DOMAIN
_LOGGER = logging.getLogger(__name__)
@@ -14,53 +23,52 @@ _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up OwnTracks based off an entry."""
@callback
def _receive_data(dev_id, host_name, gps, attributes, gps_accuracy=None,
battery=None, source_type=None, location_name=None):
def _receive_data(dev_id, **data):
"""Receive set location."""
device = hass.data[OT_DOMAIN]['devices'].get(dev_id)
entity = hass.data[OT_DOMAIN]['devices'].get(dev_id)
if device is not None:
device.update_data(
host_name=host_name,
gps=gps,
attributes=attributes,
gps_accuracy=gps_accuracy,
battery=battery,
source_type=source_type,
location_name=location_name,
)
if entity is not None:
entity.update_data(data)
return
device = hass.data[OT_DOMAIN]['devices'][dev_id] = OwnTracksEntity(
dev_id=dev_id,
host_name=host_name,
gps=gps,
attributes=attributes,
gps_accuracy=gps_accuracy,
battery=battery,
source_type=source_type,
location_name=location_name,
entity = hass.data[OT_DOMAIN]['devices'][dev_id] = OwnTracksEntity(
dev_id, data
)
async_add_entities([device])
async_add_entities([entity])
hass.data[OT_DOMAIN]['context'].async_see = _receive_data
# Restore previously loaded devices
dev_reg = await device_registry.async_get_registry(hass)
dev_ids = {
identifier[1]
for device in dev_reg.devices.values()
for identifier in device.identifiers
if identifier[0] == OT_DOMAIN
}
if not dev_ids:
return True
entities = []
for dev_id in dev_ids:
entity = hass.data[OT_DOMAIN]['devices'][dev_id] = OwnTracksEntity(
dev_id
)
entities.append(entity)
async_add_entities(entities)
return True
class OwnTracksEntity(DeviceTrackerEntity):
class OwnTracksEntity(DeviceTrackerEntity, RestoreEntity):
"""Represent a tracked device."""
def __init__(self, dev_id, host_name, gps, attributes, gps_accuracy,
battery, source_type, location_name):
def __init__(self, dev_id, data=None):
"""Set up OwnTracks entity."""
self._dev_id = dev_id
self._host_name = host_name
self._gps = gps
self._gps_accuracy = gps_accuracy
self._location_name = location_name
self._attributes = attributes
self._battery = battery
self._source_type = source_type
self._data = data or {}
self.entity_id = ENTITY_ID_FORMAT.format(dev_id)
@property
@@ -71,43 +79,45 @@ class OwnTracksEntity(DeviceTrackerEntity):
@property
def battery_level(self):
"""Return the battery level of the device."""
return self._battery
return self._data.get('battery')
@property
def device_state_attributes(self):
"""Return device specific attributes."""
return self._attributes
return self._data.get('attributes')
@property
def location_accuracy(self):
"""Return the gps accuracy of the device."""
return self._gps_accuracy
return self._data.get('gps_accuracy')
@property
def latitude(self):
"""Return latitude value of the device."""
if self._gps is not None:
return self._gps[0]
# Check with "get" instead of "in" because value can be None
if self._data.get('gps'):
return self._data['gps'][0]
return None
@property
def longitude(self):
"""Return longitude value of the device."""
if self._gps is not None:
return self._gps[1]
# Check with "get" instead of "in" because value can be None
if self._data.get('gps'):
return self._data['gps'][1]
return None
@property
def location_name(self):
"""Return a location name for the current location of the device."""
return self._location_name
return self._data.get('location_name')
@property
def name(self):
"""Return the name of the device."""
return self._host_name
return self._data.get('host_name')
@property
def should_poll(self):
@@ -117,26 +127,40 @@ class OwnTracksEntity(DeviceTrackerEntity):
@property
def source_type(self):
"""Return the source type, eg gps or router, of the device."""
return self._source_type
return self._data.get('source_type')
@property
def device_info(self):
"""Return the device info."""
return {
'name': self._host_name,
'name': self.name,
'identifiers': {(OT_DOMAIN, self._dev_id)},
}
@callback
def update_data(self, host_name, gps, attributes, gps_accuracy,
battery, source_type, location_name):
"""Mark the device as seen."""
self._host_name = host_name
self._gps = gps
self._gps_accuracy = gps_accuracy
self._location_name = location_name
self._attributes = attributes
self._battery = battery
self._source_type = source_type
async def async_added_to_hass(self):
"""Call when entity about to be added to Home Assistant."""
await super().async_added_to_hass()
# Don't restore if we got set up with data.
if self._data:
return
state = await self.async_get_last_state()
if state is None:
return
attr = state.attributes
self._data = {
'host_name': state.name,
'gps': (attr[ATTR_LATITUDE], attr[ATTR_LONGITUDE]),
'gps_accuracy': attr[ATTR_GPS_ACCURACY],
'battery': attr[ATTR_BATTERY_LEVEL],
'source_type': attr[ATTR_SOURCE_TYPE],
}
@callback
def update_data(self, data):
"""Mark the device as seen."""
self._data = data
self.async_write_ha_state()
+1 -1
View File
@@ -2,7 +2,7 @@
"""Constants used by Home Assistant components."""
MAJOR_VERSION = 0
MINOR_VERSION = 94
PATCH_VERSION = '0b4'
PATCH_VERSION = '0b5'
__short_version__ = '{}.{}'.format(MAJOR_VERSION, MINOR_VERSION)
__version__ = '{}.{}'.format(__short_version__, PATCH_VERSION)
REQUIRED_PYTHON_VER = (3, 5, 3)
+1 -1
View File
@@ -577,7 +577,7 @@ hole==0.3.0
holidays==0.9.10
# homeassistant.components.frontend
home-assistant-frontend==20190601.0
home-assistant-frontend==20190602.0
# homeassistant.components.zwave
homeassistant-pyozw==0.1.4
+1 -1
View File
@@ -148,7 +148,7 @@ hdate==0.8.7
holidays==0.9.10
# homeassistant.components.frontend
home-assistant-frontend==20190601.0
home-assistant-frontend==20190602.0
# homeassistant.components.homekit_controller
homekit[IP]==0.14.0
+18 -12
View File
@@ -5,13 +5,12 @@ from unittest.mock import patch, Mock
import pytest
from homeassistant import data_entry_flow
from homeassistant.components import zone, geofency
from homeassistant.components import zone
from homeassistant.components.geofency import (
CONF_MOBILE_BEACONS, DOMAIN, TRACKER_UPDATE)
CONF_MOBILE_BEACONS, DOMAIN)
from homeassistant.const import (
HTTP_OK, HTTP_UNPROCESSABLE_ENTITY, STATE_HOME,
STATE_NOT_HOME)
from homeassistant.helpers.dispatcher import DATA_DISPATCHER
from homeassistant.setup import async_setup_component
from homeassistant.util import slugify
@@ -291,9 +290,6 @@ async def test_beacon_enter_and_exit_car(hass, geofency_client, webhook_id):
assert STATE_HOME == state_name
@pytest.mark.xfail(
reason='The device_tracker component does not support unloading yet.'
)
async def test_load_unload_entry(hass, geofency_client, webhook_id):
"""Test that the appropriate dispatch signals are added and removed."""
url = '/api/webhook/{}'.format(webhook_id)
@@ -303,13 +299,23 @@ async def test_load_unload_entry(hass, geofency_client, webhook_id):
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(GPS_ENTER_HOME['device'])
state_name = hass.states.get('{}.{}'.format(
'device_tracker', device_name)).state
assert STATE_HOME == state_name
assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1
state_1 = hass.states.get('{}.{}'.format('device_tracker', device_name))
assert STATE_HOME == state_1.state
assert len(hass.data[DOMAIN]['devices']) == 1
entry = hass.config_entries.async_entries(DOMAIN)[0]
assert await geofency.async_unload_entry(hass, entry)
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert not hass.data[DATA_DISPATCHER][TRACKER_UPDATE]
assert len(hass.data[DOMAIN]['devices']) == 0
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state_2 = hass.states.get('{}.{}'.format('device_tracker', device_name))
assert state_2 is not None
assert state_1 is not state_2
assert STATE_HOME == state_2.state
assert state_2.attributes['latitude'] == HOME_LATITUDE
assert state_2.attributes['longitude'] == HOME_LONGITUDE
@@ -22,7 +22,7 @@ async def test_sending_location(hass, create_registrations, webhook_client):
assert resp.status == 200
await hass.async_block_till_done()
state = hass.states.get('device_tracker.test_1')
state = hass.states.get('device_tracker.test_1_2')
assert state is not None
assert state.name == 'Test 1'
assert state.state == 'bar'
@@ -54,7 +54,7 @@ async def test_sending_location(hass, create_registrations, webhook_client):
assert resp.status == 200
await hass.async_block_till_done()
state = hass.states.get('device_tracker.test_1')
state = hass.states.get('device_tracker.test_1_2')
assert state is not None
assert state.state == 'not_home'
assert state.attributes['source_type'] == 'gps'
@@ -66,3 +66,51 @@ async def test_sending_location(hass, create_registrations, webhook_client):
assert state.attributes['course'] == 6
assert state.attributes['speed'] == 7
assert state.attributes['vertical_accuracy'] == 8
async def test_restoring_location(hass, create_registrations, webhook_client):
"""Test sending a location via a webhook."""
resp = await webhook_client.post(
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
json={
'type': 'update_location',
'data': {
'gps': [10, 20],
'gps_accuracy': 30,
'battery': 40,
'altitude': 50,
'course': 60,
'speed': 70,
'vertical_accuracy': 80,
'location_name': 'bar',
}
}
)
assert resp.status == 200
await hass.async_block_till_done()
state_1 = hass.states.get('device_tracker.test_1_2')
assert state_1 is not None
config_entry = hass.config_entries.async_entries('mobile_app')[1]
# mobile app doesn't support unloading, so we just reload device tracker
await hass.config_entries.async_forward_entry_unload(config_entry,
'device_tracker')
await hass.config_entries.async_forward_entry_setup(config_entry,
'device_tracker')
state_2 = hass.states.get('device_tracker.test_1_2')
assert state_2 is not None
assert state_1 is not state_2
assert state_2.name == 'Test 1'
assert state_2.attributes['source_type'] == 'gps'
assert state_2.attributes['latitude'] == 10
assert state_2.attributes['longitude'] == 20
assert state_2.attributes['gps_accuracy'] == 30
assert state_2.attributes['battery_level'] == 40
assert state_2.attributes['altitude'] == 50
assert state_2.attributes['course'] == 60
assert state_2.attributes['speed'] == 70
assert state_2.attributes['vertical_accuracy'] == 80
@@ -1491,3 +1491,47 @@ async def test_region_mapping(hass, setup_comp):
await send_message(hass, EVENT_TOPIC, message)
assert_location_state(hass, 'inner')
async def test_restore_state(hass, hass_client):
"""Test that we can restore state."""
entry = MockConfigEntry(domain='owntracks', data={
'webhook_id': 'owntracks_test',
'secret': 'abcd',
})
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
client = await hass_client()
resp = await client.post(
'/api/webhook/owntracks_test',
json=LOCATION_MESSAGE,
headers={
'X-Limit-u': 'Paulus',
'X-Limit-d': 'Pixel',
}
)
assert resp.status == 200
await hass.async_block_till_done()
state_1 = hass.states.get('device_tracker.paulus_pixel')
assert state_1 is not None
await hass.config_entries.async_reload(entry.entry_id)
await hass.async_block_till_done()
state_2 = hass.states.get('device_tracker.paulus_pixel')
assert state_2 is not None
assert state_1 is not state_2
assert state_1.state == state_2.state
assert state_1.name == state_2.name
assert state_1.attributes['latitude'] == state_2.attributes['latitude']
assert state_1.attributes['longitude'] == state_2.attributes['longitude']
assert state_1.attributes['battery_level'] == \
state_2.attributes['battery_level']
assert state_1.attributes['source_type'] == \
state_2.attributes['source_type']