Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESPHome Native API Restore Entities on startup #19379

Merged
merged 2 commits into from
Dec 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion homeassistant/components/esphome/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from homeassistant.helpers.dispatcher import async_dispatcher_connect, \
async_dispatcher_send
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.json import JSONEncoder
from homeassistant.helpers.storage import Store
from homeassistant.helpers.typing import HomeAssistantType, ConfigType

# Import config flow so that it's added to the registry
Expand All @@ -30,6 +32,10 @@
DISPATCHER_ON_LIST = 'esphome_{entry_id}_on_list'
DISPATCHER_ON_DEVICE_UPDATE = 'esphome_{entry_id}_on_device_update'
DISPATCHER_ON_STATE = 'esphome_{entry_id}_on_state'

STORAGE_KEY = 'esphome.{}'
STORAGE_VERSION = 1

# The HA component types this integration supports
HA_COMPONENTS = ['sensor']

Expand All @@ -45,6 +51,7 @@ class RuntimeEntryData:

entry_id = attr.ib(type=str)
client = attr.ib(type='APIClient')
store = attr.ib(type=Store)
reconnect_task = attr.ib(type=Optional[asyncio.Task], default=None)
state = attr.ib(type=Dict[str, Dict[str, Any]], factory=dict)
info = attr.ib(type=Dict[str, Dict[str, Any]], factory=dict)
Expand Down Expand Up @@ -83,6 +90,42 @@ def async_update_device_state(self, hass: HomeAssistantType) -> None:
signal = DISPATCHER_ON_DEVICE_UPDATE.format(entry_id=self.entry_id)
async_dispatcher_send(hass, signal)

async def async_load_from_store(self) -> List['EntityInfo']:
"""Load the retained data from store and return de-serialized data."""
# pylint: disable= redefined-outer-name
from aioesphomeapi import COMPONENT_TYPE_TO_INFO, DeviceInfo
OttoWinter marked this conversation as resolved.
Show resolved Hide resolved

restored = await self.store.async_load()
if restored is None:
return []

self.device_info = _attr_obj_from_dict(DeviceInfo,
**restored.pop('device_info'))
infos = []
for comp_type, restored_infos in restored.items():
if comp_type not in COMPONENT_TYPE_TO_INFO:
continue
for info in restored_infos:
cls = COMPONENT_TYPE_TO_INFO[comp_type]
infos.append(_attr_obj_from_dict(cls, **info))
return infos

async def async_save_to_store(self) -> None:
"""Generate dynamic data to store and save it to the filesystem."""
store_data = {
'device_info': attr.asdict(self.device_info)
}

for comp_type, infos in self.info.items():
store_data[comp_type] = [attr.asdict(info)
for info in infos.values()]

await self.store.async_save(store_data)


def _attr_obj_from_dict(cls, **kwargs):
return cls(**{key: kwargs[key] for key in attr.fields_dict(cls)})


async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Stub to allow setting up this component.
Expand All @@ -108,9 +151,12 @@ async def async_setup_entry(hass: HomeAssistantType,
await cli.start()

# Store client in per-config-entry hass.data
store = Store(hass, STORAGE_VERSION, STORAGE_KEY.format(entry.entry_id),
encoder=JSONEncoder)
entry_data = hass.data[DOMAIN][entry.entry_id] = RuntimeEntryData(
client=cli,
entry_id=entry.entry_id
entry_id=entry.entry_id,
store=store,
)

async def on_stop(event: Event) -> None:
Expand Down Expand Up @@ -138,6 +184,8 @@ async def on_login() -> None:
entity_infos = await cli.list_entities()
entry_data.async_update_static_infos(hass, entity_infos)
await cli.subscribe_states(async_on_state)

hass.async_create_task(entry_data.async_save_to_store())
except APIConnectionError as err:
_LOGGER.warning("Error getting initial data: %s", err)
# Re-connection logic will trigger after this
Expand Down Expand Up @@ -173,6 +221,9 @@ async def complete_setup() -> None:
entry, component))
await asyncio.wait(tasks)

infos = await entry_data.async_load_from_store()
entry_data.async_update_static_infos(hass, infos)

# If first connect fails, the next re-connect will be scheduled
# outside of _pending_task, in order not to delay HA startup
# indefinitely
Expand Down