This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+140 -92
View File
@@ -4,8 +4,7 @@ import importlib
import logging
from typing import Iterable
from aiohttp.client_exceptions import (
ClientConnectionError, ClientResponseError)
from aiohttp.client_exceptions import ClientConnectionError, ClientResponseError
from pysmartapp.event import EVENT_TYPE_DEVICE
from pysmartthings import Attribute, Capability, SmartThings
@@ -14,21 +13,37 @@ from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect, async_dispatcher_send)
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from .config_flow import SmartThingsFlowHandler # noqa
from .const import (
CONF_APP_ID, CONF_INSTALLED_APP_ID, CONF_LOCATION_ID, CONF_OAUTH_CLIENT_ID,
CONF_OAUTH_CLIENT_SECRET, CONF_REFRESH_TOKEN, DATA_BROKERS, DATA_MANAGER,
DOMAIN, EVENT_BUTTON, SIGNAL_SMARTTHINGS_UPDATE, SUPPORTED_PLATFORMS,
TOKEN_REFRESH_INTERVAL)
CONF_APP_ID,
CONF_INSTALLED_APP_ID,
CONF_LOCATION_ID,
CONF_OAUTH_CLIENT_ID,
CONF_OAUTH_CLIENT_SECRET,
CONF_REFRESH_TOKEN,
DATA_BROKERS,
DATA_MANAGER,
DOMAIN,
EVENT_BUTTON,
SIGNAL_SMARTTHINGS_UPDATE,
SUPPORTED_PLATFORMS,
TOKEN_REFRESH_INTERVAL,
)
from .smartapp import (
setup_smartapp, setup_smartapp_endpoint, smartapp_sync_subscriptions,
unload_smartapp_endpoint, validate_installed_app,
validate_webhook_requirements)
setup_smartapp,
setup_smartapp_endpoint,
smartapp_sync_subscriptions,
unload_smartapp_endpoint,
validate_installed_app,
validate_webhook_requirements,
)
_LOGGER = logging.getLogger(__name__)
@@ -47,14 +62,13 @@ async def async_migrate_entry(hass: HomeAssistantType, entry: ConfigEntry):
elements. Force this by removing the entry and triggering a new flow.
"""
# Remove the entry which will invoke the callback to delete the app.
hass.async_create_task(
hass.config_entries.async_remove(entry.entry_id))
hass.async_create_task(hass.config_entries.async_remove(entry.entry_id))
# only create new flow if there isn't a pending one for SmartThings.
flows = hass.config_entries.flow.async_progress()
if not [flow for flow in flows if flow['handler'] == DOMAIN]:
if not [flow for flow in flows if flow["handler"] == DOMAIN]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={'source': 'import'}))
hass.config_entries.flow.async_init(DOMAIN, context={"source": "import"})
)
# Return False because it could not be migrated.
return False
@@ -63,12 +77,13 @@ async def async_migrate_entry(hass: HomeAssistantType, entry: ConfigEntry):
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
"""Initialize config entry which represents an installed SmartApp."""
if not validate_webhook_requirements(hass):
_LOGGER.warning("The 'base_url' of the 'http' integration must be "
"configured and start with 'https://'")
_LOGGER.warning(
"The 'base_url' of the 'http' integration must be "
"configured and start with 'https://'"
)
return False
api = SmartThings(async_get_clientsession(hass),
entry.data[CONF_ACCESS_TOKEN])
api = SmartThings(async_get_clientsession(hass), entry.data[CONF_ACCESS_TOKEN])
remove_entry = False
try:
@@ -83,7 +98,8 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
# Validate and retrieve the installed app.
installed_app = await validate_installed_app(
api, entry.data[CONF_INSTALLED_APP_ID])
api, entry.data[CONF_INSTALLED_APP_ID]
)
# Get scenes
scenes = await async_get_entry_scenes(entry, api)
@@ -92,30 +108,37 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
token = await api.generate_tokens(
entry.data[CONF_OAUTH_CLIENT_ID],
entry.data[CONF_OAUTH_CLIENT_SECRET],
entry.data[CONF_REFRESH_TOKEN])
entry.data[CONF_REFRESH_TOKEN],
)
entry.data[CONF_REFRESH_TOKEN] = token.refresh_token
hass.config_entries.async_update_entry(entry)
# Get devices and their current status
devices = await api.devices(
location_ids=[installed_app.location_id])
devices = await api.devices(location_ids=[installed_app.location_id])
async def retrieve_device_status(device):
try:
await device.status.refresh()
except ClientResponseError:
_LOGGER.debug("Unable to update status for device: %s (%s), "
"the device will be excluded",
device.label, device.device_id, exc_info=True)
_LOGGER.debug(
"Unable to update status for device: %s (%s), "
"the device will be excluded",
device.label,
device.device_id,
exc_info=True,
)
devices.remove(device)
await asyncio.gather(*(retrieve_device_status(d)
for d in devices.copy()))
await asyncio.gather(*(retrieve_device_status(d) for d in devices.copy()))
# Sync device subscriptions
await smartapp_sync_subscriptions(
hass, token.access_token, installed_app.location_id,
installed_app.installed_app_id, devices)
hass,
token.access_token,
installed_app.location_id,
installed_app.installed_app_id,
devices,
)
# Setup device broker
broker = DeviceBroker(hass, entry, token, smart_app, devices, scenes)
@@ -124,8 +147,11 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
except ClientResponseError as ex:
if ex.status in (401, 403):
_LOGGER.exception("Unable to setup config entry '%s' - please "
"reconfigure the integration", entry.title)
_LOGGER.exception(
"Unable to setup config entry '%s' - please "
"reconfigure the integration",
entry.title,
)
remove_entry = True
else:
_LOGGER.debug(ex, exc_info=True)
@@ -135,19 +161,21 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
raise ConfigEntryNotReady
if remove_entry:
hass.async_create_task(
hass.config_entries.async_remove(entry.entry_id))
hass.async_create_task(hass.config_entries.async_remove(entry.entry_id))
# only create new flow if there isn't a pending one for SmartThings.
flows = hass.config_entries.flow.async_progress()
if not [flow for flow in flows if flow['handler'] == DOMAIN]:
if not [flow for flow in flows if flow["handler"] == DOMAIN]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={'source': 'import'}))
DOMAIN, context={"source": "import"}
)
)
return False
for component in SUPPORTED_PLATFORMS:
hass.async_create_task(hass.config_entries.async_forward_entry_setup(
entry, component))
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True
@@ -157,9 +185,12 @@ async def async_get_entry_scenes(entry: ConfigEntry, api):
return await api.scenes(location_id=entry.data[CONF_LOCATION_ID])
except ClientResponseError as ex:
if ex.status == 403:
_LOGGER.exception("Unable to load scenes for config entry '%s' "
"because the access token does not have the "
"required access", entry.title)
_LOGGER.exception(
"Unable to load scenes for config entry '%s' "
"because the access token does not have the "
"required access",
entry.title,
)
else:
raise
return []
@@ -171,16 +202,16 @@ async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):
if broker:
broker.disconnect()
tasks = [hass.config_entries.async_forward_entry_unload(entry, component)
for component in SUPPORTED_PLATFORMS]
tasks = [
hass.config_entries.async_forward_entry_unload(entry, component)
for component in SUPPORTED_PLATFORMS
]
return all(await asyncio.gather(*tasks))
async def async_remove_entry(
hass: HomeAssistantType, entry: ConfigEntry) -> None:
async def async_remove_entry(hass: HomeAssistantType, entry: ConfigEntry) -> None:
"""Perform clean-up when entry is being removed."""
api = SmartThings(async_get_clientsession(hass),
entry.data[CONF_ACCESS_TOKEN])
api = SmartThings(async_get_clientsession(hass), entry.data[CONF_ACCESS_TOKEN])
# Remove the installed_app, which if already removed raises a 403 error.
installed_app_id = entry.data[CONF_INSTALLED_APP_ID]
@@ -188,8 +219,11 @@ async def async_remove_entry(
await api.delete_installed_app(installed_app_id)
except ClientResponseError as ex:
if ex.status == 403:
_LOGGER.debug("Installed app %s has already been removed",
installed_app_id, exc_info=True)
_LOGGER.debug(
"Installed app %s has already been removed",
installed_app_id,
exc_info=True,
)
else:
raise
_LOGGER.debug("Removed installed app %s", installed_app_id)
@@ -198,19 +232,19 @@ async def async_remove_entry(
# removed raises a 403 error.
all_entries = hass.config_entries.async_entries(DOMAIN)
app_id = entry.data[CONF_APP_ID]
app_count = sum(1 for entry in all_entries
if entry.data[CONF_APP_ID] == app_id)
app_count = sum(1 for entry in all_entries if entry.data[CONF_APP_ID] == app_id)
if app_count > 1:
_LOGGER.debug("App %s was not removed because it is in use by other"
"config entries", app_id)
_LOGGER.debug(
"App %s was not removed because it is in use by other" "config entries",
app_id,
)
return
# Remove the app
try:
await api.delete_app(app_id)
except ClientResponseError as ex:
if ex.status == 403:
_LOGGER.debug("App %s has already been removed",
app_id, exc_info=True)
_LOGGER.debug("App %s has already been removed", app_id, exc_info=True)
else:
raise
_LOGGER.debug("Removed app %s", app_id)
@@ -222,8 +256,15 @@ async def async_remove_entry(
class DeviceBroker:
"""Manages an individual SmartThings config entry."""
def __init__(self, hass: HomeAssistantType, entry: ConfigEntry,
token, smart_app, devices: Iterable, scenes: Iterable):
def __init__(
self,
hass: HomeAssistantType,
entry: ConfigEntry,
token,
smart_app,
devices: Iterable,
scenes: Iterable,
):
"""Create a new instance of the DeviceBroker."""
self._hass = hass
self._entry = entry
@@ -243,9 +284,8 @@ class DeviceBroker:
capabilities = device.capabilities.copy()
slots = {}
for platform_name in SUPPORTED_PLATFORMS:
platform = importlib.import_module(
'.' + platform_name, self.__module__)
if not hasattr(platform, 'get_capabilities'):
platform = importlib.import_module("." + platform_name, self.__module__)
if not hasattr(platform, "get_capabilities"):
continue
assigned = platform.get_capabilities(capabilities)
if not assigned:
@@ -267,18 +307,21 @@ class DeviceBroker:
"""Generate a new refresh token and update the config entry."""
await self._token.refresh(
self._entry.data[CONF_OAUTH_CLIENT_ID],
self._entry.data[CONF_OAUTH_CLIENT_SECRET])
self._entry.data[CONF_OAUTH_CLIENT_SECRET],
)
self._entry.data[CONF_REFRESH_TOKEN] = self._token.refresh_token
self._hass.config_entries.async_update_entry(self._entry)
_LOGGER.debug('Regenerated refresh token for installed app: %s',
self._installed_app_id)
_LOGGER.debug(
"Regenerated refresh token for installed app: %s",
self._installed_app_id,
)
self._regenerate_token_remove = async_track_time_interval(
self._hass, regenerate_refresh_token, TOKEN_REFRESH_INTERVAL)
self._hass, regenerate_refresh_token, TOKEN_REFRESH_INTERVAL
)
# Connect handler to incoming device events
self._event_disconnect = \
self._smart_app.connect_event(self._event_handler)
self._event_disconnect = self._smart_app.connect_event(self._event_handler)
def disconnect(self):
"""Disconnects handlers/listeners for device/lifecycle events."""
@@ -312,38 +355,43 @@ class DeviceBroker:
if not device:
continue
device.status.apply_attribute_update(
evt.component_id, evt.capability, evt.attribute, evt.value,
data=evt.data)
evt.component_id,
evt.capability,
evt.attribute,
evt.value,
data=evt.data,
)
# Fire events for buttons
if evt.capability == Capability.button and \
evt.attribute == Attribute.button:
if (
evt.capability == Capability.button
and evt.attribute == Attribute.button
):
data = {
'component_id': evt.component_id,
'device_id': evt.device_id,
'location_id': evt.location_id,
'value': evt.value,
'name': device.label,
'data': evt.data
"component_id": evt.component_id,
"device_id": evt.device_id,
"location_id": evt.location_id,
"value": evt.value,
"name": device.label,
"data": evt.data,
}
self._hass.bus.async_fire(EVENT_BUTTON, data)
_LOGGER.debug("Fired button event: %s", data)
else:
data = {
'location_id': evt.location_id,
'device_id': evt.device_id,
'component_id': evt.component_id,
'capability': evt.capability,
'attribute': evt.attribute,
'value': evt.value,
'data': evt.data
"location_id": evt.location_id,
"device_id": evt.device_id,
"component_id": evt.component_id,
"capability": evt.capability,
"attribute": evt.attribute,
"value": evt.value,
"data": evt.data,
}
_LOGGER.debug("Push update received: %s", data)
updated_devices.add(device.device_id)
async_dispatcher_send(self._hass, SIGNAL_SMARTTHINGS_UPDATE,
updated_devices)
async_dispatcher_send(self._hass, SIGNAL_SMARTTHINGS_UPDATE, updated_devices)
class SmartThingsEntity(Entity):
@@ -356,13 +404,15 @@ class SmartThingsEntity(Entity):
async def async_added_to_hass(self):
"""Device added to hass."""
async def async_update_state(devices):
"""Update device state."""
if self._device.device_id in devices:
await self.async_update_ha_state(True)
self._dispatcher_remove = async_dispatcher_connect(
self.hass, SIGNAL_SMARTTHINGS_UPDATE, async_update_state)
self.hass, SIGNAL_SMARTTHINGS_UPDATE, async_update_state
)
async def async_will_remove_from_hass(self) -> None:
"""Disconnect the device when removed."""
@@ -373,12 +423,10 @@ class SmartThingsEntity(Entity):
def device_info(self):
"""Get attributes about the device."""
return {
'identifiers': {
(DOMAIN, self._device.device_id)
},
'name': self._device.label,
'model': self._device.device_type_name,
'manufacturer': 'Unavailable'
"identifiers": {(DOMAIN, self._device.device_id)},
"name": self._device.label,
"model": self._device.device_type_name,
"manufacturer": "Unavailable",
}
@property