-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconfig_flow.py
More file actions
170 lines (144 loc) · 6.33 KB
/
Copy pathconfig_flow.py
File metadata and controls
170 lines (144 loc) · 6.33 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
"""Config flow for UniFi Network Rules."""
from __future__ import annotations
import asyncio
from typing import Any
import voluptuous as vol
from aiounifi.errors import (
LoginRequired,
RequestError,
ResponseError,
Unauthorized,
)
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult
from .const import (
CONF_SITE,
CONF_SMART_POLLING_ACTIVE_INTERVAL,
CONF_SMART_POLLING_ACTIVITY_TIMEOUT,
CONF_SMART_POLLING_BASE_INTERVAL,
CONF_SMART_POLLING_DEBOUNCE_SECONDS,
CONF_SMART_POLLING_OPTIMISTIC_TIMEOUT,
CONF_SMART_POLLING_REALTIME_INTERVAL,
CONF_UPDATE_INTERVAL,
DEFAULT_SITE,
DEFAULT_UPDATE_INTERVAL,
DOMAIN,
LOGGER,
)
from .udm import UDMAPI, CannotConnect, InvalidAuth
from .utils.logger import install_aiounifi_log_redaction
# Display the update interval in minutes for better UX
DEFAULT_UPDATE_INTERVAL_MINUTES = DEFAULT_UPDATE_INTERVAL // 60
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
vol.Optional(CONF_SITE, default=DEFAULT_SITE): str,
vol.Optional(
CONF_UPDATE_INTERVAL, default=DEFAULT_UPDATE_INTERVAL_MINUTES, description="Update interval in minutes"
): int,
vol.Optional(CONF_VERIFY_SSL, default=False, description="Enable SSL certificate verification"): bool,
}
)
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None:
"""Validate the user input allows us to connect."""
install_aiounifi_log_redaction()
api = UDMAPI(
data[CONF_HOST],
data[CONF_USERNAME],
data[CONF_PASSWORD],
site=data.get(CONF_SITE, DEFAULT_SITE),
verify_ssl=data.get(CONF_VERIFY_SSL, False),
)
try:
async with asyncio.timeout(10):
await api.async_init(hass)
except (ResponseError, RequestError) as err:
raise CannotConnect from err
except (LoginRequired, Unauthorized) as err:
raise InvalidAuth from err
except Exception as err:
LOGGER.exception("Unexpected exception: %s", str(err))
raise
finally:
await api.cleanup()
class UnifiNetworkRulesConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for UniFi Network Rules."""
VERSION = 1
async def async_step_user(self, user_input: dict[str, Any] | None = None) -> FlowResult:
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
# Convert update interval from minutes to seconds
if CONF_UPDATE_INTERVAL in user_input:
user_input[CONF_UPDATE_INTERVAL] = user_input[CONF_UPDATE_INTERVAL] * 60
await validate_input(self.hass, user_input)
await self.async_set_unique_id(f"unifi_rules_{user_input[CONF_HOST]}")
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"UniFi Network Rules ({user_input[CONF_HOST]})",
data=user_input,
)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception:
LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return self.async_show_form(step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors)
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow."""
return UnifiNetworkRulesOptionsFlowHandler()
class UnifiNetworkRulesOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle options flow for UniFi Network Rules."""
async def async_step_init(self, user_input=None):
"""Handle options flow."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
# Get current options with defaults
options = self.config_entry.options
# Smart polling configuration schema
options_schema = vol.Schema(
{
vol.Optional(
CONF_SMART_POLLING_BASE_INTERVAL,
default=options.get(CONF_SMART_POLLING_BASE_INTERVAL, 300),
description="Base polling interval when idle (seconds)",
): vol.All(int, vol.Range(min=30, max=3600)),
vol.Optional(
CONF_SMART_POLLING_ACTIVE_INTERVAL,
default=options.get(CONF_SMART_POLLING_ACTIVE_INTERVAL, 30),
description="Active polling interval during user activity (seconds)",
): vol.All(int, vol.Range(min=10, max=300)),
vol.Optional(
CONF_SMART_POLLING_REALTIME_INTERVAL,
default=options.get(CONF_SMART_POLLING_REALTIME_INTERVAL, 10),
description="Real-time polling interval during changes (seconds)",
): vol.All(int, vol.Range(min=5, max=60)),
vol.Optional(
CONF_SMART_POLLING_ACTIVITY_TIMEOUT,
default=options.get(CONF_SMART_POLLING_ACTIVITY_TIMEOUT, 120),
description="Time to return to base interval after activity (seconds)",
): vol.All(int, vol.Range(min=60, max=600)),
vol.Optional(
CONF_SMART_POLLING_DEBOUNCE_SECONDS,
default=options.get(CONF_SMART_POLLING_DEBOUNCE_SECONDS, 10),
description="Debounce window for rapid changes (seconds)",
): vol.All(int, vol.Range(min=5, max=60)),
vol.Optional(
CONF_SMART_POLLING_OPTIMISTIC_TIMEOUT,
default=options.get(CONF_SMART_POLLING_OPTIMISTIC_TIMEOUT, 15),
description="Maximum optimistic state duration (seconds)",
): vol.All(int, vol.Range(min=10, max=60)),
}
)
return self.async_show_form(
step_id="init", data_schema=options_schema, description_placeholders={"name": self.config_entry.title}
)