51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
from micropython import const
|
|
from .pin import Pin
|
|
|
|
_PINSTATE_PRESSED = const(0)
|
|
_PINSTATE_UNPRESSED = const(1)
|
|
|
|
|
|
class PinState:
|
|
_state: int
|
|
|
|
def __init__(self, pin_value: int) -> None:
|
|
self._state = _PINSTATE_PRESSED if pin_value == _PINSTATE_PRESSED else _PINSTATE_UNPRESSED
|
|
|
|
def __eq__(self, obj):
|
|
return isinstance(obj, PinState) and self._state == obj._state
|
|
|
|
def __ne__(self, obj):
|
|
return not isinstance(obj, PinState) or self._state != obj._state
|
|
|
|
def is_pressed(self) -> bool:
|
|
return self._state == _PINSTATE_PRESSED
|
|
|
|
|
|
class PinManager:
|
|
|
|
_pins: list[Pin] = []
|
|
_current_state: list[PinState] = []
|
|
_previous_state: list[PinState] = []
|
|
|
|
def __init__(self, pins: list[Pin]) -> None:
|
|
self._pins = pins
|
|
self.step()
|
|
self.step()
|
|
|
|
def _get_next_state(self) -> list[PinState]:
|
|
return [PinState(pin.get_value()) for pin in self._pins]
|
|
|
|
def step(self) -> None:
|
|
self._previous_state = self._current_state
|
|
self._current_state = self._get_next_state()
|
|
|
|
def get_state_delta(self) -> list[PinState]:
|
|
"""Compares the current state with the previous and returns a list of either PinState or None depending on if the state changed or not"""
|
|
delta = []
|
|
for i in range(len(self._pins)):
|
|
previous_state = self._previous_state[i]
|
|
current_state = self._current_state[i]
|
|
delta.append(current_state if current_state !=
|
|
previous_state else None)
|
|
return delta
|