| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import logging |
| 6 |
import time |
| 7 |
from typing import Callable |
| 8 |
|
| 9 |
from .aioutils import asyncio_timeout |
| 10 |
from .scanner import MESSAGE_SEND_INTERLEAVE_DELAY, BulbScanner, FluxLEDDiscovery |
| 11 |
|
| 12 |
_LOGGER = logging.getLogger(__name__) |
| 13 |
|
| 14 |
|
| 15 |
class LEDENETDiscovery(asyncio.DatagramProtocol): |
| 16 |
def __init__( |
| 17 |
self, |
| 18 |
destination: tuple[str, int], |
| 19 |
on_response: Callable[[bytes, tuple[str, int]], None], |
| 20 |
) -> None: |
| 21 |
"""Init the discovery protocol.""" |
| 22 |
self.transport = None |
| 23 |
self.destination = destination |
| 24 |
self.on_response = on_response |
| 25 |
|
| 26 |
def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: |
| 27 |
"""Trigger on_response.""" |
| 28 |
self.on_response(data, addr) |
| 29 |
|
| 30 |
def error_received(self, ex: Exception | None) -> None: |
| 31 |
"""Handle error.""" |
| 32 |
_LOGGER.debug("LEDENETDiscovery error: %s", ex) |
| 33 |
|
| 34 |
def connection_lost(self, ex: Exception | None) -> None: |
| 35 |
"""The connection is lost.""" |
| 36 |
|
| 37 |
|
| 38 |
class AIOBulbScanner(BulbScanner): |
| 39 |
"""A LEDENET discovery scanner.""" |
| 40 |
|
| 41 |
def __init__(self) -> None: |
| 42 |
self.loop = asyncio.get_running_loop() |
| 43 |
super().__init__() |
| 44 |
|
| 45 |
async def _async_send_messages( |
| 46 |
self, |
| 47 |
messages: list[bytes], |
| 48 |
sender: asyncio.DatagramTransport, |
| 49 |
destination: tuple[str, int], |
| 50 |
) -> None: |
| 51 |
"""Send messages with a short delay between them.""" |
| 52 |
last_idx = len(messages) - 1 |
| 53 |
for idx, message in enumerate(messages): |
| 54 |
self._send_message(sender, destination, message) |
| 55 |
if idx != last_idx: |
| 56 |
await asyncio.sleep(MESSAGE_SEND_INTERLEAVE_DELAY) |
| 57 |
|
| 58 |
async def _async_send_and_wait( |
| 59 |
self, |
| 60 |
events: list[asyncio.Event], |
| 61 |
commands: list[bytes], |
| 62 |
transport: asyncio.DatagramTransport, |
| 63 |
destination: tuple[str, int], |
| 64 |
timeout: int, |
| 65 |
) -> None: |
| 66 |
"""Send a message and wait for a response.""" |
| 67 |
event_map: dict[int, asyncio.Event] = {} |
| 68 |
for idx, _ in enumerate(commands): |
| 69 |
event = asyncio.Event() |
| 70 |
event_map[idx] = event |
| 71 |
events.append(event) |
| 72 |
for idx, command in enumerate(commands): |
| 73 |
self._send_message(transport, destination, command) |
| 74 |
async with asyncio_timeout(timeout): |
| 75 |
await event_map[idx].wait() |
| 76 |
|
| 77 |
async def _async_send_commands_and_reboot( |
| 78 |
self, |
| 79 |
messages: list[bytes] | None, |
| 80 |
address: str, |
| 81 |
timeout: int = 5, |
| 82 |
) -> None: |
| 83 |
"""Send a command and reboot.""" |
| 84 |
sock = self._create_socket() |
| 85 |
destination = self._destination_from_address(address) |
| 86 |
events: list[asyncio.Event] = [] |
| 87 |
|
| 88 |
def _on_response(data: bytes, addr: tuple[str, int]) -> None: |
| 89 |
_LOGGER.debug("udp: %s <= %s", addr, data) |
| 90 |
if data.startswith(b"+ok"): |
| 91 |
events.pop(0).set() |
| 92 |
|
| 93 |
transport_proto = await self.loop.create_datagram_endpoint( |
| 94 |
lambda: LEDENETDiscovery( |
| 95 |
destination=destination, |
| 96 |
on_response=_on_response, |
| 97 |
), |
| 98 |
sock=sock, |
| 99 |
) |
| 100 |
transport = transport_proto[0] |
| 101 |
commands: list[bytes] = [] |
| 102 |
if messages: |
| 103 |
commands.extend(messages) |
| 104 |
commands.extend(self._get_reboot_messages()) |
| 105 |
try: |
| 106 |
await self._async_send_messages( |
| 107 |
self._get_start_messages(), transport, destination |
| 108 |
) |
| 109 |
await self._async_send_and_wait( |
| 110 |
events, commands, transport, destination, timeout |
| 111 |
) |
| 112 |
finally: |
| 113 |
transport.close() |
| 114 |
|
| 115 |
async def _async_run_scan( |
| 116 |
self, |
| 117 |
transport: asyncio.DatagramTransport, |
| 118 |
destination: tuple[str, int], |
| 119 |
timeout: int, |
| 120 |
found_all_future: asyncio.Future[bool], |
| 121 |
) -> None: |
| 122 |
"""Send the scans.""" |
| 123 |
discovery_messages = self.get_discovery_messages() |
| 124 |
await self._async_send_messages(discovery_messages, transport, destination) |
| 125 |
quit_time = time.monotonic() + timeout |
| 126 |
time_out = timeout / self.BROADCAST_FREQUENCY |
| 127 |
while True: |
| 128 |
try: |
| 129 |
async with asyncio_timeout(time_out): |
| 130 |
await asyncio.shield(found_all_future) |
| 131 |
except asyncio.TimeoutError: |
| 132 |
pass |
| 133 |
else: |
| 134 |
return |
| 135 |
time_out = min( |
| 136 |
quit_time - time.monotonic(), timeout / self.BROADCAST_FREQUENCY |
| 137 |
) |
| 138 |
if time_out <= 0: |
| 139 |
return |
| 140 |
|
| 141 |
await self._async_send_messages(discovery_messages, transport, destination) |
| 142 |
|
| 143 |
async def async_scan( |
| 144 |
self, timeout: int = 10, address: str | None = None |
| 145 |
) -> list[FluxLEDDiscovery]: |
| 146 |
"""Discover LEDENET.""" |
| 147 |
sock = self._create_socket() |
| 148 |
destination = self._destination_from_address(address) |
| 149 |
found_all_future: asyncio.Future[bool] = self.loop.create_future() |
| 150 |
|
| 151 |
def _on_response(data: bytes, addr: tuple[str, int]) -> None: |
| 152 |
_LOGGER.debug("discover: %s <= %s", addr, data) |
| 153 |
if self._process_response(data, addr, address, self._discoveries): |
| 154 |
with contextlib.suppress(asyncio.InvalidStateError): |
| 155 |
found_all_future.set_result(True) |
| 156 |
|
| 157 |
transport_proto = await self.loop.create_datagram_endpoint( |
| 158 |
lambda: LEDENETDiscovery( |
| 159 |
destination=destination, |
| 160 |
on_response=_on_response, |
| 161 |
), |
| 162 |
sock=sock, |
| 163 |
) |
| 164 |
transport = transport_proto[0] |
| 165 |
try: |
| 166 |
await self._async_run_scan( |
| 167 |
transport, destination, timeout, found_all_future |
| 168 |
) |
| 169 |
finally: |
| 170 |
transport.close() |
| 171 |
|
| 172 |
return self.found_bulbs |
| 173 |
|
| 174 |
async def async_disable_remote_access(self, address: str, timeout: int = 5) -> None: |
| 175 |
"""Disable remote access.""" |
| 176 |
await self._async_send_commands_and_reboot( |
| 177 |
self._get_disable_remote_access_messages(), address, timeout |
| 178 |
) |
| 179 |
|
| 180 |
async def async_enable_remote_access( |
| 181 |
self, |
| 182 |
address: str, |
| 183 |
remote_access_host: str, |
| 184 |
remote_access_port: int, |
| 185 |
timeout: int = 5, |
| 186 |
) -> None: |
| 187 |
"""Enable remote access.""" |
| 188 |
await self._async_send_commands_and_reboot( |
| 189 |
self._get_enable_remote_access_messages( |
| 190 |
remote_access_host, remote_access_port |
| 191 |
), |
| 192 |
address, |
| 193 |
timeout, |
| 194 |
) |
| 195 |
|
| 196 |
async def async_reboot(self, address: str, timeout: int = 5) -> None: |
| 197 |
"""Reboot the device.""" |
| 198 |
await self._async_send_commands_and_reboot(None, address, timeout) |