Debian Codegraph @

src/govee_local_api/controller.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import errno
5 import functools
6 import ipaddress
7 import logging
8 import socket
9 import warnings
10 from collections.abc import Callable
11 from datetime import datetime, timedelta, timezone
12 from typing import Any
13
14 from .device import GoveeDevice
15 from .device_registry import DeviceRegistry
16 from .light_capabilities import (
17 GOVEE_LIGHT_CAPABILITIES,
18 ON_OFF_CAPABILITIES,
19 GoveeLightFeatures,
20 )
21 from .message import (
22 HexMessage,
23 BrightnessMessage,
24 ColorMessage,
25 SceneMessages,
26 GoveeMessage,
27 MessageResponseFactory,
28 OnOffMessage,
29 ScanMessage,
30 ScanResponse,
31 SegmentColorMessages,
32 DevStatusMessage,
33 DevStatusResponse,
34 )
35 from .network import (
36 _parse_listening_addresses,
37 _is_ip_in_same_network_heuristic,
38 )
39 from .protocol import GoveeControllerProtocol
40
41 BROADCAST_ADDRESS = "239.255.255.250"
42 BROADCAST_PORT = 4001
43 LISTENING_PORT = 4002
44 COMMAND_PORT = 4003
45
46 DISCOVERY_INTERVAL = 10
47 EVICT_INTERVAL = DISCOVERY_INTERVAL * 3
48 UPDATE_INTERVAL = 5
49
50
51 class GoveeController:
52 def __init__(
53 self,
54 loop=None,
55 broadcast_address: str = BROADCAST_ADDRESS,
56 broadcast_port: int = BROADCAST_PORT,
57 listening_addresses: str | list[str] | None = None,
58 listening_port: int = LISTENING_PORT,
59 device_command_port: int = COMMAND_PORT,
60 discovery_enabled: bool = False,
61 discovery_interval: int = DISCOVERY_INTERVAL,
62 evict_enabled: bool = False,
63 evict_interval: int = EVICT_INTERVAL,
64 update_enabled: bool = True,
65 update_interval: int = UPDATE_INTERVAL,
66 discovered_callback: Callable[[GoveeDevice, bool], bool] | None = None,
67 evicted_callback: Callable[[GoveeDevice], None] | None = None,
68 logger: logging.Logger | None = None,
69 listening_address: str | list[str] | None = None,
70 ) -> None:
71 """Build a controller that handle Govee devices that support local API on local network.
72
73 Args:
74 loop: The asyncio event loop. If None the loop is retrieved by calling ``asyncio.get_running_loop()``
75 broadcast_address (str): The multicast address to use to send discovery messages. Default: 239.255.255.250
76 broadcast_port (int): Devices port where discovery messages are sent. Default: 4001
77 listening_addresses (str | list[str]): Local IP addresses on which the controller listens for incoming
78 devices' messages. Can be a single address or a list of addresses. Supports optional CIDR or netmask
79 notation (e.g., "192.168.1.100/24" or "192.168.1.100/255.255.255.0"). When a mask is provided,
80 precise subnet matching is used for transport selection; an invalid mask raises ValueError.
81 Default: "0.0.0.0"
82 listening_port (int): Local UDP port on which the controller listen for incoming devices' messages
83 device_command_port (int): The devices' port where the commands should be sent
84 discovery_enabled (bool): If true a discovery message is sent every ``discovery_interval`` seconds. Default: False
85 discovery_interval (int): Interval between discovery messages (if discovery is enabled). Default: 10 seconds
86 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.
87 evict_interval (int): Interval after which a device is evicted. Default 30 seconds
88 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
89 update_interval (int): Interval between a status update is requested to devices.
90 discovered_callback (Callable[GoveeDevice, bool]): An optional function to call when a device is discovered (or rediscovered). Default None
91 evicted_callback (Callable[GoveeDevice]): An optional function to call when a device is evicted.
92 listening_address (str | list[str]): Deprecated alias of ``listening_addresses`` kept for
93 backward compatibility (pre-3.0 name); emits a DeprecationWarning.
94 """
95 if listening_address is not None:
96 warnings.warn(
97 "The 'listening_address' argument is deprecated and will be "
98 "removed in a future release; use 'listening_addresses' instead.",
99 DeprecationWarning,
100 stacklevel=2,
101 )
102 if listening_addresses is not None:
103 raise ValueError(
104 "Pass either 'listening_addresses' or the deprecated "
105 "'listening_address', not both"
106 )
107 listening_addresses = listening_address
108 if listening_addresses is None:
109 listening_addresses = "0.0.0.0"
110
111 self._logger = logger or logging.getLogger(__name__)
112
113 self._transports: list[Any] = []
114 self._protocols: list[Any] = []
115 self._bind_failures: list[tuple[str, OSError]] = []
116 self._broadcast_address = broadcast_address
117 self._broadcast_port = broadcast_port
118 self._listening_port = listening_port
119 self._device_command_port = device_command_port
120 self._listening_addresses, self._networks = _parse_listening_addresses(
121 listening_addresses
122 )
123
124 # Reject obviously bad input up front so it doesn't surface as a
125 # cryptic OSError from socket.bind() later.
126 for addr in self._listening_addresses:
127 try:
128 ipaddress.IPv4Address(addr)
129 except (ipaddress.AddressValueError, ValueError) as exc:
130 raise ValueError(f"Invalid IPv4 listening address: {addr!r}") from exc
131
132 # Drop duplicate entries while preserving order; two sockets bound to
133 # the same (ip, port) get load-balanced by SO_REUSEPORT and flip the
134 # device's preferred transport on every status frame.
135 seen: set[str] = set()
136 deduped: list[tuple[str, ipaddress.IPv4Network | None]] = []
137 for addr, net in zip(self._listening_addresses, self._networks):
138 if addr in seen:
139 self._logger.warning(
140 "Duplicate listening address %s; ignoring extra entry",
141 addr,
142 )
143 continue
144 seen.add(addr)
145 deduped.append((addr, net))
146 self._listening_addresses = [a for a, _ in deduped]
147 self._networks = [n for _, n in deduped]
148
149 # If specific addresses are provided alongside 0.0.0.0, drop the wildcard
150 # to avoid duplicate packet processing (0.0.0.0 receives on all interfaces)
151 if (
152 len(self._listening_addresses) > 1
153 and "0.0.0.0" in self._listening_addresses
154 ):
155 self._logger.warning(
156 "Wildcard address 0.0.0.0 mixed with specific addresses %s; "
157 "dropping 0.0.0.0 to avoid duplicate packet processing",
158 [a for a in self._listening_addresses if a != "0.0.0.0"],
159 )
160 filtered = [
161 (addr, net)
162 for addr, net in zip(self._listening_addresses, self._networks)
163 if addr != "0.0.0.0"
164 ]
165 self._listening_addresses = [a for a, _ in filtered]
166 self._networks = [n for _, n in filtered]
167
168 # Empty configuration (e.g. user passed []) would silently produce a
169 # working-looking controller that never binds anything. Fail loudly.
170 if not self._listening_addresses:
171 raise ValueError("listening_addresses resulted in an empty configuration")
172
173 # Snapshot the effective configuration so start() can always bind the
174 # full set, even after an unexpected connection_lost dropped an
175 # endpoint from the working lists.
176 self._configured_addresses: list[str] = list(self._listening_addresses)
177 self._configured_networks: list[ipaddress.IPv4Network | None] = list(
178 self._networks
179 )
180
181 # Initialize loop, handling case when no loop is running (for testing)
182 try:
183 self._loop = loop or asyncio.get_running_loop()
184 except RuntimeError:
185 # No running loop, use a new event loop (mainly for testing)
186 self._loop = loop or asyncio.new_event_loop()
187
188 self._cleanup_done: asyncio.Event = asyncio.Event()
189 self._message_factory = MessageResponseFactory()
190 self._registry: DeviceRegistry = DeviceRegistry(self._logger)
191
192 self._discovery_enabled = discovery_enabled
193 self._discovery_interval = discovery_interval
194 self._update_enabled = update_enabled
195 self._update_interval = update_interval
196 self._evict_enabled = evict_enabled
197 self._evict_interval = evict_interval
198
199 self._device_discovered_callback = discovered_callback
200 self._device_evicted_callback = evicted_callback
201
202 self._discovery_handle: asyncio.TimerHandle | None = None
203 self._update_handle: asyncio.TimerHandle | None = None
204 self._evict_handle: asyncio.TimerHandle | None = None
205 self._cleanup_timeout_handle: asyncio.TimerHandle | None = None
206
207 # Shutdown bookkeeping: connection_lost fires both during cleanup()
208 # and (in theory) on an internal transport failure. _closing marks a
209 # requested shutdown; _pending_close counts the connection_lost
210 # callbacks still owed before cleanup is actually complete.
211 self._closing: bool = False
212 self._pending_close: int = 0
213
214 # Dispatch table for incoming messages: maps the message's "cmd"
215 # string to its handler. All handlers share the signature
216 # (message, addr, protocol).
217 self._response_handler: dict[str, Callable] = {
218 ScanResponse.command: self._handle_scan_response,
219 DevStatusResponse.command: self._handle_status_update_response,
220 }
221
222 async def start(self, *, require_all: bool = True) -> None:
223 """Bind the listening endpoints and kick off discovery/updates.
224
225 Args:
226 require_all: When True (default) every configured address must
227 bind; a single failure closes any endpoint already opened by
228 this call and re-raises, leaving the controller unbound. When
229 False the controller keeps whatever binds successfully and
230 raises only if *nothing* binds; the addresses that failed are
231 reported through :attr:`bind_failures`.
232
233 Raises:
234 OSError: A bind failed (``require_all=True``) or every bind failed
235 (``require_all=False``). The ``errno`` of the original error
236 is preserved so callers can special-case e.g. ``EADDRINUSE``.
237 """
238 self._closing = False
239 self._bind_failures = []
240 # Rebind the full configuration: an unexpected connection_lost (or a
241 # previous partial start) may have dropped an endpoint from the
242 # working lists.
243 self._listening_addresses = list(self._configured_addresses)
244 self._networks = list(self._configured_networks)
245
246 # Create datagram endpoints for each listening address. We build the
247 # socket by hand so SO_REUSEADDR / SO_REUSEPORT / SO_BROADCAST are set
248 # before bind() — the kernel only honors them at bind time.
249 #
250 # Successful endpoints are accumulated locally and assigned to the
251 # four parallel instance lists in one go after the loop, so they can
252 # never be observed misaligned (transport selection in
253 # _get_best_transport_for_ip relies on index alignment).
254 bound: list[tuple[str, ipaddress.IPv4Network | None, Any, Any]] = []
255 try:
256 for listening_address, network in zip(
257 self._listening_addresses, self._networks
258 ):
259 try:
260 sock = self._create_listening_socket(listening_address)
261 try:
262 transport, protocol = await self._loop.create_datagram_endpoint(
263 functools.partial(
264 GoveeControllerProtocol, self, listening_address
265 ),
266 sock=sock,
267 )
268 except Exception:
269 sock.close()
270 raise
271 except OSError as ex:
272 if require_all:
273 raise
274 self._bind_failures.append((listening_address, ex))
275 self._logger.warning(
276 "Failed to bind UDP endpoint on %s:%d (errno %s: %s); "
277 "continuing with the remaining addresses",
278 listening_address,
279 self._listening_port,
280 ex.errno,
281 ex.strerror or ex,
282 )
283 continue
284 bound.append((listening_address, network, transport, protocol))
285 except Exception:
286 # Don't leave earlier endpoints bound: a partially started
287 # controller would leak a socket on every setup retry. Clearing
288 # the instance lists before closing keeps the ensuing
289 # connection_lost callbacks from taking the "unexpected loss"
290 # path; the endpoints opened by this call were never in them.
291 self._close_all_transports([transport for _, _, transport, _ in bound])
292 raise
293
294 if not bound:
295 # require_all=False and every bind failed. Re-raise a real OSError
296 # (never a wrapper type) so consumers branching on errno keep
297 # working. EADDRINUSE is the errno most often treated as
298 # transient/retryable, so don't let an unrelated error on another
299 # adapter mask it.
300 self._close_all_transports([])
301 errors = [ex for _, ex in self._bind_failures]
302 raise next((ex for ex in errors if ex.errno == errno.EADDRINUSE), errors[0])
303
304 self._listening_addresses = [addr for addr, _, _, _ in bound]
305 self._networks = [net for _, net, _, _ in bound]
306 self._transports = [transport for _, _, transport, _ in bound]
307 self._protocols = [protocol for _, _, _, protocol in bound]
308
309 if self._bind_failures:
310 self._logger.warning(
311 "Started with %d of %d listening addresses; live on %s, failed on %s",
312 len(bound),
313 len(self._configured_addresses),
314 self._listening_addresses,
315 [addr for addr, _ in self._bind_failures],
316 )
317
318 if self._discovery_enabled or self._registry.has_queued_devices:
319 self.send_discovery_message()
320 if self._update_enabled:
321 self.send_update_message()
322 if self._evict_enabled:
323 self._schedule_evict()
324
325 def _close_all_transports(self, extra: list[Any]) -> None:
326 """Close ``extra`` plus every transport currently held, and clear the
327 transport/protocol lists first so connection_lost sees a shutdown."""
328 transports = self._transports[:] + extra
329 self._transports.clear()
330 self._protocols.clear()
331 for transport in transports:
332 if transport is not None and not transport.is_closing():
333 transport.close()
334
335 def _create_listening_socket(self, listening_address: str) -> socket.socket:
336 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
337 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
338 # SO_REUSEPORT is the right primitive for "multiple sockets share this
339 # port" on Linux >=3.9 and macOS, but is missing on Windows and some
340 # older systems — fall through if the kernel rejects it.
341 reuse_port = getattr(socket, "SO_REUSEPORT", None)
342 if reuse_port is not None:
343 try:
344 sock.setsockopt(socket.SOL_SOCKET, reuse_port, 1)
345 except OSError:
346 pass
347 sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
348 try:
349 sock.bind((listening_address, self._listening_port))
350 except OSError:
351 sock.close()
352 raise
353 return sock
354
355 def cleanup(self, timeout: float = 2.0) -> asyncio.Event:
356 # Idempotent: if a previous cleanup() already finished, hand the
357 # already-set event back without clearing it. Second callers
358 # would otherwise wait forever because the transports are gone
359 # and nothing will fire connection_lost again.
360 if not self._transports and self._cleanup_done.is_set():
361 return self._cleanup_done
362
363 self._cleanup_done.clear()
364 already_closing = self._closing
365 self._closing = True
366 self.set_update_enabled(False)
367 # Don't go through set_discovery_enabled(False) here: it keeps the
368 # timer chain alive while queued/manual devices still need probing,
369 # which is exactly what shutdown must stop. Cancel it directly.
370 self._discovery_enabled = False
371 if self._discovery_handle is not None:
372 self._discovery_handle.cancel()
373 self._discovery_handle = None
374 # Stop the eviction loop before tearing down transports so an
375 # in-flight _handle_scan_response task can't invoke the user's
376 # evicted_callback mid-shutdown.
377 self.set_evict_enabled(False)
378
379 if not self._transports:
380 self._cleanup_done.set()
381 self._registry.cleanup()
382 return self._cleanup_done
383
384 # Completion is signalled after this many connection_lost callbacks.
385 # A second cleanup() while the first drain is in flight must NOT
386 # reset the countdown — some callbacks have already been counted.
387 if not already_closing:
388 self._pending_close = len(self._transports)
389 for transport in self._transports:
390 if transport is not None and not transport.is_closing():
391 transport.close()
392
393 # Safety net: a transport whose fd was revoked (NIC unplugged,
394 # container network teardown) may never deliver connection_lost.
395 # Without this timer, HA's async_unload_entry hangs forever.
396 if self._cleanup_timeout_handle is not None:
397 self._cleanup_timeout_handle.cancel()
398 self._cleanup_timeout_handle = self._loop.call_later(
399 timeout, self._force_cleanup_done
400 )
401
402 self._registry.cleanup()
403 return self._cleanup_done
404
405 def _force_cleanup_done(self) -> None:
406 self._cleanup_timeout_handle = None
407 if self._cleanup_done.is_set():
408 return
409 stragglers = [
410 self._listening_addresses[i]
411 for i, t in enumerate(self._transports)
412 if t is not None
413 and not t.is_closing()
414 and i < len(self._listening_addresses)
415 ]
416 if stragglers:
417 self._logger.warning(
418 "cleanup() timed out waiting for connection_lost; "
419 "forcing completion. Stragglers: %s",
420 stragglers,
421 )
422 self._transports.clear()
423 self._protocols.clear()
424 self._cleanup_done.set()
425
426 @property
427 def protocols(self) -> list:
428 """Return the list of active protocols."""
429 return self._protocols
430
431 def add_device_to_discovery_queue(self, ip: str) -> bool:
432 ip_added: bool = self._registry.add_device_to_queue(ip)
433 if not self._discovery_enabled and ip_added:
434 self.send_discovery_message()
435 return ip_added
436
437 def reconnect(self) -> None:
438 """Trigger a fresh discovery and update all known devices."""
439 self._logger.info("Triggering aggressive reconnection/discovery...")
440 self.send_discovery_message()
441 self.send_update_message()
442
443 def remove_device_from_discovery_queue(self, ip: str) -> bool:
444 return self._registry.remove_device_from_queue(ip)
445
446 @property
447 def discovery_queue(self) -> set[str]:
448 return self._registry.devices_queue
449
450 def remove_device(self, device: str | GoveeDevice) -> None:
451 if isinstance(device, GoveeDevice):
452 device = device.fingerprint
453 self._registry.remove_discovered_device(device)
454
455 @property
456 def evict_enabled(self) -> bool:
457 return self._evict_enabled
458
459 @property
460 def evict_interval(self) -> int:
461 return self._evict_interval
462
463 def set_evict_enabled(self, enabled: bool) -> None:
464 if self._evict_enabled == enabled:
465 return
466 self._evict_enabled = enabled
467 if enabled:
468 self._schedule_evict()
469 elif self._evict_handle is not None:
470 self._evict_handle.cancel()
471 self._evict_handle = None
472
473 def set_discovery_enabled(self, enabled: bool) -> None:
474 if self._discovery_enabled == enabled:
475 return
476 self._discovery_enabled = enabled
477 if enabled:
478 self.send_discovery_message()
479 elif self._discovery_handle:
480 self._discovery_handle.cancel()
481 self._discovery_handle = None
482 # The same timer chain also probes queued and manually-added
483 # devices; keep it running when they still need it.
484 has_manual_devices = any(
485 device.is_manual
486 for device in self._registry.discovered_devices.values()
487 )
488 if self._registry.has_queued_devices or has_manual_devices:
489 self.send_discovery_message()
490
491 @property
492 def discovery(self) -> bool:
493 return self._discovery_enabled
494
495 def set_discovery_interval(self, interval: int) -> None:
496 self._discovery_interval = interval
497
498 @property
499 def discovery_interval(self) -> int:
500 return self._discovery_interval
501
502 @property
503 def listening_addresses(self) -> list[str]:
504 """Get the list of listening addresses."""
505 return self._listening_addresses.copy()
506
507 @property
508 def networks(self) -> list[ipaddress.IPv4Network | None]:
509 """Get the list of parsed networks for each listening address."""
510 return self._networks.copy()
511
512 @property
513 def bind_failures(self) -> list[tuple[str, OSError]]:
514 """Addresses that failed to bind during the last start(), with the error.
515
516 Only populated when ``start(require_all=False)`` tolerated failures;
517 reset on every ``start()`` call. Returns a copy.
518 """
519 return self._bind_failures.copy()
520
521 def set_device_discovered_callback(
522 self, callback: Callable[[GoveeDevice, bool], bool] | None
523 ) -> Callable[[GoveeDevice, bool], bool] | None:
524 old_callback = self._device_discovered_callback
525 self._device_discovered_callback = callback
526 return old_callback
527
528 def set_update_enabled(self, enabled: bool) -> None:
529 if self._update_enabled == enabled:
530 return
531 self._update_enabled = enabled
532 if enabled:
533 self.send_update_message()
534 elif self._update_handle:
535 self._update_handle.cancel()
536 self._update_handle = None
537
538 @property
539 def update_enabled(self) -> bool:
540 return self._update_enabled
541
542 def send_discovery_message(self) -> None:
543 message: bytes = bytes(ScanMessage())
544 call_later: bool = False
545 if not self._transports:
546 return
547
548 if self._discovery_enabled:
549 call_later = True
550 # Send broadcast messages from each listening address/transport
551 for i, transport in enumerate(self._transports):
552 self._logger.debug(
553 "Sending discovery broadcast from interface %s (%s) to %s:%s",
554 i,
555 self._listening_addresses[i],
556 self._broadcast_address,
557 self._broadcast_port,
558 )
559 transport.sendto(
560 message, (self._broadcast_address, self._broadcast_port)
561 )
562
563 if self._registry.has_queued_devices:
564 call_later = True
565 # Send to specific devices using the most appropriate transport for each IP
566 for ip in list(self._registry.devices_queue):
567 transport = self._get_best_transport_for_ip(ip)
568 transport.sendto(message, (ip, self._broadcast_port))
569
570 manually_added_devices = [
571 device.ip
572 for device in self._registry.discovered_devices.values()
573 if device.is_manual
574 ]
575 if manually_added_devices:
576 call_later = True
577 # Send to manually added devices using the most appropriate transport for each IP
578 for ip in manually_added_devices:
579 transport = self._get_best_transport_for_ip(ip)
580 transport.sendto(message, (ip, self._broadcast_port))
581
582 if call_later:
583 # Cancel any prior pending tick — external triggers like
584 # add_device_to_discovery_queue() can call this method between
585 # scheduled ticks, and without cancelling we'd accumulate
586 # parallel timer chains and storm the network.
587 if self._discovery_handle is not None:
588 self._discovery_handle.cancel()
589 self._discovery_handle = self._loop.call_later(
590 self._discovery_interval, self.send_discovery_message
591 )
592
593 def send_update_message(self) -> None:
594 if self._transports:
595 for d in self._registry.discovered_devices.values():
596 self._send_update_message(device=d)
597
598 if self._update_enabled:
599 if self._update_handle is not None:
600 self._update_handle.cancel()
601 self._update_handle = self._loop.call_later(
602 self._update_interval, self.send_update_message
603 )
604
605 async def turn_on_off(self, device: GoveeDevice, status: bool) -> None:
606 self._send_message(OnOffMessage(status), device)
607
608 async def set_segment_rgb_color(
609 self, device: GoveeDevice, segment: int, rgb: tuple[int, int, int]
610 ) -> None:
611 if not device.capabilities:
612 self._logger.warning("Capabilities not available for device %s", device)
613 return
614
615 if device.capabilities.features & GoveeLightFeatures.SEGMENT_CONTROL == 0:
616 self._logger.warning(
617 "Segment control is not supported by device %s", device
618 )
619 return
620
621 if segment < 1 or segment > len(device.capabilities.segments):
622 self._logger.warning(
623 "Segment index %s is not valid for device %s", segment, device
624 )
625 return
626
627 segment_data: bytes = device.capabilities.segments[segment - 1]
628 if not segment_data:
629 self._logger.warning(
630 "Segment %s is not supported by device %s", segment, device
631 )
632 return
633 message = SegmentColorMessages(segment_data, rgb)
634 self._logger.debug(f"Sending message {message} to device {device}")
635 self._send_message(message, device)
636
637 async def set_scene(self, device: GoveeDevice, scene: str) -> None:
638 if (
639 not device.capabilities
640 or device.capabilities.features & GoveeLightFeatures.SCENES == 0
641 ):
642 self._logger.warning("Scenes are not supported by device %s", device)
643 return
644
645 scene_code: bytes | None = device.capabilities.scenes.get(scene.lower(), None)
646 if not scene_code:
647 self._logger.warning(
648 "Scene %s is not available for device %s", scene, device
649 )
650 return
651 self._send_message(SceneMessages(scene_code), device)
652
653 async def set_brightness(self, device: GoveeDevice, brightness: int) -> None:
654 self._send_message(BrightnessMessage(brightness), device)
655
656 async def set_color(
657 self,
658 device: GoveeDevice,
659 *,
660 rgb: tuple[int, int, int] | None,
661 temperature: int | None,
662 ) -> None:
663 if rgb:
664 self._send_message(ColorMessage(rgb=rgb, temperature=None), device)
665 else:
666 self._send_message(ColorMessage(rgb=None, temperature=temperature), device)
667
668 async def send_raw_command(self, device: GoveeDevice, command: str) -> None:
669 self._send_message(HexMessage([command]), device)
670
671 def get_device_by_ip(self, ip: str) -> GoveeDevice | None:
672 return self._registry.get_device_by_ip(ip)
673
674 def get_device_by_sku(self, sku: str) -> GoveeDevice | None:
675 return self._registry.get_device_by_sku(sku)
676
677 def get_device_by_fingerprint(self, fingerprint: str) -> GoveeDevice | None:
678 return self._registry.get_device_by_fingerprint(fingerprint)
679
680 @property
681 def devices(self) -> list[GoveeDevice]:
682 return list(self._registry.discovered_devices.values())
683
684 def _protocol_disconnected(
685 self, protocol: GoveeControllerProtocol | None = None
686 ) -> None:
687 """Called from connection_lost of each protocol.
688
689 During cleanup() this counts down the protocols still owed a
690 connection_lost and signals completion only once ALL of them have
691 delivered it — a transport reports is_closing() immediately after
692 close(), so checking that (the old behavior) fired cleanup_done on
693 the first callback while other sockets were still tearing down.
694
695 Outside cleanup() a connection_lost means an internal transport
696 failure (no realistic UDP trigger on Linux — OSErrors go to
697 error_received — but abort()/fatal errors reach here). Drop the dead
698 endpoint and complain loudly; never fake cleanup completion.
699 """
700 if self._closing:
701 self._pending_close = max(0, self._pending_close - 1)
702 if self._pending_close == 0:
703 self._transports.clear()
704 self._protocols.clear()
705 if self._cleanup_timeout_handle is not None:
706 self._cleanup_timeout_handle.cancel()
707 self._cleanup_timeout_handle = None
708 self._cleanup_done.set()
709 return
710
711 if protocol is None or protocol not in self._protocols:
712 return
713
714 # Pop the dead endpoint from all four parallel lists so transport
715 # selection stays index-aligned.
716 index = self._protocols.index(protocol)
717 self._protocols.pop(index)
718 transport = self._transports.pop(index)
719 if transport is not None and not transport.is_closing():
720 transport.close()
721 address = self._listening_addresses.pop(index)
722 self._networks.pop(index)
723 if self._transports:
724 self._logger.error(
725 "UDP endpoint on %s closed unexpectedly; continuing on %s",
726 address,
727 self._listening_addresses,
728 )
729 else:
730 self._logger.error(
731 "UDP endpoint on %s closed unexpectedly and no endpoints "
732 "remain; the controller is inoperative until restarted",
733 address,
734 )
735
736 async def _handle_datagram_received(
737 self, data: bytes, addr: tuple, protocol: GoveeControllerProtocol
738 ):
739 # datagram_received() schedules this coroutine via create_task() and
740 # never observes the resulting task, so an uncaught exception here
741 # surfaces only as asyncio's generic "Task exception was never
742 # retrieved" with no context. Contain it.
743 try:
744 if self._closing:
745 # A task created just before cleanup() can run after the
746 # registry was cleared; processing it would repopulate the
747 # registry and fire the discovered callback mid-shutdown.
748 return
749
750 message = self._message_factory.create_message(data)
751 if not message:
752 self._logger.warning(
753 "Unknown message received from %s: %r", addr, data[:128]
754 )
755 return
756
757 handler = self._response_handler.get(message.command)
758 if handler is None:
759 # Parseable Govee message we deliberately don't act on
760 # (e.g. "status") — not noise, so no warning.
761 self._logger.debug(
762 "No handler for message %r from %s; ignoring",
763 message.command,
764 addr,
765 )
766 return
767 await handler(message, addr, protocol)
768 except Exception:
769 self._logger.exception(
770 "Datagram handler crashed (addr=%s, interface=%s, data=%r)",
771 addr,
772 protocol.listening_address,
773 data[:64],
774 )
775
776 async def _handle_status_update_response(
777 self, message: DevStatusResponse, addr, protocol: GoveeControllerProtocol
778 ):
779 self._logger.debug("Status update received from %s: %s", addr, message)
780 ip = addr[0]
781 if device := self.get_device_by_ip(ip):
782 if protocol.transport:
783 device.update_transport(protocol.transport)
784 device.update(message)
785
786 async def _handle_scan_response(
787 self, message: ScanResponse, addr: tuple, protocol: GoveeControllerProtocol
788 ) -> None:
789 if not message.ip:
790 sender_ip = addr[0]
791 self._logger.debug(
792 "No ip returned in data from device %s! Using sending "
793 "address %s.\nData: %s",
794 message.device,
795 sender_ip,
796 message.data,
797 )
798 message.set_ip(sender_ip)
799
800 fingerprint = message.device
801 if not fingerprint:
802 self._logger.warning(
803 "Scan response missing device fingerprint: %s", message
804 )
805 return
806
807 if device := self.get_device_by_fingerprint(fingerprint):
808 # The scan response itself is evidence the device is alive, so
809 # refresh lastseen unconditionally — otherwise the eviction tick
810 # removes a device that just answered us. The callback's
811 # return value gates re-notification of the integration and
812 # the IP/transport updates that are tied to that, not the
813 # liveness bookkeeping.
814 device.update_lastseen()
815 if self._call_discovered_callback(device, False):
816 if message.ip and message.ip != device.ip:
817 self._logger.debug(
818 "Device %s IP changed from %s to %s",
819 fingerprint,
820 device.ip,
821 message.ip,
822 )
823 device.update_ip(message.ip)
824 if protocol.transport:
825 device.update_transport(protocol.transport)
826 self._logger.debug("Device updated: %s", device)
827 else:
828 sku = message.sku
829 if not sku:
830 self._logger.warning(
831 "Scan response missing sku for device %s", fingerprint
832 )
833 capabilities = ON_OFF_CAPABILITIES
834 else:
835 capabilities = GOVEE_LIGHT_CAPABILITIES.get(sku) or ON_OFF_CAPABILITIES
836 if sku not in GOVEE_LIGHT_CAPABILITIES:
837 self._logger.warning(
838 "Device %s is not supported. Only power control is available. Please open an issue at 'https://github.com/Galorhallen/govee-local-api/issues'",
839 sku,
840 )
841
842 ip = message.ip
843 if not ip:
844 self._logger.warning(
845 "Scan response missing ip for device %s", fingerprint
846 )
847 return
848
849 device = GoveeDevice(self, ip, fingerprint, sku or "UNKNOWN", capabilities)
850 if protocol.transport:
851 device.update_transport(protocol.transport)
852 if self._call_discovered_callback(device, True):
853 device = self._registry.add_discovered_device(device)
854 self._logger.debug("Device discovered: %s", device)
855 else:
856 self._logger.debug("Device %s ignored", device)
857
858 if self._evict_enabled:
859 self._evict()
860
861 def _call_discovered_callback(self, device: GoveeDevice, is_new: bool) -> bool:
862 if not self._device_discovered_callback:
863 return True
864 return self._device_discovered_callback(device, is_new)
865
866 def _send_message(self, message: GoveeMessage, device: GoveeDevice) -> None:
867 if self._transports:
868 # Prefer the transport the device was discovered on
869 transport = device.transport
870 if transport is None or transport.is_closing():
871 transport = self._get_best_transport_for_ip(device.ip)
872 if transport is not None:
873 transport.sendto(bytes(message), (device.ip, self._device_command_port))
874
875 def _get_best_transport_for_ip(self, target_ip: str) -> Any:
876 """
877 Select the best transport for communicating with a specific IP address.
878 Uses parsed network information for accurate subnet matching when available,
879 falling back to heuristic matching for addresses without a mask.
880 """
881 if not self._transports:
882 raise RuntimeError("No transports available")
883
884 if len(self._transports) == 1:
885 return self._transports[0]
886
887 try:
888 target_addr = ipaddress.ip_address(target_ip)
889
890 for i, (listening_addr, network) in enumerate(
891 zip(self._listening_addresses, self._networks)
892 ):
893 if listening_addr == "0.0.0.0":
894 continue
895
896 # Use precise subnet matching if a network mask was provided
897 if network is not None:
898 if target_addr in network:
899 self._logger.debug(
900 "Selected transport %d (%s/%s) for target %s (subnet match)",
901 i,
902 listening_addr,
903 network.prefixlen,
904 target_ip,
905 )
906 return self._transports[i]
907 else:
908 # Fallback to heuristic matching for addresses without a mask
909 try:
910 listen_addr = ipaddress.ip_address(listening_addr)
911 if (
912 target_addr.version == listen_addr.version == 4
913 and isinstance(target_addr, ipaddress.IPv4Address)
914 and isinstance(listen_addr, ipaddress.IPv4Address)
915 and _is_ip_in_same_network_heuristic(
916 target_addr, listen_addr
917 )
918 ):
919 self._logger.debug(
920 "Selected transport %d (%s) for target %s (heuristic match)",
921 i,
922 listening_addr,
923 target_ip,
924 )
925 return self._transports[i]
926 except ValueError:
927 continue
928
929 # If no network match found, prefer non-wildcard addresses. This
930 # is a best-effort fallback: the packet leaves with a source IP
931 # that may not belong to the target's subnet, so the device's
932 # reply may never come back. Warn so this is diagnosable.
933 for i, listening_addr in enumerate(self._listening_addresses):
934 if listening_addr != "0.0.0.0":
935 self._logger.warning(
936 "No interface matches target %s; falling back to "
937 "transport %d (%s). Device may not reply if its "
938 "subnet is not reachable from this interface.",
939 target_ip,
940 i,
941 listening_addr,
942 )
943 self._logger.debug(
944 "Selected transport %d (%s) for target %s (first specific address)",
945 i,
946 listening_addr,
947 target_ip,
948 )
949 return self._transports[i]
950
951 except ValueError:
952 # Invalid IP address, fall back to first transport
953 pass
954
955 # Fallback to first transport
956 self._logger.debug(
957 "Selected transport 0 (%s) for target %s (fallback)",
958 self._listening_addresses[0],
959 target_ip,
960 )
961 return self._transports[0]
962
963 def _send_update_message(self, device: GoveeDevice):
964 self._send_message(DevStatusMessage(), device)
965
966 def _schedule_evict(self) -> None:
967 if self._evict_handle is not None:
968 self._evict_handle.cancel()
969 self._evict_handle = self._loop.call_later(
970 self._evict_interval, self._evict_tick
971 )
972
973 def _evict_tick(self) -> None:
974 # Periodic eviction pass. _evict() also runs opportunistically from
975 # _handle_scan_response, but that path alone never fires when *no*
976 # device answers — exactly the situation where eviction matters most.
977 self._evict_handle = None
978 if not self._evict_enabled:
979 return
980 self._evict()
981 self._schedule_evict()
982
983 def _evict(self) -> None:
984 # lastseen is timezone-aware UTC; a naive now() would raise on
985 # subtraction.
986 now = datetime.now(timezone.utc)
987 devices = dict(self._registry.discovered_devices)
988 for fingerprint, device in devices.items():
989 diff: timedelta = now - device.lastseen
990 if diff.total_seconds() >= self._evict_interval:
991 self._registry.remove_discovered_device(fingerprint)
992 if device.is_manual:
993 # A manually-added device must keep being probed after
994 # eviction — with discovery disabled nothing else would
995 # ever contact its IP again, so it would stay gone until
996 # the user re-added it.
997 self._registry.add_device_to_queue(device.ip)
998 self._logger.debug("Device evicted: %s", device)
999 if self._device_evicted_callback and callable(
1000 self._device_evicted_callback
1001 ):
1002 self._device_evicted_callback(device)