Skip to content

Commit

Permalink
Added Button. (#452)
Browse files Browse the repository at this point in the history
  • Loading branch information
ATATC committed Dec 11, 2024
1 parent e7c6a13 commit 4c8572e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions leads_gpio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
if not _find_spec("serial"):
raise ImportError("Please install `pyserial` to run this module\n>>>pip install pyserial")

from leads_gpio.button import *
from leads_gpio.gps_receiver import *
from leads_gpio.led import *
from leads_gpio.led_group import *
45 changes: 45 additions & 0 deletions leads_gpio/button.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from typing import override as _override

from gpiozero import Button as _Button

from leads import Device as _Device, CallbackChain as _CallbackChain


class ButtonCallback(_CallbackChain):
def on_pressed(self) -> None: ...

def on_released(self) -> None: ...


class Button(_Device):
"""
Listen to a button.
Supports:
- Any binary button
"""

def __init__(self, pin: int, callback: ButtonCallback = ButtonCallback()) -> None:
super().__init__(pin)
self._button: _Button = _Button(pin)
self._callback: ButtonCallback = callback

def _when_activated(self) -> None:
self._callback.on_pressed()

def _when_deactivated(self) -> None:
self._callback.on_released()

@_override
def initialize(self, *parent_tags: str) -> None:
super().initialize(*parent_tags)
self._button.when_activated = self._when_activated
self._button.when_deactivated = self._when_deactivated

@_override
def read(self) -> bool:
return self._button.is_active

@_override
def write(self, callback: ButtonCallback) -> None:
callback.bind_chain(self._callback)
self._callback = callback

0 comments on commit 4c8572e

Please sign in to comment.