Mobile app device tracker to restore state (#24266)

This commit is contained in:
Paulus Schoutsen 2019-06-03 01:30:56 -07:00 committed by Pascal Vizeli
parent d2d3f27f85
commit 5f3bcedbba
4 changed files with 106 additions and 30 deletions

View File

@ -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,
}

View File

@ -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'

View File

@ -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."""

View File

@ -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