From 4c8572ee1cdf13c5e69145808de66bc4115a8bc5 Mon Sep 17 00:00:00 2001 From: ATATC Date: Wed, 11 Dec 2024 16:26:42 -0500 Subject: [PATCH] Added `Button`. (#452) --- leads_gpio/__init__.py | 1 + leads_gpio/button.py | 45 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 leads_gpio/button.py diff --git a/leads_gpio/__init__.py b/leads_gpio/__init__.py index 5d1c7606..725592c6 100644 --- a/leads_gpio/__init__.py +++ b/leads_gpio/__init__.py @@ -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 * diff --git a/leads_gpio/button.py b/leads_gpio/button.py new file mode 100644 index 00000000..083f5695 --- /dev/null +++ b/leads_gpio/button.py @@ -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