2019-03-30 04:10:00 +00:00
|
|
|
"""Config flow to configure Heos."""
|
2019-03-30 13:52:17 +00:00
|
|
|
import asyncio
|
|
|
|
|
|
|
|
import voluptuous as vol
|
|
|
|
|
2019-03-30 04:10:00 +00:00
|
|
|
from homeassistant import config_entries
|
|
|
|
from homeassistant.const import CONF_HOST
|
|
|
|
|
|
|
|
from .const import DOMAIN
|
|
|
|
|
|
|
|
|
|
|
|
def format_title(host: str) -> str:
|
|
|
|
"""Format the title for config entries."""
|
|
|
|
return "Controller ({})".format(host)
|
|
|
|
|
|
|
|
|
|
|
|
@config_entries.HANDLERS.register(DOMAIN)
|
|
|
|
class HeosFlowHandler(config_entries.ConfigFlow):
|
|
|
|
"""Define a flow for HEOS."""
|
|
|
|
|
|
|
|
VERSION = 1
|
|
|
|
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
|
|
|
|
|
2019-04-02 20:22:49 +00:00
|
|
|
async def async_step_discovery(self, discovery_info):
|
|
|
|
"""Handle a discovered Heos device."""
|
2019-04-09 02:24:40 +00:00
|
|
|
# Only continue if this is the only active flow
|
|
|
|
flows = self.hass.config_entries.flow.async_progress()
|
|
|
|
heos_flows = [flow for flow in flows if flow['handler'] == DOMAIN]
|
|
|
|
if len(heos_flows) == 1:
|
|
|
|
return await self.async_step_user(
|
|
|
|
{CONF_HOST: discovery_info[CONF_HOST]})
|
|
|
|
return self.async_abort(reason='already_setup')
|
2019-04-02 20:22:49 +00:00
|
|
|
|
2019-03-30 04:10:00 +00:00
|
|
|
async def async_step_import(self, user_input=None):
|
|
|
|
"""Occurs when an entry is setup through config."""
|
|
|
|
host = user_input[CONF_HOST]
|
|
|
|
return self.async_create_entry(
|
|
|
|
title=format_title(host),
|
|
|
|
data={CONF_HOST: host})
|
2019-03-30 13:52:17 +00:00
|
|
|
|
|
|
|
async def async_step_user(self, user_input=None):
|
|
|
|
"""Obtain host and validate connection."""
|
|
|
|
from pyheos import Heos
|
|
|
|
|
2019-04-02 20:22:49 +00:00
|
|
|
# Only a single entry is needed for all devices
|
2019-03-30 13:52:17 +00:00
|
|
|
entries = self.hass.config_entries.async_entries(DOMAIN)
|
|
|
|
if entries:
|
|
|
|
return self.async_abort(reason='already_setup')
|
|
|
|
|
|
|
|
# Try connecting to host if provided
|
|
|
|
errors = {}
|
|
|
|
host = None
|
|
|
|
if user_input is not None:
|
|
|
|
host = user_input[CONF_HOST]
|
|
|
|
heos = Heos(host)
|
|
|
|
try:
|
|
|
|
await heos.connect()
|
|
|
|
return await self.async_step_import(user_input)
|
|
|
|
except (asyncio.TimeoutError, ConnectionError):
|
|
|
|
errors[CONF_HOST] = 'connection_failure'
|
|
|
|
finally:
|
|
|
|
await heos.disconnect()
|
|
|
|
|
|
|
|
# Return form
|
|
|
|
return self.async_show_form(
|
|
|
|
step_id='user',
|
|
|
|
data_schema=vol.Schema({
|
|
|
|
vol.Required(CONF_HOST, default=host): str
|
|
|
|
}),
|
|
|
|
errors=errors)
|