From a4c67cdb98c48a919215bb010f1542038d84770c Mon Sep 17 00:00:00 2001 From: Jose Tiago Macara Coutinho Date: Thu, 22 Aug 2024 08:12:15 +0200 Subject: [PATCH 1/2] Add hardware brightness events --- linuxpy/led.py | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/linuxpy/led.py b/linuxpy/led.py index 5b9707b..c37073e 100644 --- a/linuxpy/led.py +++ b/linuxpy/led.py @@ -62,6 +62,10 @@ def decode_triggers(text): return [i[1:-1] if i.startswith("[") else i for i in text.split()] +def decode_brightness(data: bytes) -> int: + return int.from_bytes(data, "little") + + def split_name(fname): if nb_colons := fname.count(":"): parts = fname.split(":") @@ -127,6 +131,17 @@ def trigger_enabled(self) -> bool: """Tells if the LED trigger is enabled""" return self.trigger != "none" + @property + def brightness_events_path(self): + return self.syspath / "brightness_hw_changed" + + def __iter__(self): + if not self.brightness_events_path.exists(): + raise ValueError("This LED does not support hardware events") + with self.brightness_events_path.open("rb", buffering=0) as fobj: + yield decode_brightness(fobj.read(4)) + fobj.seek(0) + class ULED(BaseDevice): """ @@ -142,10 +157,6 @@ def __init__(self, name: str, max_brightness: int = 1, **kwargs): self._brightness = None super().__init__(self.PATH, **kwargs) - @staticmethod - def decode(data: bytes) -> int: - return int.from_bytes(data, "little") - def _on_open(self): data = struct.pack("64si", self.name.encode(), self.max_brightness) self._fobj.write(data) @@ -165,14 +176,14 @@ def brightness(self) -> int: """Read new brightness. Blocks until brightness changes""" data = self.raw_read() if data is not None: - self._brightness = self.decode(data) + self._brightness = decode_brightness(data) return self._brightness def stream(self) -> Iterable[int]: """Infinite stream of brightness change events""" while True: data = self.read() - self._brightness = self.decode(data) + self._brightness = decode_brightness(data) yield self._brightness From a929493beace899397ea6a7aaa7863a6f251ac1a Mon Sep 17 00:00:00 2001 From: Jose Tiago Macara Coutinho Date: Thu, 22 Aug 2024 08:14:22 +0200 Subject: [PATCH 2/2] Add basic test --- tests/test_led.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/test_led.py b/tests/test_led.py index e64b2f1..29f21ae 100644 --- a/tests/test_led.py +++ b/tests/test_led.py @@ -148,6 +148,13 @@ def _(uled=uled, uled_colored=uled_colored, uled_simple=uled_simple, uled_single assert len(leds) >= 4 +@skip("uled not prepared", when=not ULED_PREPARED) +@test("led brightness events") +def _(uled=uled): + led = LED.from_name(uled.name) + assert not led.brightness_events_path.exists() + + @skip("uled not prepared", when=not ULED_PREPARED) @test("uled stream") def _(uled=uled):