Add SmartThings component and switch platform (#20148)
* Added SmartThings component and switch platform * Corrected comment typos. * Embedded switch platform. * Replaced custom view usage with webhook component. * Replaced urls with tokens in strings. * Fixed line length. * Use generated webhook id instead of static one. * Reuse core constant instead of defining again. * Optimizations in anticipation of future platforms. * Use async_generate_path instead of hard-coded path. * Fixed line length. * Updates per review feedback. * Updates per latest review feedback.
This commit is contained in:
1 parent
5a0c707a37
commit
69ec7980ad
18 files changed
+1793
No files matched your search
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "SmartThings",
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Enter Personal Access Token",
|
||||
"description": "Please enter a SmartThings [Personal Access Token]({token_url}) that has been created per the [instructions]({component_url}).",
|
||||
"data": {
|
||||
"access_token": "Access Token"
|
||||
}
|
||||
},
|
||||
"wait_install": {
|
||||
"title": "Install SmartApp",
|
||||
"description": "Please install the Home Assistant SmartApp in at least one location and click submit."
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"token_invalid_format": "The token must be in the UID/GUID format",
|
||||
"token_unauthorized": "The token is invalid or no longer authorized.",
|
||||
"token_forbidden": "The token does not have the required OAuth scopes.",
|
||||
"token_already_setup": "The token has already been setup.",
|
||||
"app_setup_error": "Unable to setup the SmartApp. Please try again.",
|
||||
"app_not_installed": "Please ensure you have installed and authorized the Home Assistant SmartApp and try again.",
|
||||
"base_url_not_https": "The `base_url` for the `http` component must be configured and start with `https://`."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
"""SmartThings Cloud integration for Home Assistant."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Iterable
|
||||
|
||||
from aiohttp.client_exceptions import (
|
||||
ClientConnectionError, ClientResponseError)
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
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)
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
|
||||
|
||||
from .config_flow import SmartThingsFlowHandler # noqa
|
||||
from .const import (
|
||||
CONF_APP_ID, CONF_INSTALLED_APP_ID, DATA_BROKERS, DATA_MANAGER, DOMAIN,
|
||||
SIGNAL_SMARTTHINGS_UPDATE, SUPPORTED_PLATFORMS)
|
||||
from .smartapp import (
|
||||
setup_smartapp, setup_smartapp_endpoint, validate_installed_app)
|
||||
|
||||
REQUIREMENTS = ['pysmartapp==0.3.0', 'pysmartthings==0.4.2']
|
||||
DEPENDENCIES = ['webhook']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistantType, config: ConfigType):
|
||||
"""Initialize the SmartThings platform."""
|
||||
await setup_smartapp_endpoint(hass)
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
|
||||
"""Initialize config entry which represents an installed SmartApp."""
|
||||
from pysmartthings import SmartThings
|
||||
|
||||
if not hass.config.api.base_url.lower().startswith('https://'):
|
||||
_LOGGER.warning("The 'base_url' of the 'http' component must be "
|
||||
"configured and start with 'https://'")
|
||||
return False
|
||||
|
||||
api = SmartThings(async_get_clientsession(hass),
|
||||
entry.data[CONF_ACCESS_TOKEN])
|
||||
|
||||
remove_entry = False
|
||||
try:
|
||||
# See if the app is already setup. This occurs when there are
|
||||
# installs in multiple SmartThings locations (valid use-case)
|
||||
manager = hass.data[DOMAIN][DATA_MANAGER]
|
||||
smart_app = manager.smartapps.get(entry.data[CONF_APP_ID])
|
||||
if not smart_app:
|
||||
# Validate and setup the app.
|
||||
app = await api.app(entry.data[CONF_APP_ID])
|
||||
smart_app = setup_smartapp(hass, app)
|
||||
|
||||
# Validate and retrieve the installed app.
|
||||
installed_app = await validate_installed_app(
|
||||
api, entry.data[CONF_INSTALLED_APP_ID])
|
||||
|
||||
# Get devices and their current status
|
||||
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 ignored",
|
||||
device.label, device.device_id, exc_info=True)
|
||||
devices.remove(device)
|
||||
|
||||
await asyncio.gather(*[retrieve_device_status(d)
|
||||
for d in devices.copy()])
|
||||
|
||||
# Setup device broker
|
||||
broker = DeviceBroker(hass, devices,
|
||||
installed_app.installed_app_id)
|
||||
broker.event_handler_disconnect = \
|
||||
smart_app.connect_event(broker.event_handler)
|
||||
hass.data[DOMAIN][DATA_BROKERS][entry.entry_id] = broker
|
||||
|
||||
except ClientResponseError as ex:
|
||||
if ex.status in (401, 403):
|
||||
_LOGGER.exception("Unable to setup config entry '%s' - please "
|
||||
"reconfigure the integration", entry.title)
|
||||
remove_entry = True
|
||||
else:
|
||||
_LOGGER.debug(ex, exc_info=True)
|
||||
raise ConfigEntryNotReady
|
||||
except (ClientConnectionError, RuntimeWarning) as ex:
|
||||
_LOGGER.debug(ex, exc_info=True)
|
||||
raise ConfigEntryNotReady
|
||||
|
||||
if remove_entry:
|
||||
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]:
|
||||
hass.async_create_task(
|
||||
hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'import'}))
|
||||
return False
|
||||
|
||||
for component in SUPPORTED_PLATFORMS:
|
||||
hass.async_create_task(hass.config_entries.async_forward_entry_setup(
|
||||
entry, component))
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):
|
||||
"""Unload a config entry."""
|
||||
broker = hass.data[DOMAIN][DATA_BROKERS].pop(entry.entry_id, None)
|
||||
if broker and broker.event_handler_disconnect:
|
||||
broker.event_handler_disconnect()
|
||||
|
||||
tasks = [hass.config_entries.async_forward_entry_unload(entry, component)
|
||||
for component in SUPPORTED_PLATFORMS]
|
||||
return all(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
class DeviceBroker:
|
||||
"""Manages an individual SmartThings config entry."""
|
||||
|
||||
def __init__(self, hass: HomeAssistantType, devices: Iterable,
|
||||
installed_app_id: str):
|
||||
"""Create a new instance of the DeviceBroker."""
|
||||
self._hass = hass
|
||||
self._installed_app_id = installed_app_id
|
||||
self.devices = {device.device_id: device for device in devices}
|
||||
self.event_handler_disconnect = None
|
||||
|
||||
async def event_handler(self, req, resp, app):
|
||||
"""Broker for incoming events."""
|
||||
from pysmartapp.event import EVENT_TYPE_DEVICE
|
||||
|
||||
# Do not process events received from a different installed app
|
||||
# under the same parent SmartApp (valid use-scenario)
|
||||
if req.installed_app_id != self._installed_app_id:
|
||||
return
|
||||
|
||||
updated_devices = set()
|
||||
for evt in req.events:
|
||||
if evt.event_type != EVENT_TYPE_DEVICE:
|
||||
continue
|
||||
device = self.devices.get(evt.device_id)
|
||||
if not device:
|
||||
continue
|
||||
device.status.apply_attribute_update(
|
||||
evt.component_id, evt.capability, evt.attribute, evt.value)
|
||||
updated_devices.add(device.device_id)
|
||||
_LOGGER.debug("Update received with %s events and updated %s devices",
|
||||
len(req.events), len(updated_devices))
|
||||
|
||||
async_dispatcher_send(self._hass, SIGNAL_SMARTTHINGS_UPDATE,
|
||||
updated_devices)
|
||||
|
||||
|
||||
class SmartThingsEntity(Entity):
|
||||
"""Defines a SmartThings entity."""
|
||||
|
||||
def __init__(self, device):
|
||||
"""Initialize the instance."""
|
||||
self._device = device
|
||||
self._dispatcher_remove = None
|
||||
|
||||
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)
|
||||
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Disconnect the device when removed."""
|
||||
if self._dispatcher_remove:
|
||||
self._dispatcher_remove()
|
||||
|
||||
@property
|
||||
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'
|
||||
}
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Return the name of the device."""
|
||||
return self._device.label
|
||||
|
||||
@property
|
||||
def should_poll(self) -> bool:
|
||||
"""No polling needed for this device."""
|
||||
return False
|
||||
|
||||
@property
|
||||
def unique_id(self) -> str:
|
||||
"""Return a unique ID."""
|
||||
return self._device.device_id
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Config flow to configure SmartThings."""
|
||||
import logging
|
||||
|
||||
from aiohttp.client_exceptions import ClientResponseError
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from .const import (
|
||||
CONF_APP_ID, CONF_INSTALLED_APP_ID, CONF_LOCATION_ID, DOMAIN,
|
||||
VAL_UID_MATCHER)
|
||||
from .smartapp import (
|
||||
create_app, find_app, setup_smartapp, setup_smartapp_endpoint, update_app)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@config_entries.HANDLERS.register(DOMAIN)
|
||||
class SmartThingsFlowHandler(config_entries.ConfigFlow):
|
||||
"""
|
||||
Handle configuration of SmartThings integrations.
|
||||
|
||||
Any number of integrations are supported. The high level flow follows:
|
||||
1) Flow initiated
|
||||
a) User initiates through the UI
|
||||
b) Re-configuration of a failed entry setup
|
||||
2) Enter access token
|
||||
a) Check not already setup
|
||||
b) Validate format
|
||||
c) Setup SmartApp
|
||||
3) Wait for Installation
|
||||
a) Check user installed into one or more locations
|
||||
b) Config entries setup for all installations
|
||||
"""
|
||||
|
||||
VERSION = 1
|
||||
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_PUSH
|
||||
|
||||
def __init__(self):
|
||||
"""Create a new instance of the flow handler."""
|
||||
self.access_token = None
|
||||
self.app_id = None
|
||||
self.api = None
|
||||
|
||||
async def async_step_import(self, user_input=None):
|
||||
"""Occurs when a previously entry setup fails and is re-initiated."""
|
||||
return await self.async_step_user(user_input)
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Get access token and validate it."""
|
||||
from pysmartthings import SmartThings
|
||||
|
||||
errors = {}
|
||||
if not self.hass.config.api.base_url.lower().startswith('https://'):
|
||||
errors['base'] = "base_url_not_https"
|
||||
return self._show_step_user(errors)
|
||||
|
||||
if user_input is None or CONF_ACCESS_TOKEN not in user_input:
|
||||
return self._show_step_user(errors)
|
||||
|
||||
self.access_token = user_input.get(CONF_ACCESS_TOKEN, '')
|
||||
self.api = SmartThings(async_get_clientsession(self.hass),
|
||||
self.access_token)
|
||||
|
||||
# Ensure token is a UUID
|
||||
if not VAL_UID_MATCHER.match(self.access_token):
|
||||
errors[CONF_ACCESS_TOKEN] = "token_invalid_format"
|
||||
return self._show_step_user(errors)
|
||||
# Check not already setup in another entry
|
||||
if any(entry.data.get(CONF_ACCESS_TOKEN) == self.access_token
|
||||
for entry
|
||||
in self.hass.config_entries.async_entries(DOMAIN)):
|
||||
errors[CONF_ACCESS_TOKEN] = "token_already_setup"
|
||||
return self._show_step_user(errors)
|
||||
|
||||
# Setup end-point
|
||||
await setup_smartapp_endpoint(self.hass)
|
||||
|
||||
try:
|
||||
app = await find_app(self.hass, self.api)
|
||||
if app:
|
||||
await app.refresh() # load all attributes
|
||||
await update_app(self.hass, app)
|
||||
else:
|
||||
app = await create_app(self.hass, self.api)
|
||||
setup_smartapp(self.hass, app)
|
||||
self.app_id = app.app_id
|
||||
except ClientResponseError as ex:
|
||||
if ex.status == 401:
|
||||
errors[CONF_ACCESS_TOKEN] = "token_unauthorized"
|
||||
elif ex.status == 403:
|
||||
errors[CONF_ACCESS_TOKEN] = "token_forbidden"
|
||||
else:
|
||||
errors['base'] = "app_setup_error"
|
||||
return self._show_step_user(errors)
|
||||
except Exception: # pylint:disable=broad-except
|
||||
errors['base'] = "app_setup_error"
|
||||
_LOGGER.exception("Unexpected error setting up the SmartApp")
|
||||
return self._show_step_user(errors)
|
||||
|
||||
return await self.async_step_wait_install()
|
||||
|
||||
async def async_step_wait_install(self, user_input=None):
|
||||
"""Wait for SmartApp installation."""
|
||||
from pysmartthings import InstalledAppStatus
|
||||
|
||||
errors = {}
|
||||
if user_input is None:
|
||||
return self._show_step_wait_install(errors)
|
||||
|
||||
# Find installed apps that were authorized
|
||||
installed_apps = [app for app in await self.api.installed_apps(
|
||||
installed_app_status=InstalledAppStatus.AUTHORIZED)
|
||||
if app.app_id == self.app_id]
|
||||
if not installed_apps:
|
||||
errors['base'] = 'app_not_installed'
|
||||
return self._show_step_wait_install(errors)
|
||||
|
||||
# User may have installed the SmartApp in more than one SmartThings
|
||||
# location. Config flows are created for the additional installations
|
||||
for installed_app in installed_apps[1:]:
|
||||
self.hass.async_create_task(
|
||||
self.hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'install'},
|
||||
data={
|
||||
CONF_APP_ID: installed_app.app_id,
|
||||
CONF_INSTALLED_APP_ID: installed_app.installed_app_id,
|
||||
CONF_LOCATION_ID: installed_app.location_id,
|
||||
CONF_ACCESS_TOKEN: self.access_token
|
||||
}))
|
||||
|
||||
# return entity for the first one.
|
||||
installed_app = installed_apps[0]
|
||||
return await self.async_step_install({
|
||||
CONF_APP_ID: installed_app.app_id,
|
||||
CONF_INSTALLED_APP_ID: installed_app.installed_app_id,
|
||||
CONF_LOCATION_ID: installed_app.location_id,
|
||||
CONF_ACCESS_TOKEN: self.access_token
|
||||
})
|
||||
|
||||
def _show_step_user(self, errors):
|
||||
return self.async_show_form(
|
||||
step_id='user',
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(CONF_ACCESS_TOKEN,
|
||||
default=self.access_token): str
|
||||
}),
|
||||
errors=errors,
|
||||
description_placeholders={
|
||||
'token_url': 'https://account.smartthings.com/tokens',
|
||||
'component_url':
|
||||
'https://www.home-assistant.io/components/smartthings/'
|
||||
}
|
||||
)
|
||||
|
||||
def _show_step_wait_install(self, errors):
|
||||
return self.async_show_form(
|
||||
step_id='wait_install',
|
||||
errors=errors
|
||||
)
|
||||
|
||||
async def async_step_install(self, data=None):
|
||||
"""
|
||||
Create a config entry at completion of a flow.
|
||||
|
||||
Launched when the user completes the flow or when the SmartApp
|
||||
is installed into an additional location.
|
||||
"""
|
||||
from pysmartthings import SmartThings
|
||||
|
||||
if not self.api:
|
||||
# Launched from the SmartApp install event handler
|
||||
self.api = SmartThings(
|
||||
async_get_clientsession(self.hass), data[CONF_ACCESS_TOKEN])
|
||||
|
||||
location = await self.api.location(data[CONF_LOCATION_ID])
|
||||
return self.async_create_entry(title=location.name, data=data)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Constants used by the SmartThings component and platforms."""
|
||||
import re
|
||||
|
||||
APP_OAUTH_SCOPES = [
|
||||
'r:devices:*'
|
||||
]
|
||||
APP_NAME_PREFIX = 'homeassistant.'
|
||||
CONF_APP_ID = 'app_id'
|
||||
CONF_INSTALLED_APP_ID = 'installed_app_id'
|
||||
CONF_INSTANCE_ID = 'instance_id'
|
||||
CONF_LOCATION_ID = 'location_id'
|
||||
DATA_MANAGER = 'manager'
|
||||
DATA_BROKERS = 'brokers'
|
||||
DOMAIN = 'smartthings'
|
||||
SIGNAL_SMARTTHINGS_UPDATE = 'smartthings_update'
|
||||
SIGNAL_SMARTAPP_PREFIX = 'smartthings_smartap_'
|
||||
SETTINGS_INSTANCE_ID = "hassInstanceId"
|
||||
STORAGE_KEY = DOMAIN
|
||||
STORAGE_VERSION = 1
|
||||
SUPPORTED_PLATFORMS = [
|
||||
'switch'
|
||||
]
|
||||
SUPPORTED_CAPABILITIES = [
|
||||
'colorControl',
|
||||
'colorTemperature',
|
||||
'switch',
|
||||
'switchLevel'
|
||||
]
|
||||
VAL_UID = "^(?:([0-9a-fA-F]{32})|([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]" \
|
||||
"{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}))$"
|
||||
VAL_UID_MATCHER = re.compile(VAL_UID)
|
||||
@@ -0,0 +1,275 @@
|
||||
"""
|
||||
SmartApp functionality to receive cloud-push notifications.
|
||||
|
||||
This module defines the functions to manage the SmartApp integration
|
||||
within the SmartThings ecosystem in order to receive real-time webhook-based
|
||||
callbacks when device states change.
|
||||
"""
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
from uuid import uuid4
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from homeassistant.components import webhook
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_WEBHOOK_ID
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.dispatcher import (
|
||||
async_dispatcher_connect, async_dispatcher_send)
|
||||
from homeassistant.helpers.typing import HomeAssistantType
|
||||
|
||||
from .const import (
|
||||
APP_NAME_PREFIX, APP_OAUTH_SCOPES, CONF_APP_ID, CONF_INSTALLED_APP_ID,
|
||||
CONF_INSTANCE_ID, CONF_LOCATION_ID, DATA_BROKERS, DATA_MANAGER, DOMAIN,
|
||||
SETTINGS_INSTANCE_ID, SIGNAL_SMARTAPP_PREFIX, STORAGE_KEY, STORAGE_VERSION,
|
||||
SUPPORTED_CAPABILITIES)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def find_app(hass: HomeAssistantType, api):
|
||||
"""Find an existing SmartApp for this installation of hass."""
|
||||
apps = await api.apps()
|
||||
for app in [app for app in apps
|
||||
if app.app_name.startswith(APP_NAME_PREFIX)]:
|
||||
# Load settings to compare instance id
|
||||
settings = await app.settings()
|
||||
if settings.settings.get(SETTINGS_INSTANCE_ID) == \
|
||||
hass.data[DOMAIN][CONF_INSTANCE_ID]:
|
||||
return app
|
||||
|
||||
|
||||
async def validate_installed_app(api, installed_app_id: str):
|
||||
"""
|
||||
Ensure the specified installed SmartApp is valid and functioning.
|
||||
|
||||
Query the API for the installed SmartApp and validate that it is tied to
|
||||
the specified app_id and is in an authorized state.
|
||||
"""
|
||||
from pysmartthings import InstalledAppStatus
|
||||
|
||||
installed_app = await api.installed_app(installed_app_id)
|
||||
if installed_app.installed_app_status != InstalledAppStatus.AUTHORIZED:
|
||||
raise RuntimeWarning("Installed SmartApp instance '{}' ({}) is not "
|
||||
"AUTHORIZED but instead {}"
|
||||
.format(installed_app.display_name,
|
||||
installed_app.installed_app_id,
|
||||
installed_app.installed_app_status))
|
||||
return installed_app
|
||||
|
||||
|
||||
def _get_app_template(hass: HomeAssistantType):
|
||||
from pysmartthings import APP_TYPE_WEBHOOK, CLASSIFICATION_AUTOMATION
|
||||
|
||||
return {
|
||||
'app_name': APP_NAME_PREFIX + str(uuid4()),
|
||||
'display_name': 'Home Assistant',
|
||||
'description': "Home Assistant at " + hass.config.api.base_url,
|
||||
'webhook_target_url': webhook.async_generate_url(
|
||||
hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]),
|
||||
'app_type': APP_TYPE_WEBHOOK,
|
||||
'single_instance': True,
|
||||
'classifications': [CLASSIFICATION_AUTOMATION]
|
||||
}
|
||||
|
||||
|
||||
async def create_app(hass: HomeAssistantType, api):
|
||||
"""Create a SmartApp for this instance of hass."""
|
||||
from pysmartthings import App, AppOAuth, AppSettings
|
||||
from pysmartapp.const import SETTINGS_APP_ID
|
||||
|
||||
# Create app from template attributes
|
||||
template = _get_app_template(hass)
|
||||
app = App()
|
||||
for key, value in template.items():
|
||||
setattr(app, key, value)
|
||||
app = (await api.create_app(app))[0]
|
||||
_LOGGER.debug("Created SmartApp '%s' (%s)", app.app_name, app.app_id)
|
||||
|
||||
# Set unique hass id in settings
|
||||
settings = AppSettings(app.app_id)
|
||||
settings.settings[SETTINGS_APP_ID] = app.app_id
|
||||
settings.settings[SETTINGS_INSTANCE_ID] = \
|
||||
hass.data[DOMAIN][CONF_INSTANCE_ID]
|
||||
await api.update_app_settings(settings)
|
||||
_LOGGER.debug("Updated App Settings for SmartApp '%s' (%s)",
|
||||
app.app_name, app.app_id)
|
||||
|
||||
# Set oauth scopes
|
||||
oauth = AppOAuth(app.app_id)
|
||||
oauth.client_name = 'Home Assistant'
|
||||
oauth.scope.extend(APP_OAUTH_SCOPES)
|
||||
await api.update_app_oauth(oauth)
|
||||
_LOGGER.debug("Updated App OAuth for SmartApp '%s' (%s)",
|
||||
app.app_name, app.app_id)
|
||||
return app
|
||||
|
||||
|
||||
async def update_app(hass: HomeAssistantType, app):
|
||||
"""Ensure the SmartApp is up-to-date and update if necessary."""
|
||||
template = _get_app_template(hass)
|
||||
template.pop('app_name') # don't update this
|
||||
update_required = False
|
||||
for key, value in template.items():
|
||||
if getattr(app, key) != value:
|
||||
update_required = True
|
||||
setattr(app, key, value)
|
||||
if update_required:
|
||||
await app.save()
|
||||
_LOGGER.debug("SmartApp '%s' (%s) updated with latest settings",
|
||||
app.app_name, app.app_id)
|
||||
|
||||
|
||||
def setup_smartapp(hass, app):
|
||||
"""
|
||||
Configure an individual SmartApp in hass.
|
||||
|
||||
Register the SmartApp with the SmartAppManager so that hass will service
|
||||
lifecycle events (install, event, etc...). A unique SmartApp is created
|
||||
for each SmartThings account that is configured in hass.
|
||||
"""
|
||||
manager = hass.data[DOMAIN][DATA_MANAGER]
|
||||
smartapp = manager.smartapps.get(app.app_id)
|
||||
if smartapp:
|
||||
# already setup
|
||||
return smartapp
|
||||
smartapp = manager.register(app.app_id, app.webhook_public_key)
|
||||
smartapp.name = app.display_name
|
||||
smartapp.description = app.description
|
||||
smartapp.permissions.extend(APP_OAUTH_SCOPES)
|
||||
return smartapp
|
||||
|
||||
|
||||
async def setup_smartapp_endpoint(hass: HomeAssistantType):
|
||||
"""
|
||||
Configure the SmartApp webhook in hass.
|
||||
|
||||
SmartApps are an extension point within the SmartThings ecosystem and
|
||||
is used to receive push updates (i.e. device updates) from the cloud.
|
||||
"""
|
||||
from pysmartapp import Dispatcher, SmartAppManager
|
||||
|
||||
data = hass.data.get(DOMAIN)
|
||||
if data:
|
||||
# already setup
|
||||
return
|
||||
|
||||
# Get/create config to store a unique id for this hass instance.
|
||||
store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
|
||||
config = await store.async_load()
|
||||
if not config:
|
||||
# Create config
|
||||
config = {
|
||||
CONF_INSTANCE_ID: str(uuid4()),
|
||||
CONF_WEBHOOK_ID: webhook.generate_secret()
|
||||
}
|
||||
await store.async_save(config)
|
||||
|
||||
# SmartAppManager uses a dispatcher to invoke callbacks when push events
|
||||
# occur. Use hass' implementation instead of the built-in one.
|
||||
dispatcher = Dispatcher(
|
||||
signal_prefix=SIGNAL_SMARTAPP_PREFIX,
|
||||
connect=functools.partial(async_dispatcher_connect, hass),
|
||||
send=functools.partial(async_dispatcher_send, hass))
|
||||
manager = SmartAppManager(
|
||||
webhook.async_generate_path(config[CONF_WEBHOOK_ID]),
|
||||
dispatcher=dispatcher)
|
||||
manager.connect_install(functools.partial(smartapp_install, hass))
|
||||
manager.connect_uninstall(functools.partial(smartapp_uninstall, hass))
|
||||
|
||||
webhook.async_register(hass, DOMAIN, 'SmartApp',
|
||||
config[CONF_WEBHOOK_ID], smartapp_webhook)
|
||||
|
||||
hass.data[DOMAIN] = {
|
||||
DATA_MANAGER: manager,
|
||||
CONF_INSTANCE_ID: config[CONF_INSTANCE_ID],
|
||||
DATA_BROKERS: {},
|
||||
CONF_WEBHOOK_ID: config[CONF_WEBHOOK_ID]
|
||||
}
|
||||
|
||||
|
||||
async def smartapp_install(hass: HomeAssistantType, req, resp, app):
|
||||
"""
|
||||
Handle when a SmartApp is installed by the user into a location.
|
||||
|
||||
Setup subscriptions using the access token SmartThings provided in the
|
||||
event. An explicit subscription is required for each 'capability' in order
|
||||
to receive the related attribute updates. Finally, create a config entry
|
||||
representing the installation if this is not the first installation under
|
||||
the account.
|
||||
"""
|
||||
from pysmartthings import SmartThings, Subscription, SourceType
|
||||
|
||||
# This access token is a temporary 'SmartApp token' that expires in 5 min
|
||||
# and is used to create subscriptions only.
|
||||
api = SmartThings(async_get_clientsession(hass), req.auth_token)
|
||||
|
||||
async def create_subscription(target):
|
||||
sub = Subscription()
|
||||
sub.installed_app_id = req.installed_app_id
|
||||
sub.location_id = req.location_id
|
||||
sub.source_type = SourceType.CAPABILITY
|
||||
sub.capability = target
|
||||
try:
|
||||
await api.create_subscription(sub)
|
||||
_LOGGER.debug("Created subscription for '%s' under app '%s'",
|
||||
target, req.installed_app_id)
|
||||
except Exception: # pylint:disable=broad-except
|
||||
_LOGGER.exception("Failed to create subscription for '%s' under "
|
||||
"app '%s'", target, req.installed_app_id)
|
||||
|
||||
tasks = [create_subscription(c) for c in SUPPORTED_CAPABILITIES]
|
||||
await asyncio.gather(*tasks)
|
||||
_LOGGER.debug("SmartApp '%s' under parent app '%s' was installed",
|
||||
req.installed_app_id, app.app_id)
|
||||
|
||||
# The permanent access token is copied from another config flow with the
|
||||
# same parent app_id. If one is not found, that means the user is within
|
||||
# the initial config flow and the entry at the conclusion.
|
||||
access_token = next((
|
||||
entry.data.get(CONF_ACCESS_TOKEN) for entry
|
||||
in hass.config_entries.async_entries(DOMAIN)
|
||||
if entry.data[CONF_APP_ID] == app.app_id), None)
|
||||
if access_token:
|
||||
# Add as job not needed because the current coroutine was invoked
|
||||
# from the dispatcher and is not being awaited.
|
||||
await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={'source': 'install'},
|
||||
data={
|
||||
CONF_APP_ID: app.app_id,
|
||||
CONF_INSTALLED_APP_ID: req.installed_app_id,
|
||||
CONF_LOCATION_ID: req.location_id,
|
||||
CONF_ACCESS_TOKEN: access_token
|
||||
})
|
||||
|
||||
|
||||
async def smartapp_uninstall(hass: HomeAssistantType, req, resp, app):
|
||||
"""
|
||||
Handle when a SmartApp is removed from a location by the user.
|
||||
|
||||
Find and delete the config entry representing the integration.
|
||||
"""
|
||||
entry = next((entry for entry in hass.config_entries.async_entries(DOMAIN)
|
||||
if entry.data.get(CONF_INSTALLED_APP_ID) ==
|
||||
req.installed_app_id),
|
||||
None)
|
||||
if entry:
|
||||
_LOGGER.debug("SmartApp '%s' under parent app '%s' was removed",
|
||||
req.installed_app_id, app.app_id)
|
||||
# Add as job not needed because the current coroutine was invoked
|
||||
# from the dispatcher and is not being awaited.
|
||||
await hass.config_entries.async_remove(entry.entry_id)
|
||||
|
||||
|
||||
async def smartapp_webhook(hass: HomeAssistantType, webhook_id: str, request):
|
||||
"""
|
||||
Handle a smartapp lifecycle event callback from SmartThings.
|
||||
|
||||
Requests from SmartThings are digitally signed and the SmartAppManager
|
||||
validates the signature for authenticity.
|
||||
"""
|
||||
manager = hass.data[DOMAIN][DATA_MANAGER]
|
||||
data = await request.json()
|
||||
result = await manager.handle_request(data, request.headers)
|
||||
return web.json_response(result)
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "SmartThings",
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Enter Personal Access Token",
|
||||
"description": "Please enter a SmartThings [Personal Access Token]({token_url}) that has been created per the [instructions]({component_url}).",
|
||||
"data": {
|
||||
"access_token": "Access Token"
|
||||
}
|
||||
},
|
||||
"wait_install": {
|
||||
"title": "Install SmartApp",
|
||||
"description": "Please install the Home Assistant SmartApp in at least one location and click submit."
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"token_invalid_format": "The token must be in the UID/GUID format",
|
||||
"token_unauthorized": "The token is invalid or no longer authorized.",
|
||||
"token_forbidden": "The token does not have the required OAuth scopes.",
|
||||
"token_already_setup": "The token has already been setup.",
|
||||
"app_setup_error": "Unable to setup the SmartApp. Please try again.",
|
||||
"app_not_installed": "Please ensure you have installed and authorized the Home Assistant SmartApp and try again.",
|
||||
"base_url_not_https": "The `base_url` for the `http` component must be configured and start with `https://`."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
Support for switches through the SmartThings cloud API.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/smartthings.switch/
|
||||
"""
|
||||
from homeassistant.components.switch import SwitchDevice
|
||||
|
||||
from . import SmartThingsEntity
|
||||
from .const import DATA_BROKERS, DOMAIN
|
||||
|
||||
DEPENDENCIES = ['smartthings']
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Platform uses config entry setup."""
|
||||
pass
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Add switches for a config entry."""
|
||||
broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id]
|
||||
async_add_entities(
|
||||
[SmartThingsSwitch(device) for device in broker.devices.values()
|
||||
if is_switch(device)])
|
||||
|
||||
|
||||
def is_switch(device):
|
||||
"""Determine if the device should be represented as a switch."""
|
||||
from pysmartthings import Capability
|
||||
|
||||
# Must be able to be turned on/off.
|
||||
if Capability.switch not in device.capabilities:
|
||||
return False
|
||||
# Must not have a capability represented by other types.
|
||||
non_switch_capabilities = [
|
||||
Capability.color_control,
|
||||
Capability.color_temperature,
|
||||
Capability.fan_speed,
|
||||
Capability.switch_level
|
||||
]
|
||||
if any(capability in device.capabilities
|
||||
for capability in non_switch_capabilities):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class SmartThingsSwitch(SmartThingsEntity, SwitchDevice):
|
||||
"""Define a SmartThings switch."""
|
||||
|
||||
async def async_turn_off(self, **kwargs) -> None:
|
||||
"""Turn the switch off."""
|
||||
await self._device.switch_off(set_status=True)
|
||||
# State is set optimistically in the command above, therefore update
|
||||
# the entity state ahead of receiving the confirming push updates
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
async def async_turn_on(self, **kwargs) -> None:
|
||||
"""Turn the switch on."""
|
||||
await self._device.switch_on(set_status=True)
|
||||
# State is set optimistically in the command above, therefore update
|
||||
# the entity state ahead of receiving the confirming push updates
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""Return true if light is on."""
|
||||
return self._device.status.switch
|
||||
Reference in new issue
Block a user