1
0
mirror of https://github.com/natekspencer/hacs-oasis_mini.git synced 2025-11-18 01:53:41 -05:00

Add ability to reconfigure integration to handle updated host ip

This commit is contained in:
Nathan Spencer
2024-07-11 11:51:23 -06:00
parent 9b85d939c4
commit cda435070d
4 changed files with 52 additions and 20 deletions

View File

@@ -10,10 +10,9 @@ from aiohttp import ClientConnectorError
from httpx import ConnectError, HTTPStatusError from httpx import ConnectError, HTTPStatusError
import voluptuous as vol import voluptuous as vol
from homeassistant.config_entries import ConfigEntry, ConfigFlow from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_HOST, CONF_PASSWORD from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_HOST, CONF_PASSWORD
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.schema_config_entry_flow import ( from homeassistant.helpers.schema_config_entry_flow import (
SchemaCommonFlowHandler, SchemaCommonFlowHandler,
SchemaFlowError, SchemaFlowError,
@@ -30,16 +29,14 @@ _LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str}) STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str})
OPTIONS_SCHEMA = vol.Schema( OPTIONS_SCHEMA = vol.Schema(
{ {vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str}
vol.Optional(CONF_EMAIL): str,
vol.Optional(CONF_PASSWORD): str,
}
) )
async def cloud_login( async def cloud_login(
handler: SchemaCommonFlowHandler, user_input: dict[str, Any] handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Cloud login."""
coordinator: OasisMiniCoordinator = handler.parent_handler.hass.data[DOMAIN][ coordinator: OasisMiniCoordinator = handler.parent_handler.hass.data[DOMAIN][
handler.parent_handler.config_entry.entry_id handler.parent_handler.config_entry.entry_id
] ]
@@ -49,8 +46,8 @@ async def cloud_login(
email=user_input[CONF_EMAIL], password=user_input[CONF_PASSWORD] email=user_input[CONF_EMAIL], password=user_input[CONF_PASSWORD]
) )
user_input[CONF_ACCESS_TOKEN] = coordinator.device.access_token user_input[CONF_ACCESS_TOKEN] = coordinator.device.access_token
except: except Exception as ex:
raise SchemaFlowError("invalid_auth") raise SchemaFlowError("invalid_auth") from ex
del user_input[CONF_PASSWORD] del user_input[CONF_PASSWORD]
return user_input return user_input
@@ -75,7 +72,7 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
"""Get the options flow for this handler.""" """Get the options flow for this handler."""
return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW) return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW)
# async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult: # async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> ConfigFlowResult:
# """Handle dhcp discovery.""" # """Handle dhcp discovery."""
# self.host = discovery_info.ip # self.host = discovery_info.ip
# self.name = discovery_info.hostname # self.name = discovery_info.hostname
@@ -85,13 +82,29 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
async def async_step_user( async def async_step_user(
self, user_input: dict[str, Any] | None = None self, user_input: dict[str, Any] | None = None
) -> FlowResult: ) -> ConfigFlowResult:
"""Handle the initial step.""" """Handle the initial step."""
return await self._async_step("user", STEP_USER_DATA_SCHEMA, user_input) return await self._async_step("user", STEP_USER_DATA_SCHEMA, user_input)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration."""
entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
assert entry
suggested_values = user_input or entry.data
return await self._async_step(
"reconfigure", STEP_USER_DATA_SCHEMA, user_input, suggested_values
)
async def _async_step( async def _async_step(
self, step_id: str, schema: vol.Schema, user_input: dict[str, Any] | None = None self,
) -> FlowResult: step_id: str,
schema: vol.Schema,
user_input: dict[str, Any] | None = None,
suggested_values: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle step setup.""" """Handle step setup."""
if abort := self._abort_if_configured(user_input): if abort := self._abort_if_configured(user_input):
return abort return abort
@@ -108,21 +121,26 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
existing_entry, data=data existing_entry, data=data
) )
await self.hass.config_entries.async_reload(existing_entry.entry_id) await self.hass.config_entries.async_reload(existing_entry.entry_id)
return self.async_abort(reason="reauth_successful") return self.async_abort(reason="reconfigure_successful")
return self.async_create_entry( return self.async_create_entry(
title=f"Oasis Mini {self.serial_number}", title=f"Oasis Mini {self.serial_number}",
data=data, data=data,
) )
return self.async_show_form(step_id=step_id, data_schema=schema, errors=errors) return self.async_show_form(
step_id=step_id,
data_schema=self.add_suggested_values_to_schema(schema, suggested_values),
errors=errors,
)
async def validate_client(self, user_input: dict[str, Any]) -> dict[str, str]: async def validate_client(self, user_input: dict[str, Any]) -> dict[str, str]:
"""Validate client setup.""" """Validate client setup."""
errors = {} errors = {}
try: try:
client = create_client({"host": self.host} | user_input) async with asyncio.timeout(10):
self.serial_number = await client.async_get_serial_number() client = create_client({"host": self.host} | user_input)
self.serial_number = await client.async_get_serial_number()
if not self.serial_number: if not self.serial_number:
errors["base"] = "invalid_host" errors["base"] = "invalid_host"
except asyncio.TimeoutError: except asyncio.TimeoutError:
@@ -143,7 +161,7 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
@callback @callback
def _abort_if_configured( def _abort_if_configured(
self, user_input: dict[str, Any] | None self, user_input: dict[str, Any] | None
) -> FlowResult | None: ) -> ConfigFlowResult | None:
"""Abort if configured.""" """Abort if configured."""
if self.host or user_input: if self.host or user_input:
data = {CONF_HOST: self.host, **(user_input or {})} data = {CONF_HOST: self.host, **(user_input or {})}

View File

@@ -237,7 +237,7 @@ class OasisMini:
async def _async_get(self, **kwargs: Any) -> str | None: async def _async_get(self, **kwargs: Any) -> str | None:
"""Perform a GET request.""" """Perform a GET request."""
response = await self._session.get(self.url, **kwargs) response = await self._session.get(self.url, **kwargs)
if response.status == 200: if response.status == 200 and response.content_type == "text/plain":
text = await response.text() text = await response.text()
return text return text
return None return None

View File

@@ -6,6 +6,11 @@
"host": "[%key:common::config_flow::data::host%]" "host": "[%key:common::config_flow::data::host%]"
} }
}, },
"reconfigure": {
"data": {
"host": "[%key:common::config_flow::data::host%]"
}
},
"reauth_confirm": { "reauth_confirm": {
"data": {} "data": {}
} }
@@ -17,7 +22,9 @@
"unknown": "[%key:common::config_flow::error::unknown%]" "unknown": "[%key:common::config_flow::error::unknown%]"
}, },
"abort": { "abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]" "already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]"
} }
}, },
"options": { "options": {

View File

@@ -6,6 +6,11 @@
"host": "Host" "host": "Host"
} }
}, },
"reconfigure": {
"data": {
"host": "Host"
}
},
"reauth_confirm": { "reauth_confirm": {
"data": {} "data": {}
} }
@@ -17,7 +22,9 @@
"unknown": "Unexpected error" "unknown": "Unexpected error"
}, },
"abort": { "abort": {
"already_configured": "Device is already configured" "already_configured": "Device is already configured",
"reauth_successful": "Re-authentication was successful",
"reconfigure_successful": "Re-configuration was successful"
} }
}, },
"options": { "options": {