From 09bc4431830a46f626145ab7988aeb7a206874fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Vikstr=C3=B6m?= Date: Sat, 28 May 2022 20:13:40 +0000 Subject: [PATCH] Can add but sensors do not have the right functions to register --- __init__.py | 57 +++++++++++++++++++++++++++++++++------- config_flow.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++ manifest.json | 1 + 3 files changed, 119 insertions(+), 10 deletions(-) create mode 100644 config_flow.py diff --git a/__init__.py b/__init__.py index 4158cb2..7c85eb2 100644 --- a/__init__.py +++ b/__init__.py @@ -10,6 +10,7 @@ from .const import DOMAIN from homeassistant.components import persistent_notification +from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, EVENT_HOMEASSISTANT_STOP, @@ -40,14 +41,12 @@ }, extra=vol.ALLOW_EXTRA, ) +PLATFORMS: list[str] = ["sensor", "binary_sensor"] -def setup(hass: HomeAssistant, base_config: ConfigType) -> bool: - """Set up waterfurnace platform.""" - - config = base_config[DOMAIN] - - host = config[CONF_HOST] +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up Hello World from a config entry.""" + host = entry.data["host"] device_client = device.Device(host) try: @@ -58,14 +57,52 @@ def setup(hass: HomeAssistant, base_config: ConfigType) -> bool: _LOGGER.error("Could no connect ot device") return False - hass.data[DOMAIN] = DeviceData(hass, device_client) - hass.data[DOMAIN].start() + # device_data = DeviceData(hass, device_client) + # device_data.start() - discovery.load_platform(hass, Platform.SENSOR, DOMAIN, {}, config) - discovery.load_platform(hass, Platform.BINARY_SENSOR, DOMAIN, {}, config) + hass.data.setdefault(DOMAIN, {})[entry.entry_id] = DeviceData(hass, device_client) + hass.data.setdefault(DOMAIN, {})[entry.entry_id].start() + + hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Unload a config entry.""" + # This is called when an entry/configured device is to be removed. The class + # needs to unload itself, and remove callbacks. See the classes for further + # details + unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + if unload_ok: + hass.data[DOMAIN].pop(entry.entry_id) + + return unload_ok + + +# def setup(hass: HomeAssistant, base_config: ConfigType) -> bool: +# """Set up waterfurnace platform.""" + +# config = base_config[DOMAIN] + +# host = config[CONF_HOST] + +# device_client = device.Device(host) +# try: +# if not device_client.run(once=True): +# _LOGGER.error("Device found but no measuremetn was received") +# return False +# except TimeoutError: +# _LOGGER.error("Could no connect ot device") +# return False + +# hass.data[DOMAIN] = DeviceData(hass, device_client) +# hass.data[DOMAIN].start() + +# discovery.load_platform(hass, Platform.SENSOR, DOMAIN, {}, config) +# discovery.load_platform(hass, Platform.BINARY_SENSOR, DOMAIN, {}, config) +# return True + + class DeviceData(threading.Thread): """PH-803W Data Collector. diff --git a/config_flow.py b/config_flow.py new file mode 100644 index 0000000..661485f --- /dev/null +++ b/config_flow.py @@ -0,0 +1,71 @@ +"""Config flow for PH-803W integration.""" +from __future__ import annotations + +import logging +from typing import Any + +import voluptuous as vol + +from homeassistant import config_entries, exceptions +from homeassistant.core import HomeAssistant + +from .const import DOMAIN +from .lib import device + +_LOGGER = logging.getLogger(__name__) + +DATA_SCHEMA = vol.Schema({("host"): str}) + + +async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: + """Validate the user input allows us to connect.""" + if len(data["host"]) < 3: + raise InvalidHost + + host = data["host"] + + device_client = device.Device(host) + try: + if not device_client.run(once=True): + _LOGGER.error("Device found but no measuremetn was received") + raise CannotConnect + except TimeoutError: + _LOGGER.error("Could no connect ot device") + raise CannotConnect + + return {"title": data["host"]} + + +class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a config flow for Hello World.""" + + VERSION = 1 + CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL + + async def async_step_user(self, user_input=None): + """Handle the initial step.""" + errors = {} + if user_input is not None: + try: + info = await validate_input(self.hass, user_input) + + return self.async_create_entry(title=info["title"], data=user_input) + except CannotConnect: + errors["base"] = "cannot_connect" + except InvalidHost: + errors["host"] = "cannot_connect" + except Exception: # pylint: disable=broad-except + _LOGGER.exception("Unexpected exception") + errors["base"] = "unknown" + + return self.async_show_form( + step_id="user", data_schema=DATA_SCHEMA, errors=errors + ) + + +class CannotConnect(exceptions.HomeAssistantError): + """Error to indicate we cannot connect.""" + + +class InvalidHost(exceptions.HomeAssistantError): + """Error to indicate there is an invalid hostname.""" diff --git a/manifest.json b/manifest.json index 848427f..cfeaf42 100644 --- a/manifest.json +++ b/manifest.json @@ -4,6 +4,7 @@ "documentation": "https://github.com/dala318/python_ph803w", "version": "0.0.1", "dependencies": [], + "config_flow": true, "after_dependencies": [], "iot_class": "local_polling", "codeowners": ["@dala318"],