| 1 |
import asyncio |
| 2 |
import contextlib |
| 3 |
import logging |
| 4 |
import select |
| 5 |
import socket |
| 6 |
import time |
| 7 |
from datetime import date |
| 8 |
from typing import ( |
| 9 |
Optional, |
| 10 |
TypedDict, |
| 11 |
Union, |
| 12 |
) |
| 13 |
|
| 14 |
from .const import ( |
| 15 |
ATTR_FIRMWARE_DATE, |
| 16 |
ATTR_ID, |
| 17 |
ATTR_IPADDR, |
| 18 |
ATTR_MODEL, |
| 19 |
ATTR_MODEL_DESCRIPTION, |
| 20 |
ATTR_MODEL_INFO, |
| 21 |
ATTR_MODEL_NUM, |
| 22 |
ATTR_REMOTE_ACCESS_ENABLED, |
| 23 |
ATTR_REMOTE_ACCESS_HOST, |
| 24 |
ATTR_REMOTE_ACCESS_PORT, |
| 25 |
ATTR_VERSION_NUM, |
| 26 |
) |
| 27 |
from .models_db import get_model_description |
| 28 |
|
| 29 |
_LOGGER = logging.getLogger(__name__) |
| 30 |
|
| 31 |
MESSAGE_SEND_INTERLEAVE_DELAY = 0.4 |
| 32 |
LEGACY_OUI = "ACCF23" |
| 33 |
|
| 34 |
|
| 35 |
class FluxLEDDiscovery(TypedDict): |
| 36 |
"""A flux led device.""" |
| 37 |
|
| 38 |
ipaddr: str |
| 39 |
id: Optional[str] |
| 40 |
model: Optional[str] |
| 41 |
model_num: Optional[int] |
| 42 |
version_num: Optional[int] |
| 43 |
firmware_date: Optional[date] |
| 44 |
model_info: Optional[str] |
| 45 |
model_description: Optional[str] |
| 46 |
remote_access_enabled: Optional[bool] |
| 47 |
remote_access_host: Optional[str] |
| 48 |
remote_access_port: Optional[int] |
| 49 |
|
| 50 |
|
| 51 |
def is_legacy_device(discovery: Optional[FluxLEDDiscovery]) -> bool: |
| 52 |
"""Check if a discovery is a legacy device.""" |
| 53 |
if not discovery: |
| 54 |
return False |
| 55 |
is_legacy_mac = False |
| 56 |
if discovery.get(ATTR_ID): |
| 57 |
mac = discovery[ATTR_ID] |
| 58 |
assert mac is not None |
| 59 |
is_legacy_mac = mac.startswith(LEGACY_OUI) |
| 60 |
return is_legacy_mac or bool( |
| 61 |
discovery.get(ATTR_VERSION_NUM) and not discovery.get(ATTR_MODEL_NUM) |
| 62 |
) |
| 63 |
|
| 64 |
|
| 65 |
def create_udp_socket(discovery_port: int) -> socket.socket: |
| 66 |
"""Create a udp socket used for communicating with the device.""" |
| 67 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 68 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 69 |
try: |
| 70 |
|
| 71 |
sock.bind(("", discovery_port)) |
| 72 |
except OSError as err: |
| 73 |
_LOGGER.debug("Port %s is not available: %s", discovery_port, err) |
| 74 |
sock.bind(("", 0)) |
| 75 |
sock.setblocking(False) |
| 76 |
return sock |
| 77 |
|
| 78 |
|
| 79 |
def merge_discoveries(target: FluxLEDDiscovery, source: FluxLEDDiscovery) -> None: |
| 80 |
"""Merge keys from a second discovery that may be missing from the first one.""" |
| 81 |
for k, v in source.items(): |
| 82 |
if target.get(k) is None: |
| 83 |
target[k] = v |
| 84 |
|
| 85 |
|
| 86 |
def _strip_new_lines(msg: str) -> str: |
| 87 |
return msg.replace("\r", "").replace("\n", "") |
| 88 |
|
| 89 |
|
| 90 |
def _process_discovery_message(data: FluxLEDDiscovery, decoded_data: str) -> None: |
| 91 |
"""Process response from b'HF-A11ASSISTHREAD' |
| 92 |
|
| 93 |
b'192.168.214.252,B4E842E10588,AK001-ZJ2145' |
| 94 |
""" |
| 95 |
data_split = _strip_new_lines(decoded_data).split(",") |
| 96 |
if len(data_split) < 3: |
| 97 |
return |
| 98 |
ipaddr = data_split[0] |
| 99 |
data.update( |
| 100 |
{ |
| 101 |
ATTR_IPADDR: ipaddr, |
| 102 |
ATTR_ID: data_split[1], |
| 103 |
ATTR_MODEL: data_split[2], |
| 104 |
} |
| 105 |
) |
| 106 |
|
| 107 |
|
| 108 |
def _process_version_message(data: FluxLEDDiscovery, decoded_data: str) -> None: |
| 109 |
r"""Process response from b'AT+LVER\r' |
| 110 |
|
| 111 |
b'+ok=07_06_20210106_ZG-BL\r' |
| 112 |
""" |
| 113 |
version_data = _strip_new_lines(decoded_data[4:]) |
| 114 |
data_split = version_data.split("_", maxsplit=3) |
| 115 |
if len(data_split) == 1: |
| 116 |
with contextlib.suppress(ValueError): |
| 117 |
data[ATTR_VERSION_NUM] = int(data_split[0], 16) |
| 118 |
return |
| 119 |
if len(data_split) >= 2: |
| 120 |
try: |
| 121 |
data[ATTR_MODEL_NUM] = int(data_split[0], 16) |
| 122 |
data[ATTR_VERSION_NUM] = int(data_split[1], 16) |
| 123 |
except ValueError: |
| 124 |
return |
| 125 |
assert data[ATTR_MODEL_NUM] is not None |
| 126 |
if len(data_split) >= 3: |
| 127 |
firmware_date = data_split[2] |
| 128 |
with contextlib.suppress(TypeError, ValueError): |
| 129 |
data[ATTR_FIRMWARE_DATE] = date( |
| 130 |
int(firmware_date[:4]), |
| 131 |
int(firmware_date[4:6]), |
| 132 |
int(firmware_date[6:8]), |
| 133 |
) |
| 134 |
if len(data_split) == 4: |
| 135 |
data[ATTR_MODEL_INFO] = data_split[3] |
| 136 |
data[ATTR_MODEL_DESCRIPTION] = get_model_description( |
| 137 |
data[ATTR_MODEL_NUM], data[ATTR_MODEL_INFO] |
| 138 |
) |
| 139 |
|
| 140 |
|
| 141 |
def _process_remote_access_message(data: FluxLEDDiscovery, decoded_data: str) -> None: |
| 142 |
"""Process response from b'AT+SOCKB\r' |
| 143 |
|
| 144 |
b'+ok=TCP,8816,ra8816us02.magichue.net\r' |
| 145 |
""" |
| 146 |
data_split = _strip_new_lines(decoded_data).split(",") |
| 147 |
if len(data_split) < 3: |
| 148 |
if not data.get(ATTR_REMOTE_ACCESS_ENABLED): |
| 149 |
data[ATTR_REMOTE_ACCESS_ENABLED] = False |
| 150 |
return |
| 151 |
try: |
| 152 |
data.update( |
| 153 |
{ |
| 154 |
ATTR_REMOTE_ACCESS_ENABLED: True, |
| 155 |
ATTR_REMOTE_ACCESS_PORT: int(data_split[1]), |
| 156 |
ATTR_REMOTE_ACCESS_HOST: data_split[2], |
| 157 |
} |
| 158 |
) |
| 159 |
except ValueError: |
| 160 |
return |
| 161 |
|
| 162 |
|
| 163 |
class BulbScanner: |
| 164 |
DISCOVERY_PORT = 48899 |
| 165 |
BROADCAST_FREQUENCY = 6 |
| 166 |
RESPONSE_SIZE = 64 |
| 167 |
DISCOVER_MESSAGE = b"HF-A11ASSISTHREAD" |
| 168 |
VERSION_MESSAGE = b"AT+LVER\r" |
| 169 |
REMOTE_ACCESS_MESSAGE = b"AT+SOCKB\r" |
| 170 |
DISABLE_REMOTE_ACCESS_MESSAGE = b"AT+SOCKB=NONE\r" |
| 171 |
REBOOT_MESSAGE = b"AT+Z\r" |
| 172 |
ALL_MESSAGES = {DISCOVER_MESSAGE, VERSION_MESSAGE, REMOTE_ACCESS_MESSAGE} |
| 173 |
BROADCAST_ADDRESS = "<broadcast>" |
| 174 |
|
| 175 |
def __init__(self) -> None: |
| 176 |
self._discoveries: dict[str, FluxLEDDiscovery] = {} |
| 177 |
|
| 178 |
@property |
| 179 |
def found_bulbs(self) -> list[FluxLEDDiscovery]: |
| 180 |
"""Return only complete bulb discoveries.""" |
| 181 |
return [info for info in self._discoveries.values() if info["id"]] |
| 182 |
|
| 183 |
def getBulbInfoByID(self, id: str) -> FluxLEDDiscovery: |
| 184 |
for b in self.found_bulbs: |
| 185 |
if b["id"] == id: |
| 186 |
return b |
| 187 |
return b |
| 188 |
|
| 189 |
def getBulbInfo(self) -> list[FluxLEDDiscovery]: |
| 190 |
return self.found_bulbs |
| 191 |
|
| 192 |
def _create_socket(self) -> socket.socket: |
| 193 |
return create_udp_socket(self.DISCOVERY_PORT) |
| 194 |
|
| 195 |
def _destination_from_address(self, address: Optional[str]) -> tuple[str, int]: |
| 196 |
if address is None: |
| 197 |
address = self.BROADCAST_ADDRESS |
| 198 |
return (address, self.DISCOVERY_PORT) |
| 199 |
|
| 200 |
def _process_response( |
| 201 |
self, |
| 202 |
data: Optional[bytes], |
| 203 |
from_address: tuple[str, int], |
| 204 |
address: Optional[str], |
| 205 |
response_list: dict[str, FluxLEDDiscovery], |
| 206 |
) -> bool: |
| 207 |
"""Process a response. |
| 208 |
|
| 209 |
Returns True if processing should stop |
| 210 |
""" |
| 211 |
if data is None: |
| 212 |
return False |
| 213 |
if data in self.ALL_MESSAGES: |
| 214 |
return False |
| 215 |
decoded_data = data.decode("ascii") |
| 216 |
self._process_data(from_address, decoded_data, response_list) |
| 217 |
if address is None or address not in response_list: |
| 218 |
return False |
| 219 |
response = response_list[address] |
| 220 |
return is_legacy_device(response) or ( |
| 221 |
response[ATTR_MODEL_NUM] is not None |
| 222 |
and response[ATTR_REMOTE_ACCESS_ENABLED] is not None |
| 223 |
) |
| 224 |
|
| 225 |
def _process_data( |
| 226 |
self, |
| 227 |
from_address: tuple[str, int], |
| 228 |
decoded_data: str, |
| 229 |
response_list: dict[str, FluxLEDDiscovery], |
| 230 |
) -> None: |
| 231 |
"""Process data.""" |
| 232 |
from_ipaddr = from_address[0] |
| 233 |
data = response_list.setdefault( |
| 234 |
from_ipaddr, |
| 235 |
FluxLEDDiscovery( |
| 236 |
ipaddr=from_ipaddr, |
| 237 |
id=None, |
| 238 |
model=None, |
| 239 |
model_num=None, |
| 240 |
version_num=None, |
| 241 |
firmware_date=None, |
| 242 |
model_info=None, |
| 243 |
model_description=None, |
| 244 |
remote_access_enabled=None, |
| 245 |
remote_access_host=None, |
| 246 |
remote_access_port=None, |
| 247 |
), |
| 248 |
) |
| 249 |
if ( |
| 250 |
decoded_data.startswith("+ok=T") |
| 251 |
or decoded_data == "+ok=" |
| 252 |
or decoded_data == "+ok=\r" |
| 253 |
): |
| 254 |
_process_remote_access_message(data, decoded_data) |
| 255 |
if decoded_data.startswith("+ok="): |
| 256 |
_process_version_message(data, decoded_data) |
| 257 |
elif "," in decoded_data: |
| 258 |
_process_discovery_message(data, decoded_data) |
| 259 |
|
| 260 |
def _get_start_messages( |
| 261 |
self, |
| 262 |
) -> list[bytes]: |
| 263 |
return [self.DISCOVER_MESSAGE] |
| 264 |
|
| 265 |
def _get_enable_remote_access_messages( |
| 266 |
self, |
| 267 |
remote_access_host: str, |
| 268 |
remote_access_port: int, |
| 269 |
) -> list[bytes]: |
| 270 |
enable_message = f"AT+SOCKB=TCP,{remote_access_port},{remote_access_host}\r" |
| 271 |
return [enable_message.encode()] |
| 272 |
|
| 273 |
def _get_disable_remote_access_messages( |
| 274 |
self, |
| 275 |
) -> list[bytes]: |
| 276 |
return [self.DISABLE_REMOTE_ACCESS_MESSAGE] |
| 277 |
|
| 278 |
def _get_reboot_messages( |
| 279 |
self, |
| 280 |
) -> list[bytes]: |
| 281 |
return [self.REBOOT_MESSAGE] |
| 282 |
|
| 283 |
def _send_message( |
| 284 |
self, |
| 285 |
sender: Union[socket.socket, asyncio.DatagramTransport], |
| 286 |
destination: tuple[str, int], |
| 287 |
message: bytes, |
| 288 |
) -> None: |
| 289 |
_LOGGER.debug("udp: %s => %s", destination, message) |
| 290 |
sender.sendto(message, destination) |
| 291 |
|
| 292 |
def _send_messages( |
| 293 |
self, |
| 294 |
messages: list[bytes], |
| 295 |
sender: Union[socket.socket, asyncio.DatagramTransport], |
| 296 |
destination: tuple[str, int], |
| 297 |
) -> None: |
| 298 |
"""Send messages with a short delay between them.""" |
| 299 |
for idx, message in enumerate(messages): |
| 300 |
self._send_message(sender, destination, message) |
| 301 |
if idx != len(messages): |
| 302 |
time.sleep(MESSAGE_SEND_INTERLEAVE_DELAY) |
| 303 |
|
| 304 |
def get_discovery_messages( |
| 305 |
self, |
| 306 |
) -> list[bytes]: |
| 307 |
return [self.DISCOVER_MESSAGE, self.VERSION_MESSAGE, self.REMOTE_ACCESS_MESSAGE] |
| 308 |
|
| 309 |
def scan( |
| 310 |
self, timeout: int = 10, address: Optional[str] = None |
| 311 |
) -> list[FluxLEDDiscovery]: |
| 312 |
"""Scan for bulbs. |
| 313 |
|
| 314 |
If an address is provided, the scan will return |
| 315 |
as soon as it gets a response from that address |
| 316 |
""" |
| 317 |
discovery_messages = self.get_discovery_messages() |
| 318 |
sock = self._create_socket() |
| 319 |
destination = self._destination_from_address(address) |
| 320 |
|
| 321 |
quit_time = time.monotonic() + timeout |
| 322 |
found_all = False |
| 323 |
|
| 324 |
while not found_all: |
| 325 |
if time.monotonic() > quit_time: |
| 326 |
break |
| 327 |
|
| 328 |
self._send_messages(discovery_messages, sock, destination) |
| 329 |
|
| 330 |
while True: |
| 331 |
sock.settimeout(1) |
| 332 |
remain_time = quit_time - time.monotonic() |
| 333 |
time_out = min(remain_time, timeout / self.BROADCAST_FREQUENCY) |
| 334 |
if time_out <= 0: |
| 335 |
break |
| 336 |
read_ready, _, _ = select.select([sock], [], [], time_out) |
| 337 |
if not read_ready: |
| 338 |
if time.monotonic() < quit_time: |
| 339 |
|
| 340 |
self._send_messages(discovery_messages, sock, destination) |
| 341 |
continue |
| 342 |
|
| 343 |
try: |
| 344 |
data, addr = sock.recvfrom(self.RESPONSE_SIZE) |
| 345 |
_LOGGER.debug("discover: %s <= %s", addr, data) |
| 346 |
except socket.timeout: |
| 347 |
continue |
| 348 |
|
| 349 |
if self._process_response(data, addr, address, self._discoveries): |
| 350 |
found_all = True |
| 351 |
break |
| 352 |
|
| 353 |
return self.found_bulbs |