This repository was archived by the owner on Dec 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconfig_flow.py
More file actions
212 lines (170 loc) · 7.07 KB
/
config_flow.py
File metadata and controls
212 lines (170 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""Config flow for Klyqa."""
# import my_pypi_dependency
from typing import Any, cast
from numpy import integer
from requests.exceptions import ConnectTimeout, HTTPError
import voluptuous as vol
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_flow
from . import api
from .api import Klyqa
from .const import CONF_POLLING, DEFAULT_CACHEDB, DOMAIN, LOGGER
import homeassistant.helpers.config_validation as cv
from homeassistant import config_entries
from homeassistant.const import (
CONF_PASSWORD,
CONF_HOST,
CONF_SCAN_INTERVAL,
CONF_ROOM,
CONF_USERNAME,
)
from .const import CONF_SYNC_ROOMS
from homeassistant.data_entry_flow import FlowResult
# user_step_data_schema = {
# vol.Required(CONF_USERNAME, default="frederick.stallmeyer1@qconnex.com"): cv.string,
# vol.Required(CONF_PASSWORD, default="testpwd1"): cv.string,
# vol.Required(CONF_SCAN_INTERVAL, default="60"): cv.string,
# vol.Required(CONF_SYNC_ROOMS, default=True): cv.boolean,
# vol.Required(CONF_HOST, default="http://localhost:3000"): cv.url,
# }
user_step_data_schema = {
vol.Required(CONF_USERNAME, default="frederick.stallmeyer1@qconnex.com"): str,
vol.Required(CONF_PASSWORD, default="testpwd1"): str,
vol.Required(CONF_SCAN_INTERVAL, default=60): int,
vol.Required(CONF_SYNC_ROOMS, default=True): bool,
vol.Required(CONF_HOST, default="http://localhost:3000"): str,
}
class OptionsFlowHandler(config_entries.OptionsFlow):
def __init__(self, config_entry):
"""Initialize options flow."""
self.config_entry = config_entry
async def async_step_init(self, user_input=None):
"""Manage the options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
user_step_data_schema
# {
# vol.Required(
# "user",
# default=self.config_entry.options.get("show_things"),
# ): bool
# }
),
)
class KlyqaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Example config flow."""
# The schema version of the entries that it creates
# Home Assistant will call your migrate method if the version changes
# (this is not implemented yet)
VERSION = 1
def __init__(self) -> None:
"""Initialize."""
self._username: str | None = None
self._password: str | None = None
self._cache: str | None = None
self._scan_interval: int = 30
self._host: str | None = None
self._klyqa = None
pass
def klyqa(self) -> Klyqa:
if self._klyqa:
return self._klyqa
if not self.hass or not DOMAIN in self.hass.data:
return None
self._klyqa = self.hass.data[DOMAIN]
return self.hass.data[DOMAIN]
async def async_step_user(self, user_input=None) -> FlowResult:
"""Handle a flow initialized by the user."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
""" already logged in from platform or other way """
if self.klyqa() and self._klyqa._access_token:
self._username = self._klyqa._username
self._password = self._klyqa._password
self._host = self._klyqa._host
return await self._async_create_entry()
login_failed = False
if user_input is None or login_failed:
return self.async_show_form(
step_id="user", data_schema=vol.Schema(user_step_data_schema)
)
self._username = user_input[CONF_USERNAME]
self._password = user_input[CONF_PASSWORD]
self._scan_interval = user_input[CONF_SCAN_INTERVAL]
self._sync_rooms = user_input[CONF_SYNC_ROOMS]
self._host = user_input[CONF_HOST]
return await self._async_klyqa_login(step_id="user")
async def _async_klyqa_login(self, step_id: str) -> FlowResult:
"""Handle login with Klyqa."""
# self._cache = self.hass.config.path(DEFAULT_CACHEDB)
errors = {}
if DOMAIN in self.hass.data:
self._klyqa = self.hass.data[DOMAIN]
try:
await self.hass.async_add_executor_job(self._klyqa.shutdown)
except Exception as e:
pass
try:
self._klyqa: Klyqa = Klyqa(
self._username,
self._password,
self._host,
self.hass,
sync_rooms=self._sync_rooms,
)
if not await self.hass.async_add_executor_job(
self._klyqa.login,
):
raise Exception("Unable to login")
if self._klyqa:
self.hass.data[DOMAIN] = self._klyqa
except (ConnectTimeout, HTTPError):
LOGGER.error("Unable to connect to Klyqa: %s", ex)
errors = {"base": "cannot_connect"}
except Exception as ex:
LOGGER.error("Unable to connect to Klyqa: %s", ex)
errors = {"base": "cannot_connect"}
if not self._klyqa or not self._klyqa._access_token:
errors = {"base": "cannot_connect"}
if errors:
return self.async_show_form(
step_id=step_id,
data_schema=vol.Schema(user_step_data_schema),
errors=errors,
)
return await self._async_create_entry()
async def _async_create_entry(self) -> FlowResult:
"""Create the config entry."""
config_data = {
CONF_USERNAME: self._username,
CONF_PASSWORD: self._password,
CONF_SCAN_INTERVAL: self._scan_interval,
CONF_SYNC_ROOMS: self._sync_rooms,
CONF_HOST: self._host,
}
existing_entry = await self.async_set_unique_id(self._username)
if existing_entry:
self.hass.config_entries.async_update_entry(
existing_entry, data=config_data
)
# Reload the Klyqa config entry otherwise devices will remain unavailable
self.hass.async_create_task(
self.hass.config_entries.async_reload(existing_entry.entry_id)
)
return self.async_abort(reason="reauth_successful")
return self.async_create_entry(
title=cast(str, self._username), data=config_data
)
# async def _async_has_devices(hass: HomeAssistant) -> bool:
# """Return if there are devices that can be discovered."""
# # TODO Check if there are any devices that can be discovered in the network.
# devices = []
# # await hass.async_add_executor_job(my_pypi_dependency.discover)
# device_unique_id = "AABBCCDD" # e. g. mac address using homeassistant.helpers.device_registry.format_mac
# # api.send("--request")
# LOGGER.info("okkkk")
# return True # len(devices) > 0
# config_entry_flow.register_discovery_flow(DOMAIN, "Klyqa", _async_has_devices)