-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig_flow.py
189 lines (160 loc) · 7 KB
/
config_flow.py
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
import asyncio
from .coordinator import PranaCoordinator
from .const import DOMAIN
from typing import Any
from homeassistant import config_entries
from homeassistant.const import CONF_MAC
import voluptuous as vol
from homeassistant.helpers.device_registry import format_mac
from homeassistant.data_entry_flow import FlowResult
from homeassistant.components.bluetooth import (
BluetoothServiceInfoBleak,
async_discovered_service_info,
)
from bluetooth_sensor_state_data import BluetoothData
from home_assistant_bluetooth import BluetoothServiceInfo
import logging
LOGGER = logging.getLogger(__name__)
DATA_SCHEMA = vol.Schema({("host"): str})
MANUAL_MAC = "manual"
class DeviceData(BluetoothData):
def __init__(self, discovery_info) -> None:
self._discovery = discovery_info
def supported(self):
return self._discovery.name.lower().startswith("prna")
def address(self):
return self._discovery.address
def get_device_name(self):
return self._discovery.name
def name(self):
return self._discovery.name
def rssi(self):
return self._discovery.rssi
def _start_update(self, service_info: BluetoothServiceInfo) -> None:
"""Update from BLE advertisement data."""
LOGGER.debug("Parsing Govee BLE advertisement data: %s", service_info)
class BLEDOMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
def __init__(self) -> None:
self.mac = None
self._device = None
self._instance = None
self.name = None
self._discovery_info: BluetoothServiceInfoBleak | None = None
self._discovered_device: DeviceData | None = None
self._discovered_devices = []
async def async_step_bluetooth(
self, discovery_info: BluetoothServiceInfoBleak
) -> FlowResult:
"""Handle the bluetooth discovery step."""
LOGGER.debug("Discovered bluetooth devices, step bluetooth, : %s , %s", discovery_info.address, discovery_info.name)
await self.async_set_unique_id(discovery_info.address)
self._abort_if_unique_id_configured()
device = DeviceData(discovery_info)
if device.supported():
self._discovered_devices.append(device)
return await self.async_step_bluetooth_confirm()
else:
return self.async_abort(reason="not_supported")
async def async_step_bluetooth_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Confirm discovery."""
LOGGER.debug("Discovered bluetooth devices, step bluetooth confirm, : %s", user_input)
self._set_confirm_only()
return await self.async_step_user()
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the user step to pick discovered device."""
if user_input is not None:
if user_input[CONF_MAC] == MANUAL_MAC:
return await self.async_step_manual()
self.mac = user_input[CONF_MAC]
self.name = user_input["name"]
await self.async_set_unique_id(self.mac, raise_on_progress=False)
self._abort_if_unique_id_configured()
return await self.async_step_validate()
current_addresses = self._async_current_ids()
for discovery_info in async_discovered_service_info(self.hass):
self.mac = discovery_info.address
if self.mac in current_addresses:
LOGGER.debug("Device %s in current_addresses", (self.mac))
continue
if (device for device in self._discovered_devices if device.address == self.mac) == ([]):
LOGGER.debug("Device %s in discovered_devices", (device))
continue
device = DeviceData(discovery_info)
if device.supported():
self._discovered_devices.append(device)
if not self._discovered_devices:
return await self.async_step_manual()
LOGGER.debug("Discovered supported devices: %s - %s", self._discovered_devices[0].name(), self._discovered_devices[0].address())
return self.async_show_form(
step_id="user", data_schema=vol.Schema(
{
vol.Required(CONF_MAC): vol.In(
{
##TODO: Show all supported devices
self._discovered_devices[0].address(): self._discovered_devices[0].name(),
MANUAL_MAC: "Manually add a MAC address",
}
),
vol.Required("name"): str
}
),
errors={})
async def async_step_validate(self, user_input: "dict[str, Any] | None" = None):
if user_input is not None:
if "flicker" in user_input:
if user_input["flicker"]:
return self.async_create_entry(title=self.name, data={CONF_MAC: self.mac, "name": self.name})
return self.async_abort(reason="cannot_validate")
if "retry" in user_input and not user_input["retry"]:
return self.async_abort(reason="cannot_connect")
error = await self.turn_on()
if error:
return self.async_show_form(
step_id="validate", data_schema=vol.Schema(
{
vol.Required("retry"): bool
}
), errors={"base": "connect"})
return self.async_show_form(
step_id="validate", data_schema=vol.Schema(
{
vol.Required("flicker"): bool
}
), errors={})
async def async_step_manual(self, user_input: "dict[str, Any] | None" = None):
if user_input is not None:
self.mac = user_input[CONF_MAC]
self.name = user_input["name"]
await self.async_set_unique_id(format_mac(self.mac))
return await self.async_step_validate()
return self.async_show_form(
step_id="manual", data_schema=vol.Schema(
{
vol.Required(CONF_MAC): str,
vol.Required("name"): str
}
), errors={})
async def turn_on(self):
if not self._instance:
self._instance = PranaCoordinator(self.mac, self.hass)
try:
await self._instance._async_update_data()
if self._instance.is_on:
await self._instance.turn_off()
await asyncio.sleep(2)
await self._instance.turn_on()
else:
await self._instance.turn_on()
await asyncio.sleep(2)
await self._instance.turn_off()
except (Exception) as error:
LOGGER.debug("Error talking to prana.", exc_info=True)
return error
finally:
await self._instance.stop()