Skip to content

Commit

Permalink
Merge pull request #34 from tiagocoutinho/led
Browse files Browse the repository at this point in the history
Led brightness hardware events
  • Loading branch information
tiagocoutinho authored Aug 22, 2024
2 parents a0ff323 + a929493 commit 71af39d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
23 changes: 17 additions & 6 deletions linuxpy/led.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(":")
Expand Down Expand Up @@ -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):
"""
Expand All @@ -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)
Expand All @@ -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


Expand Down
7 changes: 7 additions & 0 deletions tests/test_led.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 71af39d

Please sign in to comment.