|
| 1 | +"""Aggregate Light controller with fluent interface.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import re |
| 7 | +from contextlib import contextmanager |
| 8 | +from dataclasses import dataclass, field |
| 9 | +from typing import Pattern |
| 10 | + |
| 11 | +from busylight_core import Light, LightUnavailableError, NoLightsFoundError |
| 12 | +from loguru import logger |
| 13 | + |
| 14 | +from .effects import Effects |
| 15 | +from .speed import Speed |
| 16 | + |
| 17 | + |
| 18 | +@dataclass |
| 19 | +class LightSelection: |
| 20 | + """A selection of lights that can have operations applied to them.""" |
| 21 | + |
| 22 | + lights: list[Light] = field(default_factory=list) |
| 23 | + |
| 24 | + def __len__(self) -> int: |
| 25 | + return len(self.lights) |
| 26 | + |
| 27 | + def __bool__(self) -> bool: |
| 28 | + return bool(self.lights) |
| 29 | + |
| 30 | + def __iter__(self): |
| 31 | + return iter(self.lights) |
| 32 | + |
| 33 | + def turn_on(self, color: tuple[int, int, int]) -> LightSelection: |
| 34 | + """Turn on selected lights.""" |
| 35 | + |
| 36 | + for light in self.lights: |
| 37 | + try: |
| 38 | + light.on(color) |
| 39 | + except LightUnavailableError as error: |
| 40 | + logger.debug(f"Light unavailable during turn_on: {error}") |
| 41 | + |
| 42 | + return self |
| 43 | + |
| 44 | + def turn_off(self) -> LightSelection: |
| 45 | + """Turn off selected lights.""" |
| 46 | + for light in self.lights: |
| 47 | + try: |
| 48 | + light.off() |
| 49 | + except LightUnavailableError as error: |
| 50 | + logger.debug(f"Light unavailable during turn_off: {error}") |
| 51 | + return self |
| 52 | + |
| 53 | + def blink( |
| 54 | + self, |
| 55 | + color: tuple[int, int, int], |
| 56 | + count: int = 0, |
| 57 | + speed: str = "slow", |
| 58 | + ) -> LightSelection: |
| 59 | + """Apply blink effect to selected lights.""" |
| 60 | + try: |
| 61 | + speed_obj = Speed(speed) |
| 62 | + except ValueError: |
| 63 | + speed_obj = Speed.slow |
| 64 | + |
| 65 | + effect = Effects.for_name("blink")(color, count=count) |
| 66 | + return self.apply_effect(effect, interval=speed_obj.duty_cycle) |
| 67 | + |
| 68 | + def apply_effect( |
| 69 | + self, |
| 70 | + effect: Effects, |
| 71 | + duration: float | None = None, |
| 72 | + interval: float | None = None, |
| 73 | + ) -> LightSelection: |
| 74 | + """Apply a custom effect to selected lights.""" |
| 75 | + actual_interval = interval if interval is not None else effect.default_interval |
| 76 | + |
| 77 | + for light in self.lights: |
| 78 | + light.cancel_tasks() |
| 79 | + |
| 80 | + async def effect_task(target_light=light): |
| 81 | + return await effect.execute(target_light, actual_interval) |
| 82 | + |
| 83 | + task = light.add_task( |
| 84 | + name=effect.name.lower(), |
| 85 | + func=effect_task, |
| 86 | + priority=effect.priority, |
| 87 | + replace=True, |
| 88 | + ) |
| 89 | + |
| 90 | + if duration: |
| 91 | + asyncio.create_task(asyncio.wait_for(task, timeout=duration)) |
| 92 | + |
| 93 | + return self |
| 94 | + |
| 95 | + |
| 96 | +class LightController: |
| 97 | + """Light controller with fluent interface.""" |
| 98 | + |
| 99 | + def __init__(self, light_class: type = None) -> None: |
| 100 | + self.light_class = light_class or Light |
| 101 | + self._lights: set[Light] = set() |
| 102 | + |
| 103 | + @property |
| 104 | + def lights(self) -> list[Light]: |
| 105 | + """All managed lights, sorted by name.""" |
| 106 | + try: |
| 107 | + if found := self.light_class.all_lights(exclusive=True, reset=False): |
| 108 | + self._lights.update(found) |
| 109 | + except Exception as error: |
| 110 | + logger.warning(f"Failed to get lights: {error}") |
| 111 | + return sorted(self._lights) |
| 112 | + |
| 113 | + def __enter__(self) -> LightController: |
| 114 | + return self |
| 115 | + |
| 116 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 117 | + self.cleanup() |
| 118 | + |
| 119 | + async def __aenter__(self): |
| 120 | + return self.__enter__() |
| 121 | + |
| 122 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 123 | + return self.__exit__(exc_type, exc_val, exc_tb) |
| 124 | + |
| 125 | + def cleanup(self) -> None: |
| 126 | + """Turn off all lights and clean up.""" |
| 127 | + for light in self.lights: |
| 128 | + try: |
| 129 | + light.off() |
| 130 | + except Exception as error: |
| 131 | + logger.error(f"Error turning off light during cleanup: {error}") |
| 132 | + |
| 133 | + def release_lights(self) -> None: |
| 134 | + """Release all owned lights.""" |
| 135 | + for light in self._lights: |
| 136 | + try: |
| 137 | + light.release() |
| 138 | + except Exception as error: |
| 139 | + logger.warning(f"Failed to release light {light.name}: {error}") |
| 140 | + self._lights = set() |
| 141 | + |
| 142 | + # Fluent selection methods |
| 143 | + def all(self) -> LightSelection: |
| 144 | + """Select all lights.""" |
| 145 | + return LightSelection(self.lights) |
| 146 | + |
| 147 | + def first(self) -> LightSelection: |
| 148 | + """Select the first light.""" |
| 149 | + lights = self.lights |
| 150 | + return LightSelection(lights[:1] if lights else []) |
| 151 | + |
| 152 | + def by_index(self, *indices: int) -> LightSelection: |
| 153 | + """Select lights by index.""" |
| 154 | + lights = self.lights |
| 155 | + selected = [] |
| 156 | + for index in indices: |
| 157 | + try: |
| 158 | + selected.append(lights[index]) |
| 159 | + except IndexError: |
| 160 | + logger.warning(f"Light index {index} not found") |
| 161 | + return LightSelection(selected) |
| 162 | + |
| 163 | + def by_name(self, name: str, index: int = None) -> LightSelection: |
| 164 | + """Select lights by name, optionally by index for duplicates.""" |
| 165 | + |
| 166 | + matching = [light for light in self.lights if light.name == name] |
| 167 | + |
| 168 | + if not matching: |
| 169 | + logger.warning(f"No lights found with name '{name}'") |
| 170 | + return LightSelection([]) |
| 171 | + |
| 172 | + if index is None: |
| 173 | + return LightSelection(matching) |
| 174 | + |
| 175 | + try: |
| 176 | + return LightSelection([matching[index]]) |
| 177 | + except IndexError: |
| 178 | + logger.warning(f"Light '{name}' index {index} not found") |
| 179 | + return LightSelection([]) |
| 180 | + |
| 181 | + def by_pattern(self, pattern: str | Pattern) -> LightSelection: |
| 182 | + """Select lights matching a regex pattern.""" |
| 183 | + if isinstance(pattern, str): |
| 184 | + pattern = re.compile(pattern, re.IGNORECASE) |
| 185 | + |
| 186 | + matching = [light for light in self.lights if pattern.search(light.name)] |
| 187 | + return LightSelection(matching) |
| 188 | + |
| 189 | + def names(self) -> list[str]: |
| 190 | + """Get light names with duplicates numbered.""" |
| 191 | + lights = self.lights |
| 192 | + name_counts = {} |
| 193 | + display_names = [] |
| 194 | + |
| 195 | + # Count occurrences |
| 196 | + for light in lights: |
| 197 | + name_counts[light.name] = name_counts.get(light.name, 0) + 1 |
| 198 | + |
| 199 | + # Generate display names |
| 200 | + name_indices = {} |
| 201 | + for light in lights: |
| 202 | + name = light.name |
| 203 | + if name_counts[name] > 1: |
| 204 | + name_indices[name] = name_indices.get(name, 0) + 1 |
| 205 | + display_names.append(f"{name} #{name_indices[name]}") |
| 206 | + else: |
| 207 | + display_names.append(name) |
| 208 | + |
| 209 | + return display_names |
| 210 | + |
| 211 | + def __len__(self) -> int: |
| 212 | + return len(self.lights) |
| 213 | + |
| 214 | + def __bool__(self) -> bool: |
| 215 | + return bool(self.lights) |
0 commit comments