Skip to content
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
48 changes: 27 additions & 21 deletions homeassistant/components/switch/hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import aiohttp

from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, CONF_TOKEN
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv

Expand All @@ -22,8 +22,12 @@
TIMEOUT = 10

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Exclusive(CONF_PASSWORD, 'hook_secret', msg='hook: provide ' +
'username/password OR token'): cv.string,
vol.Exclusive(CONF_TOKEN, 'hook_secret', msg='hook: provide ' +
'username/password OR token'): cv.string,
vol.Inclusive(CONF_USERNAME, 'hook_auth'): cv.string,
vol.Inclusive(CONF_PASSWORD, 'hook_auth'): cv.string,
})


Expand All @@ -32,31 +36,33 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up Hook by getting the access token and list of actions."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
token = config.get(CONF_TOKEN)
websession = async_get_clientsession(hass)
# If password is set in config, prefer it over token
if username is not None and password is not None:
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.post(
'{}{}'.format(HOOK_ENDPOINT, 'user/login'),
data={
'username': username,
'password': password})
data = yield from response.json()
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed authentication API call: %s", error)
return False

try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.post(
'{}{}'.format(HOOK_ENDPOINT, 'user/login'),
data={
'username': username,
'password': password})
data = yield from response.json()
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed authentication API call: %s", error)
return False

try:
token = data['data']['token']
except KeyError:
_LOGGER.error("No token. Check username and password")
return False
try:
token = data['data']['token']
except KeyError:
_LOGGER.error("No token. Check username and password")
return False

try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.get(
'{}{}'.format(HOOK_ENDPOINT, 'device'),
params={"token": data['data']['token']})
params={"token": token})
data = yield from response.json()
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed getting devices: %s", error)
Expand Down