| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import ipaddress |
| 5 |
import logging |
| 6 |
import socket |
| 7 |
import warnings |
| 8 |
from collections.abc import Callable |
| 9 |
from datetime import datetime, timedelta, timezone |
| 10 |
from typing import Any |
| 11 |
|
| 12 |
from .device import GoveeDevice |
| 13 |
from .device_registry import DeviceRegistry |
| 14 |
from .light_capabilities import ( |
| 15 |
GOVEE_LIGHT_CAPABILITIES, |
| 16 |
ON_OFF_CAPABILITIES, |
| 17 |
GoveeLightFeatures, |
| 18 |
) |
| 19 |
from .message import ( |
| 20 |
HexMessage, |
| 21 |
BrightnessMessage, |
| 22 |
ColorMessage, |
| 23 |
SceneMessages, |
| 24 |
GoveeMessage, |
| 25 |
MessageResponseFactory, |
| 26 |
OnOffMessage, |
| 27 |
ScanMessage, |
| 28 |
ScanResponse, |
| 29 |
SegmentColorMessages, |
| 30 |
DevStatusMessage, |
| 31 |
DevStatusResponse, |
| 32 |
) |
| 33 |
from .network import ( |
| 34 |
_parse_listening_addresses, |
| 35 |
_is_ip_in_same_network_heuristic, |
| 36 |
) |
| 37 |
from .protocol import GoveeControllerProtocol |
| 38 |
|
| 39 |
BROADCAST_ADDRESS = "239.255.255.250" |
| 40 |
BROADCAST_PORT = 4001 |
| 41 |
LISTENING_PORT = 4002 |
| 42 |
COMMAND_PORT = 4003 |
| 43 |
|
| 44 |
DISCOVERY_INTERVAL = 10 |
| 45 |
EVICT_INTERVAL = DISCOVERY_INTERVAL * 3 |
| 46 |
UPDATE_INTERVAL = 5 |
| 47 |
|
| 48 |
|
| 49 |
class GoveeController: |
| 50 |
def __init__( |
| 51 |
self, |
| 52 |
loop=None, |
| 53 |
broadcast_address: str = BROADCAST_ADDRESS, |
| 54 |
broadcast_port: int = BROADCAST_PORT, |
| 55 |
listening_addresses: str | list[str] | None = None, |
| 56 |
listening_port: int = LISTENING_PORT, |
| 57 |
device_command_port: int = COMMAND_PORT, |
| 58 |
discovery_enabled: bool = False, |
| 59 |
discovery_interval: int = DISCOVERY_INTERVAL, |
| 60 |
evict_enabled: bool = False, |
| 61 |
evict_interval: int = EVICT_INTERVAL, |
| 62 |
update_enabled: bool = True, |
| 63 |
update_interval: int = UPDATE_INTERVAL, |
| 64 |
discovered_callback: Callable[[GoveeDevice, bool], bool] | None = None, |
| 65 |
evicted_callback: Callable[[GoveeDevice], None] | None = None, |
| 66 |
logger: logging.Logger | None = None, |
| 67 |
listening_address: str | list[str] | None = None, |
| 68 |
) -> None: |
| 69 |
"""Build a controller that handle Govee devices that support local API on local network. |
| 70 |
|
| 71 |
Args: |
| 72 |
loop: The asyncio event loop. If None the loop is retrieved by calling ``asyncio.get_running_loop()`` |
| 73 |
broadcast_address (str): The multicast address to use to send discovery messages. Default: 239.255.255.250 |
| 74 |
broadcast_port (int): Devices port where discovery messages are sent. Default: 4001 |
| 75 |
listening_addresses (str | list[str]): Local IP addresses on which the controller listens for incoming |
| 76 |
devices' messages. Can be a single address or a list of addresses. Supports optional CIDR or netmask |
| 77 |
notation (e.g., "192.168.1.100/24" or "192.168.1.100/255.255.255.0"). When a mask is provided, |
| 78 |
precise subnet matching is used for transport selection; an invalid mask raises ValueError. |
| 79 |
Default: "0.0.0.0" |
| 80 |
listening_port (int): Local UDP port on which the controller listen for incoming devices' messages |
| 81 |
device_command_port (int): The devices' port where the commands should be sent |
| 82 |
discovery_enabled (bool): If true a discovery message is sent every ``discovery_interval`` seconds. Default: False |
| 83 |
discovery_interval (int): Interval between discovery messages (if discovery is enabled). Default: 10 seconds |
| 84 |
evict_enabled (bool): If true the controller automatically removes devices not seen for ``evict_interval`` seconds. Eviction runs on its own periodic check (every ``evict_interval`` seconds) and opportunistically when scan responses arrive. |
| 85 |
evict_interval (int): Interval after which a device is evicted. Default 30 seconds |
| 86 |
update_enabled (bool): If true the devices status is updated automatically every ``update_interval`` seconds. A successful device update reset the eviction timer for the device. Default: True |
| 87 |
update_interval (int): Interval between a status update is requested to devices. |
| 88 |
discovered_callback (Callable[GoveeDevice, bool]): An optional function to call when a device is discovered (or rediscovered). Default None |
| 89 |
evicted_callback (Callable[GoveeDevice]): An optional function to call when a device is evicted. |
| 90 |
listening_address (str | list[str]): Deprecated alias of ``listening_addresses`` kept for |
| 91 |
backward compatibility (pre-3.0 name); emits a DeprecationWarning. |
| 92 |
""" |
| 93 |
if listening_address is not None: |
| 94 |
warnings.warn( |
| 95 |
"The 'listening_address' argument is deprecated and will be " |
| 96 |
"removed in a future release; use 'listening_addresses' instead.", |
| 97 |
DeprecationWarning, |
| 98 |
stacklevel=2, |
| 99 |
) |
| 100 |
if listening_addresses is not None: |
| 101 |
raise ValueError( |
| 102 |
"Pass either 'listening_addresses' or the deprecated " |
| 103 |
"'listening_address', not both" |
| 104 |
) |
| 105 |
listening_addresses = listening_address |
| 106 |
if listening_addresses is None: |
| 107 |
listening_addresses = "0.0.0.0" |
| 108 |
|
| 109 |
self._logger = logger or logging.getLogger(__name__) |
| 110 |
|
| 111 |
self._transports: list[Any] = [] |
| 112 |
self._protocols: list[Any] = [] |
| 113 |
self._broadcast_address = broadcast_address |
| 114 |
self._broadcast_port = broadcast_port |
| 115 |
self._listening_port = listening_port |
| 116 |
self._device_command_port = device_command_port |
| 117 |
self._listening_addresses, self._networks = _parse_listening_addresses( |
| 118 |
listening_addresses |
| 119 |
) |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
for addr in self._listening_addresses: |
| 124 |
try: |
| 125 |
ipaddress.IPv4Address(addr) |
| 126 |
except (ipaddress.AddressValueError, ValueError) as exc: |
| 127 |
raise ValueError(f"Invalid IPv4 listening address: {addr!r}") from exc |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
seen: set[str] = set() |
| 133 |
deduped: list[tuple[str, ipaddress.IPv4Network | None]] = [] |
| 134 |
for addr, net in zip(self._listening_addresses, self._networks): |
| 135 |
if addr in seen: |
| 136 |
self._logger.warning( |
| 137 |
"Duplicate listening address %s; ignoring extra entry", |
| 138 |
addr, |
| 139 |
) |
| 140 |
continue |
| 141 |
seen.add(addr) |
| 142 |
deduped.append((addr, net)) |
| 143 |
self._listening_addresses = [a for a, _ in deduped] |
| 144 |
self._networks = [n for _, n in deduped] |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
if ( |
| 149 |
len(self._listening_addresses) > 1 |
| 150 |
and "0.0.0.0" in self._listening_addresses |
| 151 |
): |
| 152 |
self._logger.warning( |
| 153 |
"Wildcard address 0.0.0.0 mixed with specific addresses %s; " |
| 154 |
"dropping 0.0.0.0 to avoid duplicate packet processing", |
| 155 |
[a for a in self._listening_addresses if a != "0.0.0.0"], |
| 156 |
) |
| 157 |
filtered = [ |
| 158 |
(addr, net) |
| 159 |
for addr, net in zip(self._listening_addresses, self._networks) |
| 160 |
if addr != "0.0.0.0" |
| 161 |
] |
| 162 |
self._listening_addresses = [a for a, _ in filtered] |
| 163 |
self._networks = [n for _, n in filtered] |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
if not self._listening_addresses: |
| 168 |
raise ValueError("listening_addresses resulted in an empty configuration") |
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
self._configured_addresses: list[str] = list(self._listening_addresses) |
| 174 |
self._configured_networks: list[ipaddress.IPv4Network | None] = list( |
| 175 |
self._networks |
| 176 |
) |
| 177 |
|
| 178 |
|
| 179 |
try: |
| 180 |
self._loop = loop or asyncio.get_running_loop() |
| 181 |
except RuntimeError: |
| 182 |
|
| 183 |
self._loop = loop or asyncio.new_event_loop() |
| 184 |
|
| 185 |
self._cleanup_done: asyncio.Event = asyncio.Event() |
| 186 |
self._message_factory = MessageResponseFactory() |
| 187 |
self._registry: DeviceRegistry = DeviceRegistry(self._logger) |
| 188 |
|
| 189 |
self._discovery_enabled = discovery_enabled |
| 190 |
self._discovery_interval = discovery_interval |
| 191 |
self._update_enabled = update_enabled |
| 192 |
self._update_interval = update_interval |
| 193 |
self._evict_enabled = evict_enabled |
| 194 |
self._evict_interval = evict_interval |
| 195 |
|
| 196 |
self._device_discovered_callback = discovered_callback |
| 197 |
self._device_evicted_callback = evicted_callback |
| 198 |
|
| 199 |
self._discovery_handle: asyncio.TimerHandle | None = None |
| 200 |
self._update_handle: asyncio.TimerHandle | None = None |
| 201 |
self._evict_handle: asyncio.TimerHandle | None = None |
| 202 |
self._cleanup_timeout_handle: asyncio.TimerHandle | None = None |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
self._closing: bool = False |
| 209 |
self._pending_close: int = 0 |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
self._response_handler: dict[str, Callable] = { |
| 215 |
ScanResponse.command: self._handle_scan_response, |
| 216 |
DevStatusResponse.command: self._handle_status_update_response, |
| 217 |
} |
| 218 |
|
| 219 |
async def start(self): |
| 220 |
self._closing = False |
| 221 |
|
| 222 |
|
| 223 |
self._listening_addresses = list(self._configured_addresses) |
| 224 |
self._networks = list(self._configured_networks) |
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
e. |
| 229 |
try: |
| 230 |
for listening_address in self._listening_addresses: |
| 231 |
sock = self._create_listening_socket(listening_address) |
| 232 |
try: |
| 233 |
transport, protocol = await self._loop.create_datagram_endpoint( |
| 234 |
lambda addr=listening_address: GoveeControllerProtocol( |
| 235 |
self, addr |
| 236 |
), |
| 237 |
sock=sock, |
| 238 |
) |
| 239 |
except Exception: |
| 240 |
sock.close() |
| 241 |
raise |
| 242 |
self._transports.append(transport) |
| 243 |
self._protocols.append(protocol) |
| 244 |
except Exception: |
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
transports = self._transports[:] |
| 250 |
self._transports.clear() |
| 251 |
self._protocols.clear() |
| 252 |
for transport in transports: |
| 253 |
if transport is not None and not transport.is_closing(): |
| 254 |
transport.close() |
| 255 |
raise |
| 256 |
|
| 257 |
if self._discovery_enabled or self._registry.has_queued_devices: |
| 258 |
self.send_discovery_message() |
| 259 |
if self._update_enabled: |
| 260 |
self.send_update_message() |
| 261 |
if self._evict_enabled: |
| 262 |
self._schedule_evict() |
| 263 |
|
| 264 |
def _create_listening_socket(self, listening_address: str) -> socket.socket: |
| 265 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 266 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 267 |
|
| 268 |
|
| 269 |
t. |
| 270 |
reuse_port = getattr(socket, "SO_REUSEPORT", None) |
| 271 |
if reuse_port is not None: |
| 272 |
try: |
| 273 |
sock.setsockopt(socket.SOL_SOCKET, reuse_port, 1) |
| 274 |
except OSError: |
| 275 |
pass |
| 276 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 277 |
try: |
| 278 |
sock.bind((listening_address, self._listening_port)) |
| 279 |
except OSError: |
| 280 |
sock.close() |
| 281 |
raise |
| 282 |
return sock |
| 283 |
|
| 284 |
def cleanup(self, timeout: float = 2.0) -> asyncio.Event: |
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
if not self._transports and self._cleanup_done.is_set(): |
| 290 |
return self._cleanup_done |
| 291 |
|
| 292 |
self._cleanup_done.clear() |
| 293 |
already_closing = self._closing |
| 294 |
self._closing = True |
| 295 |
self.set_update_enabled(False) |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
self._discovery_enabled = False |
| 300 |
if self._discovery_handle is not None: |
| 301 |
self._discovery_handle.cancel() |
| 302 |
self._discovery_handle = None |
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
self.set_evict_enabled(False) |
| 307 |
|
| 308 |
if not self._transports: |
| 309 |
self._cleanup_done.set() |
| 310 |
self._registry.cleanup() |
| 311 |
return self._cleanup_done |
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
d. |
| 316 |
if not already_closing: |
| 317 |
self._pending_close = len(self._transports) |
| 318 |
for transport in self._transports: |
| 319 |
if transport is not None and not transport.is_closing(): |
| 320 |
transport.close() |
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
if self._cleanup_timeout_handle is not None: |
| 326 |
self._cleanup_timeout_handle.cancel() |
| 327 |
self._cleanup_timeout_handle = self._loop.call_later( |
| 328 |
timeout, self._force_cleanup_done |
| 329 |
) |
| 330 |
|
| 331 |
self._registry.cleanup() |
| 332 |
return self._cleanup_done |
| 333 |
|
| 334 |
def _force_cleanup_done(self) -> None: |
| 335 |
self._cleanup_timeout_handle = None |
| 336 |
if self._cleanup_done.is_set(): |
| 337 |
return |
| 338 |
stragglers = [ |
| 339 |
self._listening_addresses[i] |
| 340 |
for i, t in enumerate(self._transports) |
| 341 |
if t is not None |
| 342 |
and not t.is_closing() |
| 343 |
and i < len(self._listening_addresses) |
| 344 |
] |
| 345 |
if stragglers: |
| 346 |
self._logger.warning( |
| 347 |
"cleanup() timed out waiting for connection_lost; " |
| 348 |
"forcing completion. Stragglers: %s", |
| 349 |
stragglers, |
| 350 |
) |
| 351 |
self._transports.clear() |
| 352 |
self._protocols.clear() |
| 353 |
self._cleanup_done.set() |
| 354 |
|
| 355 |
@property |
| 356 |
def protocols(self) -> list: |
| 357 |
"""Return the list of active protocols.""" |
| 358 |
return self._protocols |
| 359 |
|
| 360 |
def add_device_to_discovery_queue(self, ip: str) -> bool: |
| 361 |
ip_added: bool = self._registry.add_device_to_queue(ip) |
| 362 |
if not self._discovery_enabled and ip_added: |
| 363 |
self.send_discovery_message() |
| 364 |
return ip_added |
| 365 |
|
| 366 |
def reconnect(self) -> None: |
| 367 |
"""Trigger a fresh discovery and update all known devices.""" |
| 368 |
self._logger.info("Triggering aggressive reconnection/discovery...") |
| 369 |
self.send_discovery_message() |
| 370 |
self.send_update_message() |
| 371 |
|
| 372 |
def remove_device_from_discovery_queue(self, ip: str) -> bool: |
| 373 |
return self._registry.remove_device_from_queue(ip) |
| 374 |
|
| 375 |
@property |
| 376 |
def discovery_queue(self) -> set[str]: |
| 377 |
return self._registry.devices_queue |
| 378 |
|
| 379 |
def remove_device(self, device: str | GoveeDevice) -> None: |
| 380 |
if isinstance(device, GoveeDevice): |
| 381 |
device = device.fingerprint |
| 382 |
self._registry.remove_discovered_device(device) |
| 383 |
|
| 384 |
@property |
| 385 |
def evict_enabled(self) -> bool: |
| 386 |
return self._evict_enabled |
| 387 |
|
| 388 |
@property |
| 389 |
def evict_interval(self) -> int: |
| 390 |
return self._evict_interval |
| 391 |
|
| 392 |
def set_evict_enabled(self, enabled: bool) -> None: |
| 393 |
if self._evict_enabled == enabled: |
| 394 |
return |
| 395 |
self._evict_enabled = enabled |
| 396 |
if enabled: |
| 397 |
self._schedule_evict() |
| 398 |
elif self._evict_handle is not None: |
| 399 |
self._evict_handle.cancel() |
| 400 |
self._evict_handle = None |
| 401 |
|
| 402 |
def set_discovery_enabled(self, enabled: bool) -> None: |
| 403 |
if self._discovery_enabled == enabled: |
| 404 |
return |
| 405 |
self._discovery_enabled = enabled |
| 406 |
if enabled: |
| 407 |
self.send_discovery_message() |
| 408 |
elif self._discovery_handle: |
| 409 |
self._discovery_handle.cancel() |
| 410 |
self._discovery_handle = None |
| 411 |
|
| 412 |
|
| 413 |
has_manual_devices = any( |
| 414 |
device.is_manual |
| 415 |
for device in self._registry.discovered_devices.values() |
| 416 |
) |
| 417 |
if self._registry.has_queued_devices or has_manual_devices: |
| 418 |
self.send_discovery_message() |
| 419 |
|
| 420 |
@property |
| 421 |
def discovery(self) -> bool: |
| 422 |
return self._discovery_enabled |
| 423 |
|
| 424 |
def set_discovery_interval(self, interval: int) -> None: |
| 425 |
self._discovery_interval = interval |
| 426 |
|
| 427 |
@property |
| 428 |
def discovery_interval(self) -> int: |
| 429 |
return self._discovery_interval |
| 430 |
|
| 431 |
@property |
| 432 |
def listening_addresses(self) -> list[str]: |
| 433 |
"""Get the list of listening addresses.""" |
| 434 |
return self._listening_addresses.copy() |
| 435 |
|
| 436 |
@property |
| 437 |
def networks(self) -> list[ipaddress.IPv4Network | None]: |
| 438 |
"""Get the list of parsed networks for each listening address.""" |
| 439 |
return self._networks.copy() |
| 440 |
|
| 441 |
def set_device_discovered_callback( |
| 442 |
self, callback: Callable[[GoveeDevice, bool], bool] | None |
| 443 |
) -> Callable[[GoveeDevice, bool], bool] | None: |
| 444 |
old_callback = self._device_discovered_callback |
| 445 |
self._device_discovered_callback = callback |
| 446 |
return old_callback |
| 447 |
|
| 448 |
def set_update_enabled(self, enabled: bool) -> None: |
| 449 |
if self._update_enabled == enabled: |
| 450 |
return |
| 451 |
self._update_enabled = enabled |
| 452 |
if enabled: |
| 453 |
self.send_update_message() |
| 454 |
elif self._update_handle: |
| 455 |
self._update_handle.cancel() |
| 456 |
self._update_handle = None |
| 457 |
|
| 458 |
@property |
| 459 |
def update_enabled(self) -> bool: |
| 460 |
return self._update_enabled |
| 461 |
|
| 462 |
def send_discovery_message(self) -> None: |
| 463 |
message: bytes = bytes(ScanMessage()) |
| 464 |
call_later: bool = False |
| 465 |
if not self._transports: |
| 466 |
return |
| 467 |
|
| 468 |
if self._discovery_enabled: |
| 469 |
call_later = True |
| 470 |
|
| 471 |
for i, transport in enumerate(self._transports): |
| 472 |
self._logger.debug( |
| 473 |
"Sending discovery broadcast from interface %s (%s) to %s:%s", |
| 474 |
i, |
| 475 |
self._listening_addresses[i], |
| 476 |
self._broadcast_address, |
| 477 |
self._broadcast_port, |
| 478 |
) |
| 479 |
transport.sendto( |
| 480 |
message, (self._broadcast_address, self._broadcast_port) |
| 481 |
) |
| 482 |
|
| 483 |
if self._registry.has_queued_devices: |
| 484 |
call_later = True |
| 485 |
|
| 486 |
for ip in list(self._registry.devices_queue): |
| 487 |
transport = self._get_best_transport_for_ip(ip) |
| 488 |
transport.sendto(message, (ip, self._broadcast_port)) |
| 489 |
|
| 490 |
manually_added_devices = [ |
| 491 |
device.ip |
| 492 |
for device in self._registry.discovered_devices.values() |
| 493 |
if device.is_manual |
| 494 |
] |
| 495 |
if manually_added_devices: |
| 496 |
call_later = True |
| 497 |
|
| 498 |
for ip in manually_added_devices: |
| 499 |
transport = self._get_best_transport_for_ip(ip) |
| 500 |
transport.sendto(message, (ip, self._broadcast_port)) |
| 501 |
|
| 502 |
if call_later: |
| 503 |
ke |
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
if self._discovery_handle is not None: |
| 508 |
self._discovery_handle.cancel() |
| 509 |
self._discovery_handle = self._loop.call_later( |
| 510 |
self._discovery_interval, self.send_discovery_message |
| 511 |
) |
| 512 |
|
| 513 |
def send_update_message(self) -> None: |
| 514 |
if self._transports: |
| 515 |
for d in self._registry.discovered_devices.values(): |
| 516 |
self._send_update_message(device=d) |
| 517 |
|
| 518 |
if self._update_enabled: |
| 519 |
if self._update_handle is not None: |
| 520 |
self._update_handle.cancel() |
| 521 |
self._update_handle = self._loop.call_later( |
| 522 |
self._update_interval, self.send_update_message |
| 523 |
) |
| 524 |
|
| 525 |
async def turn_on_off(self, device: GoveeDevice, status: bool) -> None: |
| 526 |
self._send_message(OnOffMessage(status), device) |
| 527 |
|
| 528 |
async def set_segment_rgb_color( |
| 529 |
self, device: GoveeDevice, segment: int, rgb: tuple[int, int, int] |
| 530 |
) -> None: |
| 531 |
if not device.capabilities: |
| 532 |
self._logger.warning("Capabilities not available for device %s", device) |
| 533 |
return |
| 534 |
|
| 535 |
if device.capabilities.features & GoveeLightFeatures.SEGMENT_CONTROL == 0: |
| 536 |
self._logger.warning( |
| 537 |
"Segment control is not supported by device %s", device |
| 538 |
) |
| 539 |
return |
| 540 |
|
| 541 |
if segment < 1 or segment > len(device.capabilities.segments): |
| 542 |
self._logger.warning( |
| 543 |
"Segment index %s is not valid for device %s", segment, device |
| 544 |
) |
| 545 |
return |
| 546 |
|
| 547 |
segment_data: bytes = device.capabilities.segments[segment - 1] |
| 548 |
if not segment_data: |
| 549 |
self._logger.warning( |
| 550 |
"Segment %s is not supported by device %s", segment, device |
| 551 |
) |
| 552 |
return |
| 553 |
message = SegmentColorMessages(segment_data, rgb) |
| 554 |
self._logger.debug(f"Sending message {message} to device {device}") |
| 555 |
self._send_message(message, device) |
| 556 |
|
| 557 |
async def set_scene(self, device: GoveeDevice, scene: str) -> None: |
| 558 |
if ( |
| 559 |
not device.capabilities |
| 560 |
or device.capabilities.features & GoveeLightFeatures.SCENES == 0 |
| 561 |
): |
| 562 |
self._logger.warning("Scenes are not supported by device %s", device) |
| 563 |
return |
| 564 |
|
| 565 |
scene_code: bytes | None = device.capabilities.scenes.get(scene.lower(), None) |
| 566 |
if not scene_code: |
| 567 |
self._logger.warning( |
| 568 |
"Scene %s is not available for device %s", scene, device |
| 569 |
) |
| 570 |
return |
| 571 |
self._send_message(SceneMessages(scene_code), device) |
| 572 |
|
| 573 |
async def set_brightness(self, device: GoveeDevice, brightness: int) -> None: |
| 574 |
self._send_message(BrightnessMessage(brightness), device) |
| 575 |
|
| 576 |
async def set_color( |
| 577 |
self, |
| 578 |
device: GoveeDevice, |
| 579 |
*, |
| 580 |
rgb: tuple[int, int, int] | None, |
| 581 |
temperature: int | None, |
| 582 |
) -> None: |
| 583 |
if rgb: |
| 584 |
self._send_message(ColorMessage(rgb=rgb, temperature=None), device) |
| 585 |
else: |
| 586 |
self._send_message(ColorMessage(rgb=None, temperature=temperature), device) |
| 587 |
|
| 588 |
async def send_raw_command(self, device: GoveeDevice, command: str) -> None: |
| 589 |
self._send_message(HexMessage([command]), device) |
| 590 |
|
| 591 |
def get_device_by_ip(self, ip: str) -> GoveeDevice | None: |
| 592 |
return self._registry.get_device_by_ip(ip) |
| 593 |
|
| 594 |
def get_device_by_sku(self, sku: str) -> GoveeDevice | None: |
| 595 |
return self._registry.get_device_by_sku(sku) |
| 596 |
|
| 597 |
def get_device_by_fingerprint(self, fingerprint: str) -> GoveeDevice | None: |
| 598 |
return self._registry.get_device_by_fingerprint(fingerprint) |
| 599 |
|
| 600 |
@property |
| 601 |
def devices(self) -> list[GoveeDevice]: |
| 602 |
return list(self._registry.discovered_devices.values()) |
| 603 |
|
| 604 |
def _protocol_disconnected( |
| 605 |
self, protocol: GoveeControllerProtocol | None = None |
| 606 |
) -> None: |
| 607 |
"""Called from connection_lost of each protocol. |
| 608 |
|
| 609 |
During cleanup() this counts down the protocols still owed a |
| 610 |
connection_lost and signals completion only once ALL of them have |
| 611 |
delivered it — a transport reports is_closing() immediately after |
| 612 |
close(), so checking that (the old behavior) fired cleanup_done on |
| 613 |
the first callback while other sockets were still tearing down. |
| 614 |
|
| 615 |
Outside cleanup() a connection_lost means an internal transport |
| 616 |
failure (no realistic UDP trigger on Linux — OSErrors go to |
| 617 |
error_received — but abort()/fatal errors reach here). Drop the dead |
| 618 |
endpoint and complain loudly; never fake cleanup completion. |
| 619 |
""" |
| 620 |
if self._closing: |
| 621 |
self._pending_close = max(0, self._pending_close - 1) |
| 622 |
if self._pending_close == 0: |
| 623 |
self._transports.clear() |
| 624 |
self._protocols.clear() |
| 625 |
if self._cleanup_timeout_handle is not None: |
| 626 |
self._cleanup_timeout_handle.cancel() |
| 627 |
self._cleanup_timeout_handle = None |
| 628 |
self._cleanup_done.set() |
| 629 |
return |
| 630 |
|
| 631 |
if protocol is None or protocol not in self._protocols: |
| 632 |
return |
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
index = self._protocols.index(protocol) |
| 637 |
self._protocols.pop(index) |
| 638 |
transport = self._transports.pop(index) |
| 639 |
if transport is not None and not transport.is_closing(): |
| 640 |
transport.close() |
| 641 |
address = self._listening_addresses.pop(index) |
| 642 |
self._networks.pop(index) |
| 643 |
if self._transports: |
| 644 |
self._logger.error( |
| 645 |
"UDP endpoint on %s closed unexpectedly; continuing on %s", |
| 646 |
address, |
| 647 |
self._listening_addresses, |
| 648 |
) |
| 649 |
else: |
| 650 |
self._logger.error( |
| 651 |
"UDP endpoint on %s closed unexpectedly and no endpoints " |
| 652 |
"remain; the controller is inoperative until restarted", |
| 653 |
address, |
| 654 |
) |
| 655 |
|
| 656 |
async def _handle_datagram_received( |
| 657 |
self, data: bytes, addr: tuple, protocol: GoveeControllerProtocol |
| 658 |
): |
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
try: |
| 664 |
if self._closing: |
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
return |
| 669 |
|
| 670 |
message = self._message_factory.create_message(data) |
| 671 |
if not message: |
| 672 |
self._logger.warning( |
| 673 |
"Unknown message received from %s: %r", addr, data[:128] |
| 674 |
) |
| 675 |
return |
| 676 |
|
| 677 |
handler = self._response_handler.get(message.command) |
| 678 |
if handler is None: |
| 679 |
|
| 680 |
g. |
| 681 |
self._logger.debug( |
| 682 |
"No handler for message %r from %s; ignoring", |
| 683 |
message.command, |
| 684 |
addr, |
| 685 |
) |
| 686 |
return |
| 687 |
await handler(message, addr, protocol) |
| 688 |
except Exception: |
| 689 |
self._logger.exception( |
| 690 |
"Datagram handler crashed (addr=%s, interface=%s, data=%r)", |
| 691 |
addr, |
| 692 |
protocol.listening_address, |
| 693 |
data[:64], |
| 694 |
) |
| 695 |
|
| 696 |
async def _handle_status_update_response( |
| 697 |
self, message: DevStatusResponse, addr, protocol: GoveeControllerProtocol |
| 698 |
): |
| 699 |
self._logger.debug("Status update received from %s: %s", addr, message) |
| 700 |
ip = addr[0] |
| 701 |
if device := self.get_device_by_ip(ip): |
| 702 |
if protocol.transport: |
| 703 |
device.update_transport(protocol.transport) |
| 704 |
device.update(message) |
| 705 |
|
| 706 |
async def _handle_scan_response( |
| 707 |
self, message: ScanResponse, addr: tuple, protocol: GoveeControllerProtocol |
| 708 |
) -> None: |
| 709 |
if not message.ip: |
| 710 |
sender_ip = addr[0] |
| 711 |
self._logger.debug( |
| 712 |
"No ip returned in data from device %s! Using sending " |
| 713 |
"address %s.\nData: %s", |
| 714 |
message.device, |
| 715 |
sender_ip, |
| 716 |
message.data, |
| 717 |
) |
| 718 |
message.set_ip(sender_ip) |
| 719 |
|
| 720 |
fingerprint = message.device |
| 721 |
if not fingerprint: |
| 722 |
self._logger.warning( |
| 723 |
"Scan response missing device fingerprint: %s", message |
| 724 |
) |
| 725 |
return |
| 726 |
|
| 727 |
if device := self.get_device_by_fingerprint(fingerprint): |
| 728 |
|
| 729 |
ck |
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
device.update_lastseen() |
| 735 |
if self._call_discovered_callback(device, False): |
| 736 |
if message.ip and message.ip != device.ip: |
| 737 |
self._logger.debug( |
| 738 |
"Device %s IP changed from %s to %s", |
| 739 |
fingerprint, |
| 740 |
device.ip, |
| 741 |
message.ip, |
| 742 |
) |
| 743 |
device.update_ip(message.ip) |
| 744 |
if protocol.transport: |
| 745 |
device.update_transport(protocol.transport) |
| 746 |
self._logger.debug("Device updated: %s", device) |
| 747 |
else: |
| 748 |
sku = message.sku |
| 749 |
if not sku: |
| 750 |
self._logger.warning( |
| 751 |
"Scan response missing sku for device %s", fingerprint |
| 752 |
) |
| 753 |
capabilities = ON_OFF_CAPABILITIES |
| 754 |
else: |
| 755 |
capabilities = GOVEE_LIGHT_CAPABILITIES.get(sku) or ON_OFF_CAPABILITIES |
| 756 |
if sku not in GOVEE_LIGHT_CAPABILITIES: |
| 757 |
self._logger.warning( |
| 758 |
"Device %s is not supported. Only power control is available. Please open an issue at 'https://github.com/Galorhallen/govee-local-api/issues'", |
| 759 |
sku, |
| 760 |
) |
| 761 |
|
| 762 |
ip = message.ip |
| 763 |
if not ip: |
| 764 |
self._logger.warning( |
| 765 |
"Scan response missing ip for device %s", fingerprint |
| 766 |
) |
| 767 |
return |
| 768 |
|
| 769 |
device = GoveeDevice(self, ip, fingerprint, sku or "UNKNOWN", capabilities) |
| 770 |
if protocol.transport: |
| 771 |
device.update_transport(protocol.transport) |
| 772 |
if self._call_discovered_callback(device, True): |
| 773 |
device = self._registry.add_discovered_device(device) |
| 774 |
self._logger.debug("Device discovered: %s", device) |
| 775 |
else: |
| 776 |
self._logger.debug("Device %s ignored", device) |
| 777 |
|
| 778 |
if self._evict_enabled: |
| 779 |
self._evict() |
| 780 |
|
| 781 |
def _call_discovered_callback(self, device: GoveeDevice, is_new: bool) -> bool: |
| 782 |
if not self._device_discovered_callback: |
| 783 |
return True |
| 784 |
return self._device_discovered_callback(device, is_new) |
| 785 |
|
| 786 |
def _send_message(self, message: GoveeMessage, device: GoveeDevice) -> None: |
| 787 |
if self._transports: |
| 788 |
|
| 789 |
transport = device.transport |
| 790 |
if transport is None or transport.is_closing(): |
| 791 |
transport = self._get_best_transport_for_ip(device.ip) |
| 792 |
if transport is not None: |
| 793 |
transport.sendto(bytes(message), (device.ip, self._device_command_port)) |
| 794 |
|
| 795 |
def _get_best_transport_for_ip(self, target_ip: str) -> Any: |
| 796 |
""" |
| 797 |
Select the best transport for communicating with a specific IP address. |
| 798 |
Uses parsed network information for accurate subnet matching when available, |
| 799 |
falling back to heuristic matching for addresses without a mask. |
| 800 |
""" |
| 801 |
if not self._transports: |
| 802 |
raise RuntimeError("No transports available") |
| 803 |
|
| 804 |
if len(self._transports) == 1: |
| 805 |
return self._transports[0] |
| 806 |
|
| 807 |
try: |
| 808 |
target_addr = ipaddress.ip_address(target_ip) |
| 809 |
|
| 810 |
for i, (listening_addr, network) in enumerate( |
| 811 |
zip(self._listening_addresses, self._networks) |
| 812 |
): |
| 813 |
if listening_addr == "0.0.0.0": |
| 814 |
continue |
| 815 |
|
| 816 |
|
| 817 |
if network is not None: |
| 818 |
if target_addr in network: |
| 819 |
self._logger.debug( |
| 820 |
"Selected transport %d (%s/%s) for target %s (subnet match)", |
| 821 |
i, |
| 822 |
listening_addr, |
| 823 |
network.prefixlen, |
| 824 |
target_ip, |
| 825 |
) |
| 826 |
return self._transports[i] |
| 827 |
else: |
| 828 |
|
| 829 |
try: |
| 830 |
listen_addr = ipaddress.ip_address(listening_addr) |
| 831 |
if ( |
| 832 |
target_addr.version == listen_addr.version == 4 |
| 833 |
and isinstance(target_addr, ipaddress.IPv4Address) |
| 834 |
and isinstance(listen_addr, ipaddress.IPv4Address) |
| 835 |
and _is_ip_in_same_network_heuristic( |
| 836 |
target_addr, listen_addr |
| 837 |
) |
| 838 |
): |
| 839 |
self._logger.debug( |
| 840 |
"Selected transport %d (%s) for target %s (heuristic match)", |
| 841 |
i, |
| 842 |
listening_addr, |
| 843 |
target_ip, |
| 844 |
) |
| 845 |
return self._transports[i] |
| 846 |
except ValueError: |
| 847 |
continue |
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
|
| 853 |
for i, listening_addr in enumerate(self._listening_addresses): |
| 854 |
if listening_addr != "0.0.0.0": |
| 855 |
self._logger.warning( |
| 856 |
"No interface matches target %s; falling back to " |
| 857 |
"transport %d (%s). Device may not reply if its " |
| 858 |
"subnet is not reachable from this interface.", |
| 859 |
target_ip, |
| 860 |
i, |
| 861 |
listening_addr, |
| 862 |
) |
| 863 |
self._logger.debug( |
| 864 |
"Selected transport %d (%s) for target %s (first specific address)", |
| 865 |
i, |
| 866 |
listening_addr, |
| 867 |
target_ip, |
| 868 |
) |
| 869 |
return self._transports[i] |
| 870 |
|
| 871 |
except ValueError: |
| 872 |
|
| 873 |
pass |
| 874 |
|
| 875 |
|
| 876 |
self._logger.debug( |
| 877 |
"Selected transport 0 (%s) for target %s (fallback)", |
| 878 |
self._listening_addresses[0], |
| 879 |
target_ip, |
| 880 |
) |
| 881 |
return self._transports[0] |
| 882 |
|
| 883 |
def _send_update_message(self, device: GoveeDevice): |
| 884 |
self._send_message(DevStatusMessage(), device) |
| 885 |
|
| 886 |
def _schedule_evict(self) -> None: |
| 887 |
if self._evict_handle is not None: |
| 888 |
self._evict_handle.cancel() |
| 889 |
self._evict_handle = self._loop.call_later( |
| 890 |
self._evict_interval, self._evict_tick |
| 891 |
) |
| 892 |
|
| 893 |
def _evict_tick(self) -> None: |
| 894 |
|
| 895 |
|
| 896 |
t. |
| 897 |
self._evict_handle = None |
| 898 |
if not self._evict_enabled: |
| 899 |
return |
| 900 |
self._evict() |
| 901 |
self._schedule_evict() |
| 902 |
|
| 903 |
def _evict(self) -> None: |
| 904 |
|
| 905 |
|
| 906 |
now = datetime.now(timezone.utc) |
| 907 |
devices = dict(self._registry.discovered_devices) |
| 908 |
for fingerprint, device in devices.items(): |
| 909 |
diff: timedelta = now - device.lastseen |
| 910 |
if diff.total_seconds() >= self._evict_interval: |
| 911 |
self._registry.remove_discovered_device(fingerprint) |
| 912 |
if device.is_manual: |
| 913 |
|
| 914 |
ld |
| 915 |
|
| 916 |
|
| 917 |
self._registry.add_device_to_queue(device.ip) |
| 918 |
self._logger.debug("Device evicted: %s", device) |
| 919 |
if self._device_evicted_callback and callable( |
| 920 |
self._device_evicted_callback |
| 921 |
): |
| 922 |
self._device_evicted_callback(device) |