| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import logging |
| 5 |
import time |
| 6 |
from asyncio import ALL_COMPLETED, FIRST_COMPLETED |
| 7 |
from datetime import datetime |
| 8 |
from typing import Any, Callable |
| 9 |
|
| 10 |
from .aioprotocol import AIOLEDENETProtocol |
| 11 |
from .aioscanner import AIOBulbScanner |
| 12 |
from .aioutils import asyncio_timeout |
| 13 |
from .base_device import ( |
| 14 |
ALL_ADDRESSABLE_PROTOCOLS, |
| 15 |
ALL_IC_PROTOCOLS, |
| 16 |
DeviceType, |
| 17 |
DeviceUnavailableException, |
| 18 |
LEDENETDevice, |
| 19 |
) |
| 20 |
from .const import ( |
| 21 |
COLOR_MODE_CCT, |
| 22 |
COLOR_MODE_DIM, |
| 23 |
COLOR_MODE_RGB, |
| 24 |
COLOR_MODE_RGBW, |
| 25 |
COLOR_MODE_RGBWW, |
| 26 |
EFFECT_MUSIC, |
| 27 |
EFFECT_RANDOM, |
| 28 |
NEVER_TIME, |
| 29 |
PRESET_MUSIC_MODE, |
| 30 |
PUSH_UPDATE_INTERVAL, |
| 31 |
STATE_BLUE, |
| 32 |
STATE_COOL_WHITE, |
| 33 |
STATE_GREEN, |
| 34 |
STATE_RED, |
| 35 |
STATE_WARM_WHITE, |
| 36 |
MultiColorEffects, |
| 37 |
) |
| 38 |
from .protocol import ( |
| 39 |
POWER_RESTORE_BYTES_TO_POWER_RESTORE, |
| 40 |
REMOTE_CONFIG_BYTES_TO_REMOTE_CONFIG, |
| 41 |
LEDENETOriginalRawState, |
| 42 |
LEDENETRawState, |
| 43 |
PowerRestoreState, |
| 44 |
PowerRestoreStates, |
| 45 |
ProtocolLEDENET8Byte, |
| 46 |
ProtocolLEDENETAddressableA3, |
| 47 |
ProtocolLEDENETAddressableChristmas, |
| 48 |
ProtocolLEDENETOriginal, |
| 49 |
RemoteConfig, |
| 50 |
) |
| 51 |
from .scanner import FluxLEDDiscovery |
| 52 |
from .timer import LedTimer |
| 53 |
from .utils import color_temp_to_white_levels, rgbw_brightness, rgbww_brightness |
| 54 |
|
| 55 |
_LOGGER = logging.getLogger(__name__) |
| 56 |
|
| 57 |
|
| 58 |
COMMAND_SPACING_DELAY = 1 |
| 59 |
MAX_UPDATES_WITHOUT_RESPONSE = 4 |
| 60 |
DEVICE_CONFIG_WAIT_SECONDS = ( |
| 61 |
3.5 |
| 62 |
) |
| 63 |
POWER_STATE_TIMEOUT = 1.2 |
| 64 |
POWER_CHANGE_ATTEMPTS = 6 |
| 65 |
|
| 66 |
|
| 67 |
class AIOWifiLedBulb(LEDENETDevice): |
| 68 |
"""A LEDENET Wifi bulb device.""" |
| 69 |
|
| 70 |
def __init__( |
| 71 |
self, |
| 72 |
ipaddr: str, |
| 73 |
port: int = 0, |
| 74 |
timeout: float = 7.5, |
| 75 |
discovery: FluxLEDDiscovery | None = None, |
| 76 |
) -> None: |
| 77 |
"""Init and setup the bulb.""" |
| 78 |
super().__init__(ipaddr, port, timeout, discovery) |
| 79 |
loop = asyncio.get_running_loop() |
| 80 |
self._connect_lock = asyncio.Lock() |
| 81 |
self._aio_protocol: AIOLEDENETProtocol | None = None |
| 82 |
self._get_time_lock: asyncio.Lock = asyncio.Lock() |
| 83 |
self._get_time_future: asyncio.Future[bool] | None = None |
| 84 |
self._get_timers_lock: asyncio.Lock = asyncio.Lock() |
| 85 |
self._get_timers_future: asyncio.Future[bool] | None = None |
| 86 |
self._timers: list[LedTimer] | None = None |
| 87 |
self._power_restore_future: asyncio.Future[bool] = loop.create_future() |
| 88 |
self._device_config_lock: asyncio.Lock = asyncio.Lock() |
| 89 |
self._device_config_future: asyncio.Future[bool] = loop.create_future() |
| 90 |
self._remote_config_future: asyncio.Future[bool] = loop.create_future() |
| 91 |
self._device_config_setup = False |
| 92 |
self._power_state_lock = asyncio.Lock() |
| 93 |
self._power_state_futures: list[asyncio.Future[bool]] = [] |
| 94 |
self._state_futures: list[ |
| 95 |
asyncio.Future[LEDENETRawState | LEDENETOriginalRawState] |
| 96 |
] = [] |
| 97 |
self._determine_protocol_future: asyncio.Future[bool] | None = None |
| 98 |
self._updated_callback: Callable[[], None] | None = None |
| 99 |
self._updates_without_response = 0 |
| 100 |
self._last_update_time: float = NEVER_TIME |
| 101 |
self._power_restore_state: PowerRestoreStates | None = None |
| 102 |
self._buffer = b"" |
| 103 |
self.loop = loop |
| 104 |
|
| 105 |
@property |
| 106 |
def power_restore_states(self) -> PowerRestoreStates | None: |
| 107 |
"""Returns the power restore states for all channels.""" |
| 108 |
return self._power_restore_state |
| 109 |
|
| 110 |
async def async_setup(self, updated_callback: Callable[[], None]) -> None: |
| 111 |
"""Setup the connection and fetch initial state.""" |
| 112 |
self._updated_callback = updated_callback |
| 113 |
try: |
| 114 |
await self._async_setup() |
| 115 |
except Exception: |
| 116 |
self._async_stop() |
| 117 |
raise |
| 118 |
|
| 119 |
async def _async_setup(self) -> None: |
| 120 |
await self._async_determine_protocol() |
| 121 |
assert self._protocol is not None |
| 122 |
if isinstance(self._protocol, ALL_IC_PROTOCOLS): |
| 123 |
await self._async_device_config_setup() |
| 124 |
hardware = self.hardware |
| 125 |
if hardware is not None and hardware.remote_24g_controls: |
| 126 |
await self._async_remote_config_setup() |
| 127 |
if self.device_type == DeviceType.Switch: |
| 128 |
await self._async_switch_setup() |
| 129 |
_LOGGER.debug( |
| 130 |
"%s: device_config: wiring=%s operating_mode=%s", |
| 131 |
self.ipaddr, |
| 132 |
self.wiring, |
| 133 |
self.operating_mode, |
| 134 |
) |
| 135 |
|
| 136 |
async def _async_remote_config_setup(self) -> None: |
| 137 |
"""Setup remote config.""" |
| 138 |
assert self._protocol is not None |
| 139 |
await self._async_send_msg(self._protocol.construct_query_remote_config()) |
| 140 |
try: |
| 141 |
async with asyncio_timeout(self.timeout): |
| 142 |
await self._remote_config_future |
| 143 |
except asyncio.TimeoutError: |
| 144 |
_LOGGER.warning("%s: Could not determine 2.4ghz remote config", self.ipaddr) |
| 145 |
|
| 146 |
async def _async_switch_setup(self) -> None: |
| 147 |
"""Setup a switch.""" |
| 148 |
assert self._protocol is not None |
| 149 |
await self._async_send_msg(self._protocol.construct_power_restore_state_query()) |
| 150 |
try: |
| 151 |
async with asyncio_timeout(self.timeout): |
| 152 |
await self._power_restore_future |
| 153 |
except asyncio.TimeoutError: |
| 154 |
self.set_unavailable("Could not determine power restore state") |
| 155 |
raise DeviceUnavailableException( |
| 156 |
f"{self.ipaddr}: Could not determine power restore state" |
| 157 |
) |
| 158 |
|
| 159 |
async def _async_device_config_setup(self) -> None: |
| 160 |
"""Setup an addressable light.""" |
| 161 |
assert self._protocol is not None |
| 162 |
if isinstance(self._protocol, ProtocolLEDENETAddressableChristmas): |
| 163 |
self._device_config = self._protocol.parse_strip_setting(b"") |
| 164 |
return |
| 165 |
|
| 166 |
if self._device_config_setup: |
| 167 |
self._device_config_future = self.loop.create_future() |
| 168 |
self._device_config_setup = True |
| 169 |
|
| 170 |
assert isinstance(self._protocol, ALL_ADDRESSABLE_PROTOCOLS) |
| 171 |
await self._async_send_msg(self._protocol.construct_request_strip_setting()) |
| 172 |
try: |
| 173 |
async with asyncio_timeout(self.timeout): |
| 174 |
await self._device_config_future |
| 175 |
except asyncio.TimeoutError: |
| 176 |
self.set_unavailable("Could not determine number pixels") |
| 177 |
raise DeviceUnavailableException( |
| 178 |
f"{self.ipaddr}: Could not determine number pixels" |
| 179 |
) |
| 180 |
|
| 181 |
async def async_stop(self) -> None: |
| 182 |
"""Shutdown the connection.""" |
| 183 |
self._async_stop() |
| 184 |
|
| 185 |
def _async_stop(self) -> None: |
| 186 |
"""Shutdown the connection and mark unavailable.""" |
| 187 |
self.set_unavailable("Connection closed") |
| 188 |
self._async_close() |
| 189 |
self._last_update_time = NEVER_TIME |
| 190 |
|
| 191 |
def _async_close(self) -> None: |
| 192 |
"""Close the connection.""" |
| 193 |
if self._aio_protocol: |
| 194 |
self._aio_protocol.close() |
| 195 |
self._aio_protocol = None |
| 196 |
|
| 197 |
async def _async_send_state_query(self) -> None: |
| 198 |
assert self._protocol is not None |
| 199 |
await self._async_send_msg(self._protocol.construct_state_query()) |
| 200 |
|
| 201 |
async def _async_wait_state_change( |
| 202 |
self, futures: list[asyncio.Future[Any]], state: bool, timeout: float |
| 203 |
) -> bool: |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
return_when = ALL_COMPLETED if self.requires_turn_on else FIRST_COMPLETED |
| 208 |
done, _ = await asyncio.wait(futures, timeout=timeout, return_when=return_when) |
| 209 |
return bool(done and self.is_on == state) |
| 210 |
|
| 211 |
async def _async_set_power_state( |
| 212 |
self, state: bool, accept_any_power_state_response: bool |
| 213 |
) -> bool: |
| 214 |
assert self._protocol is not None |
| 215 |
power_state_future: asyncio.Future[bool] = self.loop.create_future() |
| 216 |
state_future: asyncio.Future[LEDENETRawState | LEDENETOriginalRawState] = ( |
| 217 |
self.loop.create_future() |
| 218 |
) |
| 219 |
self._power_state_futures.append(power_state_future) |
| 220 |
self._state_futures.append(state_future) |
| 221 |
await self._async_send_msg(self._protocol.construct_state_change(state)) |
| 222 |
_LOGGER.debug("%s: Waiting for power state response", self.ipaddr) |
| 223 |
if await self._async_wait_state_change( |
| 224 |
[state_future, power_state_future], state, POWER_STATE_TIMEOUT * (3 / 8) |
| 225 |
): |
| 226 |
return True |
| 227 |
if power_state_future.done() and accept_any_power_state_response: |
| 228 |
|
| 229 |
|
| 230 |
return True |
| 231 |
if power_state_future.done() or state_future.done(): |
| 232 |
_LOGGER.debug( |
| 233 |
"%s: Bulb power state change taking longer than expected to %s, sending state query", |
| 234 |
self.ipaddr, |
| 235 |
state, |
| 236 |
) |
| 237 |
else: |
| 238 |
_LOGGER.debug( |
| 239 |
"%s: Bulb failed to respond, sending state query", self.ipaddr |
| 240 |
) |
| 241 |
if state_future.done(): |
| 242 |
state_future = self.loop.create_future() |
| 243 |
self._state_futures.append(state_future) |
| 244 |
pending: list[asyncio.Future[Any]] = [state_future] |
| 245 |
if not power_state_future.done(): |
| 246 |
|
| 247 |
|
| 248 |
pending.append(power_state_future) |
| 249 |
await self._async_send_state_query() |
| 250 |
if await self._async_wait_state_change( |
| 251 |
pending, state, POWER_STATE_TIMEOUT * (5 / 8) |
| 252 |
): |
| 253 |
return True |
| 254 |
_LOGGER.debug( |
| 255 |
"%s: State query did not return expected power state of %s", |
| 256 |
self.ipaddr, |
| 257 |
state, |
| 258 |
) |
| 259 |
return False |
| 260 |
|
| 261 |
async def async_turn_on(self) -> bool: |
| 262 |
"""Turn on the device.""" |
| 263 |
return await self._async_set_power_locked(True) |
| 264 |
|
| 265 |
async def async_turn_off(self) -> bool: |
| 266 |
"""Turn off the device.""" |
| 267 |
return await self._async_set_power_locked(False) |
| 268 |
|
| 269 |
async def _async_set_power_locked(self, state: bool) -> bool: |
| 270 |
async with self._power_state_lock: |
| 271 |
self._power_state_transition_complete_time = NEVER_TIME |
| 272 |
return await self._async_set_power_state_with_retry(state) |
| 273 |
|
| 274 |
async def _async_set_power_state_with_retry(self, state: bool) -> bool: |
| 275 |
for idx in range(POWER_CHANGE_ATTEMPTS): |
| 276 |
accept_any_power_state_response = idx > 2 |
| 277 |
if await self._async_set_power_state( |
| 278 |
state, accept_any_power_state_response |
| 279 |
): |
| 280 |
_LOGGER.debug( |
| 281 |
"%s: Completed power state change to %s (%s/%s)", |
| 282 |
self.ipaddr, |
| 283 |
state, |
| 284 |
1 + idx, |
| 285 |
POWER_CHANGE_ATTEMPTS, |
| 286 |
) |
| 287 |
if accept_any_power_state_response and self.is_on != state: |
| 288 |
|
| 289 |
|
| 290 |
assert self._protocol is not None |
| 291 |
byte = self._protocol.on_byte if state else self._protocol.off_byte |
| 292 |
self._set_power_state(byte) |
| 293 |
self._set_power_transition_complete_time() |
| 294 |
return True |
| 295 |
_LOGGER.debug( |
| 296 |
"%s: Failed to set power state to %s (%s/%s)", |
| 297 |
self.ipaddr, |
| 298 |
state, |
| 299 |
1 + idx, |
| 300 |
POWER_CHANGE_ATTEMPTS, |
| 301 |
) |
| 302 |
_LOGGER.error( |
| 303 |
"%s: Failed to change power state to %s after %s attempts; Try rebooting the device", |
| 304 |
self.ipaddr, |
| 305 |
state, |
| 306 |
POWER_CHANGE_ATTEMPTS, |
| 307 |
) |
| 308 |
return False |
| 309 |
|
| 310 |
async def async_set_white_temp( |
| 311 |
self, temperature: int, brightness: int, persist: bool = True |
| 312 |
) -> None: |
| 313 |
"""Set the white tempature.""" |
| 314 |
warm, cold = color_temp_to_white_levels( |
| 315 |
temperature, brightness, self.min_temp, self.max_temp |
| 316 |
) |
| 317 |
if self.rgbw_color_temp_support(self.color_modes): |
| 318 |
await self.async_set_levels(cold, cold, cold, warm, 0, persist=persist) |
| 319 |
else: |
| 320 |
await self.async_set_levels(None, None, None, warm, cold, persist=persist) |
| 321 |
|
| 322 |
async def async_update(self, force: bool = False) -> None: |
| 323 |
"""Request an update. |
| 324 |
|
| 325 |
The callback will be triggered when the state is recieved. |
| 326 |
""" |
| 327 |
now = time.monotonic() |
| 328 |
assert self._protocol is not None |
| 329 |
if ( |
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
self.available |
| 334 |
and not force |
| 335 |
and (self._last_update_time + PUSH_UPDATE_INTERVAL) > now |
| 336 |
): |
| 337 |
if self.is_on and self._protocol.state_push_updates: |
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
return |
| 342 |
if self._protocol.power_push_updates: |
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
return |
| 347 |
self._last_update_time = now |
| 348 |
if ( |
| 349 |
self._aio_protocol |
| 350 |
and self._updates_without_response >= MAX_UPDATES_WITHOUT_RESPONSE |
| 351 |
): |
| 352 |
self._async_close() |
| 353 |
self.set_unavailable( |
| 354 |
f"device stopped responding after {MAX_UPDATES_WITHOUT_RESPONSE} requests to send state" |
| 355 |
) |
| 356 |
raise DeviceUnavailableException( |
| 357 |
f"{self.ipaddr}: device stopped responding after {MAX_UPDATES_WITHOUT_RESPONSE} requests to send state" |
| 358 |
) |
| 359 |
try: |
| 360 |
await self._async_send_state_query() |
| 361 |
except asyncio.TimeoutError as ex: |
| 362 |
raise DeviceUnavailableException( |
| 363 |
f"{self.ipaddr}: timed out trying to connect after {self.timeout} seconds" |
| 364 |
) from ex |
| 365 |
|
| 366 |
self._updates_without_response += 1 |
| 367 |
|
| 368 |
async def async_set_levels( |
| 369 |
self, |
| 370 |
r: int | None = None, |
| 371 |
g: int | None = None, |
| 372 |
b: int | None = None, |
| 373 |
w: int | None = None, |
| 374 |
w2: int | None = None, |
| 375 |
persist: bool = True, |
| 376 |
brightness: int | None = None, |
| 377 |
) -> None: |
| 378 |
"""Set any of the levels.""" |
| 379 |
await self._async_process_levels_change( |
| 380 |
*self._generate_levels_change( |
| 381 |
{ |
| 382 |
STATE_RED: r, |
| 383 |
STATE_GREEN: g, |
| 384 |
STATE_BLUE: b, |
| 385 |
STATE_WARM_WHITE: w, |
| 386 |
STATE_COOL_WHITE: w2, |
| 387 |
}, |
| 388 |
persist, |
| 389 |
brightness, |
| 390 |
) |
| 391 |
) |
| 392 |
|
| 393 |
async def _async_process_levels_change( |
| 394 |
self, msgs: list[bytearray], updates: dict[str, int] |
| 395 |
) -> None: |
| 396 |
"""Process and send a levels change.""" |
| 397 |
self._set_transition_complete_time() |
| 398 |
if updates: |
| 399 |
self._replace_raw_state(updates) |
| 400 |
for idx, msg in enumerate(msgs): |
| 401 |
await self._async_send_msg(msg) |
| 402 |
if idx > 0: |
| 403 |
self._process_callbacks() |
| 404 |
await asyncio.sleep(COMMAND_SPACING_DELAY) |
| 405 |
self._set_transition_complete_time() |
| 406 |
|
| 407 |
async def async_set_preset_pattern( |
| 408 |
self, effect: int, speed: int, brightness: int = 100 |
| 409 |
) -> None: |
| 410 |
"""Set a preset pattern on the device.""" |
| 411 |
self._set_transition_complete_time() |
| 412 |
await self._async_send_msg( |
| 413 |
self._generate_preset_pattern(effect, speed, brightness) |
| 414 |
) |
| 415 |
|
| 416 |
async def async_set_custom_pattern( |
| 417 |
self, rgb_list: list[tuple[int, int, int]], speed: int, transition_type: str |
| 418 |
) -> None: |
| 419 |
"""Set a custom pattern on the device.""" |
| 420 |
await self._async_send_msg( |
| 421 |
self._generate_custom_patterm(rgb_list, speed, transition_type) |
| 422 |
) |
| 423 |
|
| 424 |
async def async_set_effect( |
| 425 |
self, effect: str, speed: int, brightness: int = 100 |
| 426 |
) -> None: |
| 427 |
"""Set an effect.""" |
| 428 |
if effect == EFFECT_RANDOM: |
| 429 |
await self.async_set_random() |
| 430 |
return |
| 431 |
brightness = min(100, max(0, brightness)) |
| 432 |
if effect == EFFECT_MUSIC: |
| 433 |
await self.async_set_music_mode(brightness=brightness) |
| 434 |
return |
| 435 |
await self.async_set_preset_pattern( |
| 436 |
self._effect_to_pattern(effect), speed, brightness |
| 437 |
) |
| 438 |
|
| 439 |
async def async_set_zones( |
| 440 |
self, |
| 441 |
rgb_list: list[tuple[int, int, int]], |
| 442 |
speed: int = 100, |
| 443 |
effect: MultiColorEffects = MultiColorEffects.STATIC, |
| 444 |
) -> None: |
| 445 |
"""Set zones.""" |
| 446 |
assert self._protocol is not None |
| 447 |
if not self._protocol.zones: |
| 448 |
raise ValueError("{self.model} does not support zones") |
| 449 |
assert self._device_config is not None |
| 450 |
assert isinstance( |
| 451 |
self._protocol, |
| 452 |
(ProtocolLEDENETAddressableA3, ProtocolLEDENETAddressableChristmas), |
| 453 |
) |
| 454 |
await self._async_send_msg( |
| 455 |
self._protocol.construct_zone_change( |
| 456 |
self._device_config.pixels_per_segment, rgb_list, speed, effect |
| 457 |
) |
| 458 |
) |
| 459 |
|
| 460 |
async def async_set_music_mode( |
| 461 |
self, |
| 462 |
sensitivity: int | None = 100, |
| 463 |
brightness: int | None = 100, |
| 464 |
mode: int | None = None, |
| 465 |
effect: int | None = None, |
| 466 |
foreground_color: tuple[int, int, int] | None = None, |
| 467 |
background_color: tuple[int, int, int] | None = None, |
| 468 |
) -> None: |
| 469 |
"""Set music mode.""" |
| 470 |
assert self._protocol is not None |
| 471 |
if not self.microphone: |
| 472 |
raise ValueError("{self.model} does not have a built-in microphone") |
| 473 |
self._set_preset_pattern_transition_complete_time() |
| 474 |
self._replace_raw_state({"preset_pattern": PRESET_MUSIC_MODE}) |
| 475 |
for idx, bytes_send in enumerate( |
| 476 |
self._protocol.construct_music_mode( |
| 477 |
sensitivity or 100, |
| 478 |
brightness or 100, |
| 479 |
mode, |
| 480 |
effect, |
| 481 |
foreground_color or self.rgb, |
| 482 |
background_color, |
| 483 |
) |
| 484 |
): |
| 485 |
if idx > 0: |
| 486 |
await asyncio.sleep(COMMAND_SPACING_DELAY) |
| 487 |
await self._async_send_msg(bytes_send) |
| 488 |
|
| 489 |
async def async_set_random(self) -> None: |
| 490 |
"""Set levels randomly.""" |
| 491 |
await self._async_process_levels_change(*self._generate_random_levels_change()) |
| 492 |
|
| 493 |
async def async_set_brightness(self, brightness: int) -> None: |
| 494 |
"""Adjust brightness.""" |
| 495 |
effect = self.effect |
| 496 |
if effect: |
| 497 |
effect_brightness = round(brightness / 255 * 100) |
| 498 |
await self.async_set_effect(effect, self.speed, effect_brightness) |
| 499 |
return |
| 500 |
if self.color_mode == COLOR_MODE_CCT: |
| 501 |
await self.async_set_white_temp(self.color_temp, brightness) |
| 502 |
return |
| 503 |
if self.color_mode == COLOR_MODE_RGB: |
| 504 |
await self.async_set_levels(*self.rgb_unscaled, brightness=brightness) |
| 505 |
return |
| 506 |
if self.color_mode == COLOR_MODE_RGBW: |
| 507 |
await self.async_set_levels(*rgbw_brightness(self.rgbw, brightness)) |
| 508 |
return |
| 509 |
if self.color_mode == COLOR_MODE_RGBWW: |
| 510 |
await self.async_set_levels(*rgbww_brightness(self.rgbww, brightness)) |
| 511 |
return |
| 512 |
if self.color_mode == COLOR_MODE_DIM: |
| 513 |
await self.async_set_levels(w=brightness) |
| 514 |
return |
| 515 |
|
| 516 |
async def async_enable_remote_access( |
| 517 |
self, remote_access_host: str, remote_access_port: int |
| 518 |
) -> None: |
| 519 |
"""Enable remote access.""" |
| 520 |
await AIOBulbScanner().async_enable_remote_access( |
| 521 |
self.ipaddr, remote_access_host, remote_access_port |
| 522 |
) |
| 523 |
self._async_stop() |
| 524 |
|
| 525 |
async def async_disable_remote_access(self) -> None: |
| 526 |
"""Disable remote access.""" |
| 527 |
await AIOBulbScanner().async_disable_remote_access(self.ipaddr) |
| 528 |
self._async_stop() |
| 529 |
|
| 530 |
async def async_reboot(self) -> None: |
| 531 |
"""Reboot a device.""" |
| 532 |
await AIOBulbScanner().async_reboot(self.ipaddr) |
| 533 |
self._async_stop() |
| 534 |
|
| 535 |
async def async_set_power_restore( |
| 536 |
self, |
| 537 |
channel1: PowerRestoreState | None = None, |
| 538 |
channel2: PowerRestoreState | None = None, |
| 539 |
channel3: PowerRestoreState | None = None, |
| 540 |
channel4: PowerRestoreState | None = None, |
| 541 |
) -> None: |
| 542 |
new_power_restore_state = self._power_restore_state |
| 543 |
assert new_power_restore_state is not None |
| 544 |
if channel1 is not None: |
| 545 |
new_power_restore_state.channel1 = channel1 |
| 546 |
if channel2 is not None: |
| 547 |
new_power_restore_state.channel2 = channel2 |
| 548 |
if channel3 is not None: |
| 549 |
new_power_restore_state.channel3 = channel3 |
| 550 |
if channel4 is not None: |
| 551 |
new_power_restore_state.channel4 = channel4 |
| 552 |
assert self._protocol is not None |
| 553 |
await self._async_send_msg( |
| 554 |
self._protocol.construct_power_restore_state_change(new_power_restore_state) |
| 555 |
) |
| 556 |
|
| 557 |
async def async_set_device_config( |
| 558 |
self, |
| 559 |
operating_mode: str | None = None, |
| 560 |
wiring: str | None = None, |
| 561 |
ic_type: str | None = None, |
| 562 |
pixels_per_segment: int | None = None, |
| 563 |
segments: int | None = None, |
| 564 |
music_pixels_per_segment: int | None = None, |
| 565 |
music_segments: int | None = None, |
| 566 |
) -> None: |
| 567 |
"""Set device configuration.""" |
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
async with self._device_config_lock: |
| 573 |
device_config = self.model_data.device_config |
| 574 |
ic_type_to_num = device_config.ic_type_to_num |
| 575 |
operating_mode_to_num = device_config.operating_mode_to_num |
| 576 |
if self._device_config is not None: |
| 577 |
wiring_to_num = self._device_config.wiring_to_num |
| 578 |
else: |
| 579 |
wiring_to_num = device_config.wiring_to_num |
| 580 |
operating_mode_num = ( |
| 581 |
self.operating_mode_num |
| 582 |
if operating_mode is None |
| 583 |
else operating_mode_to_num[operating_mode] |
| 584 |
) |
| 585 |
wiring_num = self.wiring_num if wiring is None else wiring_to_num[wiring] |
| 586 |
ic_type_num = ( |
| 587 |
self.ic_type_num if ic_type is None else ic_type_to_num[ic_type] |
| 588 |
) |
| 589 |
assert self._protocol is not None |
| 590 |
assert not isinstance(self._protocol, ProtocolLEDENETOriginal) |
| 591 |
await self._async_send_msg( |
| 592 |
self._protocol.construct_device_config( |
| 593 |
operating_mode_num, |
| 594 |
wiring_num, |
| 595 |
ic_type_num, |
| 596 |
pixels_per_segment or self.pixels_per_segment, |
| 597 |
segments or self.segments, |
| 598 |
music_pixels_per_segment or self.music_pixels_per_segment, |
| 599 |
music_segments or self.music_segments, |
| 600 |
) |
| 601 |
) |
| 602 |
if isinstance(self._protocol, ALL_IC_PROTOCOLS): |
| 603 |
await self._async_device_config_resync() |
| 604 |
|
| 605 |
async def async_unpair_remotes(self) -> None: |
| 606 |
"""Unpair 2.4ghz remotes.""" |
| 607 |
assert self._protocol is not None |
| 608 |
if self.paired_remotes is None: |
| 609 |
raise ValueError("{self.model} does support unpairing remotes") |
| 610 |
await self._async_send_msg(self._protocol.construct_unpair_remotes()) |
| 611 |
await self._async_send_msg(self._protocol.construct_query_remote_config()) |
| 612 |
|
| 613 |
async def async_config_remotes(self, remote_config: RemoteConfig) -> None: |
| 614 |
"""Change remote config.""" |
| 615 |
assert self._protocol is not None |
| 616 |
if self.paired_remotes is None: |
| 617 |
raise ValueError("{self.model} does support unpairing remotes") |
| 618 |
await self._async_send_msg( |
| 619 |
self._protocol.construct_remote_config(remote_config) |
| 620 |
) |
| 621 |
await self._async_send_msg(self._protocol.construct_query_remote_config()) |
| 622 |
|
| 623 |
async def async_get_time(self) -> datetime | None: |
| 624 |
"""Get the current time.""" |
| 625 |
assert self._protocol is not None |
| 626 |
await self._async_send_msg(self._protocol.construct_get_time()) |
| 627 |
async with self._get_time_lock: |
| 628 |
self._get_time_future = self.loop.create_future() |
| 629 |
try: |
| 630 |
async with asyncio_timeout(self.timeout): |
| 631 |
await self._get_time_future |
| 632 |
except asyncio.TimeoutError: |
| 633 |
_LOGGER.warning("%s: Could not get time from the device", self.ipaddr) |
| 634 |
return None |
| 635 |
return self._last_time |
| 636 |
|
| 637 |
async def async_get_timers(self) -> list[LedTimer] | None: |
| 638 |
"""Get the timers.""" |
| 639 |
assert self._protocol is not None |
| 640 |
if isinstance(self._protocol, ProtocolLEDENETOriginal): |
| 641 |
led_timers: list[LedTimer] = [] |
| 642 |
return led_timers |
| 643 |
await self._async_send_msg(self._protocol.construct_get_timers()) |
| 644 |
async with self._get_timers_lock: |
| 645 |
self._get_timers_future = self.loop.create_future() |
| 646 |
try: |
| 647 |
async with asyncio_timeout(self.timeout): |
| 648 |
await self._get_timers_future |
| 649 |
except asyncio.TimeoutError: |
| 650 |
_LOGGER.warning("%s: Could not get timers from the device", self.ipaddr) |
| 651 |
return None |
| 652 |
return self._timers |
| 653 |
|
| 654 |
async def async_set_timers(self, timer_list: list[LedTimer]) -> None: |
| 655 |
"""Set the timers.""" |
| 656 |
assert self._protocol is not None |
| 657 |
await self._async_send_msg(self._protocol.construct_set_timers(timer_list)) |
| 658 |
|
| 659 |
async def async_set_time(self, time: datetime | None = None) -> None: |
| 660 |
"""Set the current time.""" |
| 661 |
assert self._protocol is not None |
| 662 |
await self._async_send_msg(self._protocol.construct_set_time(time)) |
| 663 |
|
| 664 |
async def _async_device_config_resync(self) -> None: |
| 665 |
await asyncio.sleep(DEVICE_CONFIG_WAIT_SECONDS) |
| 666 |
await self._async_device_config_setup() |
| 667 |
|
| 668 |
async def _async_connect(self) -> None: |
| 669 |
"""Create connection.""" |
| 670 |
async with asyncio_timeout(self.timeout): |
| 671 |
_, self._aio_protocol = await self.loop.create_connection( |
| 672 |
lambda: AIOLEDENETProtocol( |
| 673 |
self._async_data_recieved, self._async_connection_lost |
| 674 |
), |
| 675 |
self.ipaddr, |
| 676 |
self.port, |
| 677 |
) |
| 678 |
|
| 679 |
def _async_connection_lost(self, exc: Exception | None) -> None: |
| 680 |
"""Called when the connection is lost.""" |
| 681 |
self._aio_protocol = None |
| 682 |
self.set_unavailable("Connection lost") |
| 683 |
|
| 684 |
def _async_data_recieved(self, data: bytes) -> None: |
| 685 |
"""New data on the socket.""" |
| 686 |
assert self._protocol is not None |
| 687 |
assert self._aio_protocol is not None |
| 688 |
start_empty_buffer = not self._buffer |
| 689 |
self._buffer += data |
| 690 |
self._updates_without_response = 0 |
| 691 |
msg_length = len(self._buffer) |
| 692 |
while msg_length: |
| 693 |
expected_length = self._protocol.expected_response_length(self._buffer) |
| 694 |
if msg_length < expected_length: |
| 695 |
|
| 696 |
return |
| 697 |
msg = self._buffer[:expected_length] |
| 698 |
self._buffer = self._buffer[expected_length:] |
| 699 |
msg_length = len(self._buffer) |
| 700 |
if not start_empty_buffer: |
| 701 |
_LOGGER.debug( |
| 702 |
"%s <= Reassembled (%s) (%d)", |
| 703 |
self._aio_protocol.peername, |
| 704 |
" ".join(f"0x{x:02X}" for x in msg), |
| 705 |
len(msg), |
| 706 |
) |
| 707 |
self._async_process_message(msg) |
| 708 |
|
| 709 |
def _async_process_state_response(self, msg: bytes) -> bool: |
| 710 |
if ( |
| 711 |
self._determine_protocol_future |
| 712 |
and not self._determine_protocol_future.done() |
| 713 |
): |
| 714 |
assert self._protocol is not None |
| 715 |
self._set_protocol_from_msg(msg, self._protocol.name) |
| 716 |
self._determine_protocol_future.set_result(True) |
| 717 |
return self.process_state_response(msg) |
| 718 |
|
| 719 |
def _async_process_message(self, msg: bytes) -> None: |
| 720 |
"""Process a full message (maybe reassembled).""" |
| 721 |
assert self._protocol is not None |
| 722 |
self.set_available(f"Received message {msg.hex()}") |
| 723 |
prev_state = self.raw_state |
| 724 |
changed_state = False |
| 725 |
if self._protocol.is_valid_outer_message(msg): |
| 726 |
msg = self._protocol.extract_inner_message(msg) |
| 727 |
|
| 728 |
if self._protocol.is_valid_state_response(msg): |
| 729 |
self._last_message["state"] = msg |
| 730 |
self._async_process_state_response(msg) |
| 731 |
self._process_state_futures() |
| 732 |
elif self._protocol.is_valid_extended_state_response(msg): |
| 733 |
self._last_message["extended_state"] = msg |
| 734 |
self.process_extended_state_response(msg) |
| 735 |
elif self._protocol.is_valid_power_state_response(msg): |
| 736 |
self._last_message["power_state"] = msg |
| 737 |
self.process_power_state_response(msg) |
| 738 |
self._process_power_futures() |
| 739 |
elif self._protocol.is_valid_get_time_response(msg): |
| 740 |
self._last_message["get_time"] = msg |
| 741 |
self.process_time_response(msg) |
| 742 |
elif self._protocol.is_valid_timers_response(msg): |
| 743 |
self._last_message["timers"] = msg |
| 744 |
self.process_timers_response(msg) |
| 745 |
changed_state = True |
| 746 |
elif self._protocol.is_valid_device_config_response(msg): |
| 747 |
self._last_message["device_config"] = msg |
| 748 |
self.process_device_config_response(msg) |
| 749 |
changed_state = True |
| 750 |
elif self._protocol.is_valid_power_restore_state_response(msg): |
| 751 |
self._last_message["power_restore_state"] = msg |
| 752 |
self.process_power_restore_state_response(msg) |
| 753 |
elif self._protocol.is_valid_remote_config_response(msg): |
| 754 |
self._last_message["remote_config"] = msg |
| 755 |
self.process_remote_config_response(msg) |
| 756 |
changed_state = True |
| 757 |
else: |
| 758 |
self._last_message["unknown"] = msg |
| 759 |
_LOGGER.debug( |
| 760 |
"%s: Ignoring unknown message: %s", |
| 761 |
self.ipaddr, |
| 762 |
" ".join(f"0x{x:02X}" for x in msg), |
| 763 |
) |
| 764 |
return |
| 765 |
if not changed_state and self.raw_state == prev_state: |
| 766 |
return |
| 767 |
self._process_callbacks() |
| 768 |
|
| 769 |
def _process_state_futures(self) -> None: |
| 770 |
"""Process power future responses.""" |
| 771 |
assert self.raw_state is not None |
| 772 |
for future in self._state_futures: |
| 773 |
if not future.done(): |
| 774 |
future.set_result(self.raw_state) |
| 775 |
self._state_futures.clear() |
| 776 |
|
| 777 |
def _process_power_futures(self) -> None: |
| 778 |
"""Process power future responses.""" |
| 779 |
for future in self._power_state_futures: |
| 780 |
if not future.done(): |
| 781 |
future.set_result(self.is_on) |
| 782 |
self._power_state_futures.clear() |
| 783 |
|
| 784 |
def _process_callbacks(self) -> None: |
| 785 |
"""Called when state changes.""" |
| 786 |
assert self._updated_callback is not None |
| 787 |
try: |
| 788 |
self._updated_callback() |
| 789 |
except Exception as ex: |
| 790 |
_LOGGER.exception("Error while calling callback: %s", ex) |
| 791 |
|
| 792 |
def process_power_restore_state_response(self, msg: bytes) -> None: |
| 793 |
"""Process a power restore state response. |
| 794 |
Power on state always off |
| 795 |
f0 32 ff f0 f0 f0 f1 |
| 796 |
Power on state always on |
| 797 |
f0 32 0f f0 f0 f0 01 |
| 798 |
Power on state keep last state |
| 799 |
f0 32 f0 f0 f0 f0 e2 |
| 800 |
""" |
| 801 |
self._power_restore_state = PowerRestoreStates( |
| 802 |
channel1=POWER_RESTORE_BYTES_TO_POWER_RESTORE.get(msg[2]), |
| 803 |
channel2=POWER_RESTORE_BYTES_TO_POWER_RESTORE.get(msg[3]), |
| 804 |
channel3=POWER_RESTORE_BYTES_TO_POWER_RESTORE.get(msg[4]), |
| 805 |
channel4=POWER_RESTORE_BYTES_TO_POWER_RESTORE.get(msg[5]), |
| 806 |
) |
| 807 |
if not self._power_restore_future.done(): |
| 808 |
self._power_restore_future.set_result(True) |
| 809 |
|
| 810 |
def process_device_config_response(self, msg: bytes) -> None: |
| 811 |
"""Process an IC (strip config) response.""" |
| 812 |
super().process_device_config_response(msg) |
| 813 |
if not self._device_config_future.done(): |
| 814 |
self._device_config_future.set_result(True) |
| 815 |
|
| 816 |
def process_time_response(self, msg: bytes) -> None: |
| 817 |
"""Process an time response.""" |
| 818 |
assert self._protocol is not None |
| 819 |
self._last_time = self._protocol.parse_get_time(msg) |
| 820 |
if self._get_time_future and not self._get_time_future.done(): |
| 821 |
self._get_time_future.set_result(True) |
| 822 |
|
| 823 |
def process_timers_response(self, msg: bytes) -> None: |
| 824 |
"""Process an timers response.""" |
| 825 |
assert self._protocol is not None |
| 826 |
self._timers = self._protocol.parse_get_timers(msg) |
| 827 |
if self._get_timers_future and not self._get_timers_future.done(): |
| 828 |
self._get_timers_future.set_result(True) |
| 829 |
|
| 830 |
def process_remote_config_response(self, msg: bytes) -> None: |
| 831 |
"""Process a 2.4ghz remote config response.""" |
| 832 |
|
| 833 |
|
| 834 |
self._paired_remotes = msg[3] |
| 835 |
self._remote_config = REMOTE_CONFIG_BYTES_TO_REMOTE_CONFIG.get(msg[1]) |
| 836 |
_LOGGER.debug( |
| 837 |
"%s: remote_config: config=%s paired_remotes=%s", |
| 838 |
self.ipaddr, |
| 839 |
self._remote_config, |
| 840 |
self._paired_remotes, |
| 841 |
) |
| 842 |
if not self._remote_config_future.done(): |
| 843 |
self._remote_config_future.set_result(True) |
| 844 |
|
| 845 |
async def _async_send_msg(self, msg: bytearray) -> None: |
| 846 |
"""Write a message on the socket.""" |
| 847 |
if not self._aio_protocol: |
| 848 |
async with self._connect_lock: |
| 849 |
|
| 850 |
if not self._aio_protocol: |
| 851 |
await self._async_connect() |
| 852 |
assert self._aio_protocol is not None |
| 853 |
self._aio_protocol.write(msg) |
| 854 |
|
| 855 |
async def _async_determine_protocol(self) -> None: |
| 856 |
|
| 857 |
for protocol_cls in self._protocol_probes(): |
| 858 |
protocol = protocol_cls() |
| 859 |
assert isinstance(protocol, (ProtocolLEDENET8Byte, ProtocolLEDENETOriginal)) |
| 860 |
self._protocol = protocol |
| 861 |
async with self._connect_lock: |
| 862 |
await self._async_connect() |
| 863 |
assert self._aio_protocol is not None |
| 864 |
self._determine_protocol_future = self.loop.create_future() |
| 865 |
self._aio_protocol.write(protocol.construct_state_query()) |
| 866 |
try: |
| 867 |
async with asyncio_timeout(self.timeout): |
| 868 |
await self._determine_protocol_future |
| 869 |
except asyncio.TimeoutError: |
| 870 |
self._async_close() |
| 871 |
continue |
| 872 |
else: |
| 873 |
return |
| 874 |
self.set_unavailable("Cannot determine protocol") |
| 875 |
raise DeviceUnavailableException(f"{self.ipaddr}: Cannot determine protocol") |