hass-core/homeassistant/components/luftdaten/config_flow.py

71 lines
2.2 KiB
Python
Raw Normal View History

"""Config flow to configure the Luftdaten component."""
from collections import OrderedDict
from luftdaten import Luftdaten
from luftdaten.exceptions import LuftdatenConnectionError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
2019-07-31 12:25:30 -07:00
CONF_MONITORED_CONDITIONS,
CONF_SCAN_INTERVAL,
CONF_SENSORS,
CONF_SHOW_ON_MAP,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from .const import CONF_SENSOR_ID, DEFAULT_SCAN_INTERVAL, DOMAIN
class LuftDatenFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a Luftdaten config flow."""
VERSION = 1
@callback
def _show_form(self, errors=None):
"""Show the form to the user."""
data_schema = OrderedDict()
data_schema[vol.Required(CONF_SENSOR_ID)] = cv.positive_int
data_schema[vol.Optional(CONF_SHOW_ON_MAP, default=False)] = bool
return self.async_show_form(
2019-07-31 12:25:30 -07:00
step_id="user", data_schema=vol.Schema(data_schema), errors=errors or {}
)
async def async_step_user(self, user_input=None):
"""Handle the start of the config flow."""
if not user_input:
return self._show_form()
await self.async_set_unique_id(str(user_input[CONF_SENSOR_ID]))
self._abort_if_unique_id_configured()
2021-12-04 09:16:00 +01:00
luftdaten = Luftdaten(user_input[CONF_SENSOR_ID])
try:
await luftdaten.get_data()
valid = await luftdaten.validate_sensor()
except LuftdatenConnectionError:
return self._show_form({CONF_SENSOR_ID: "cannot_connect"})
if not valid:
2019-07-31 12:25:30 -07:00
return self._show_form({CONF_SENSOR_ID: "invalid_sensor"})
2019-07-31 12:25:30 -07:00
available_sensors = [
x for x, x_values in luftdaten.values.items() if x_values is not None
2019-07-31 12:25:30 -07:00
]
if available_sensors:
2019-07-31 12:25:30 -07:00
user_input.update(
{CONF_SENSORS: {CONF_MONITORED_CONDITIONS: available_sensors}}
)
2019-07-31 12:25:30 -07:00
scan_interval = user_input.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
user_input.update({CONF_SCAN_INTERVAL: scan_interval.total_seconds()})
return self.async_create_entry(
title=str(user_input[CONF_SENSOR_ID]), data=user_input
)