Skip to content

Commit

Permalink
bumped client to support new api 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
ShayGus committed Jan 14, 2023
1 parent 2922a0d commit 2293201
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 26 deletions.
34 changes: 32 additions & 2 deletions custom_components/cool_open_integration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady

from cool_open_client.hvac_units_factory import HVACUnitsFactory
from cool_open_client.cool_automation_client import CoolAutomationClient
from cool_open_client.cool_automation_client import (
CoolAutomationClient,
InvalidTokenException,
)

from .const import DOMAIN, PLATFORMS
from .coordinator import CoolAutomationDataUpdateCoordinator
Expand All @@ -33,12 +36,39 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
token = entry.data["token"]
try:
client = await CoolAutomationClient.create(token=token)
except OSError as error:
raise ConfigEntryNotReady() from error
except InvalidTokenException as error:
_LOGGER.error("Invalid token, reauthenticating...")
username = entry.data["username"]
password = entry.data["password"]
try:
token = await CoolAutomationClient.authenticate(username, password)
hass.config_entries.async_update_entry(
entry, data={"username": username, "password": password, "token": token}
)
client = await CoolAutomationClient.create(token=token)
except Exception as error:
_LOGGER.error("Can't authenticate, wrong credentials: %s", error)
raise ConfigEntryAuthFailed(
"Authentication is no longer valid. Please reauthenticate"
) from error
except Exception as error:
_LOGGER.error("General Error: %s", error)
raise ConfigEntryNotReady() from error
try:
units_factory = await HVACUnitsFactory.create(token=token)
units = await units_factory.generate_units_from_api()
if not units:
raise ConfigEntryNotReady
except OSError as error:
raise ConfigEntryNotReady() from error
except InvalidTokenException as error:
_LOGGER.error("Invalid token")
raise ConfigEntryAuthFailed(error) from error
except Exception as error:
_LOGGER.error("General Error: %s", error)
raise ConfigEntryNotReady() from error

coordinator = CoolAutomationDataUpdateCoordinator(hass, entry, client, units)
await coordinator.async_config_entry_first_refresh()
Expand Down
98 changes: 93 additions & 5 deletions custom_components/cool_open_integration/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError

from homeassistant.helpers.schema_config_entry_flow import (
SchemaFlowFormStep,
SchemaOptionsFlowHandler,
)
from collections.abc import Mapping

from cool_open_client.cool_automation_client import CoolAutomationClient

Expand All @@ -27,6 +31,10 @@
}
)

OPTIONS_FLOW = {
"init": SchemaFlowFormStep(STEP_USER_DATA_SCHEMA),
}


async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect.
Expand Down Expand Up @@ -60,18 +68,32 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,

# Return info that you want to store in the config entry.
devices = [device.serial for device in devices]
return {"username": data["username"], "password": data["password"], "token": token, "devices": devices, "id": id}
return {
"username": data["username"],
"password": data["password"],
"token": token,
"devices": devices,
"id": id,
}


class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for CoolAutomation Cloud Open Integration."""

VERSION = 1

async def async_step_user(self, user_input: dict[str, str] | None = None) -> FlowResult:
def __init__(self) -> None:
"""Initialize the flow."""
self.entry: config_entries.ConfigEntry | None = None

async def async_step_user(
self, user_input: dict[str, str] | None = None
) -> FlowResult:
"""Handle the initial step."""
if user_input is None:
return self.async_show_form(step_id="user", data_schema=STEP_USER_DATA_SCHEMA)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
)

errors = {}

Expand All @@ -89,7 +111,73 @@ async def async_step_user(self, user_input: dict[str, str] | None = None) -> Flo
self._abort_if_unique_id_configured()
return self.async_create_entry(title=TITLE, data=data)

return self.async_show_form(step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)

async def async_step_user_reauth(
self, user_input: dict[str, str] | None = None
) -> FlowResult:
"""Handle the initial step."""
if user_input is None:
return self.async_show_form(
step_id="user_reauth", data_schema=STEP_USER_DATA_SCHEMA
)

errors = {}

try:
data = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
self.hass.config_entries.async_update_entry(self.entry, data=data)
await self.hass.config_entries.async_reload(self.entry.entry_id)
return self.async_abort(reason="reauth_successful")

return self.async_show_form(
step_id="user_reauth", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)

async def async_step_reauth(self, _: Mapping[str, Any]) -> FlowResult:
"""Handle configuration by re-auth."""
self.entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
# return await self.async_step_reauth_perform()
return await self.async_step_user_reauth()

async def async_step_reauth_perform(
self, user_input: dict[str, str] | None = None
) -> FlowResult:
"""Confirm reauth dialog."""
# if user_input is not None:
return await self.async_step_user_reauth()

# return self.async_show_form(
# step_id="reauth_perform", data_schema=STEP_USER_DATA_SCHEMA
# )

# @staticmethod
# @callback
# def async_get_options_flow(
# config_entry: config_entries.ConfigEntry,
# ) -> CoolOpenIntegrationOptionsFlowHandler:
# """Get the options flow for this handler."""
# return CoolOpenIntegrationOptionsFlowHandler(config_entry)


# class CoolOpenIntegrationOptionsFlowHandler(config_entries.OptionsFlow):
# def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
# """Initialize CoolOpenIntegration options flow."""
# self.arm_options = config_entry.options.get(OPTIONS_ARM, DEFAULT_ARM_OPTIONS)
# self.zone_options = config_entry.options.get(
# OPTIONS_ZONES, DEFAULT_ZONE_OPTIONS
# )
# self.selected_zone = None


class CannotConnect(HomeAssistantError):
Expand Down
38 changes: 19 additions & 19 deletions custom_components/cool_open_integration/manifest.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
{
"domain": "cool_open_integration",
"name": "CoolAutomation Cloud Open Integration",
"config_flow": true,
"documentation": "https://github.com/ShayGus/cool-open-integration/wiki",
"issue_tracker": "https://github.com/ShayGus/cool-open-integration/issues",
"requirements": [
"cool-open-client==0.0.9"
],
"ssdp": [],
"zeroconf": [],
"homekit": {},
"dependencies": [],
"codeowners": [
"@ShayGus"
],
"iot_class": "cloud_push",
"version": "0.0.3"
}
{
"domain": "cool_open_integration",
"name": "CoolAutomation Cloud Open Integration",
"config_flow": true,
"documentation": "https://github.com/ShayGus/cool-open-integration/wiki",
"issue_tracker": "https://github.com/ShayGus/cool-open-integration/issues",
"requirements": [
"cool-open-client==0.0.10"
],
"ssdp": [],
"zeroconf": [],
"homekit": {},
"dependencies": [],
"codeowners": [
"@ShayGus"
],
"iot_class": "cloud_push",
"version": "0.0.4"
}

0 comments on commit 2293201

Please sign in to comment.