"""The box's GPIO, narrowed: the Voice HAT's button and LED, and nothing else on the chip. The Voice HAT wires the button to GPIO 23 (pressed pulls it low) and its LED to GPIO 25. """ from datetime import timedelta from gpiod import EdgeEvent, LineSettings # data types: no authority from gpiod.line import Bias, Direction, Edge, Value BUTTON, LED = 23, 25 CONFIG = { BUTTON: LineSettings(direction=Direction.INPUT, bias=Bias.PULL_UP, edge_detection=Edge.BOTH, debounce_period=timedelta(milliseconds=20)), LED: LineSettings(direction=Direction.OUTPUT, output_value=Value.INACTIVE), } def edge_of(event): """An edge event as (falling?, t_ns). >>> class Ev: event_type, timestamp_ns = EdgeEvent.Type.FALLING_EDGE, 10 >>> edge_of(Ev()) (True, 10) """ return (event.event_type == EdgeEvent.Type.FALLING_EDGE, event.timestamp_ns) class HatLines: """The button and LED lines, claimed from chip with request_lines (gpiod.request_lines). fileno() is readable when the button has new edges; read_edges() returns them, as (falling?, t_ns). set_led(on) lights the LED or not. >>> class Request: ... fd = 7 ... def set_value(self, line, value): print(line, value) >>> def request_lines(chip, consumer, config): ... print(chip, consumer, sorted(config)) ... return Request() >>> lines = HatLines(request_lines, "/dev/gpiochip0") /dev/gpiochip0 pdtv26-box [23, 25] >>> lines.fileno() 7 >>> lines.set_led(True) 25 Value.ACTIVE """ def __init__(self, request_lines, chip): self.__request = request_lines(chip, consumer="pdtv26-box", config=CONFIG) def fileno(self): return self.__request.fd def read_edges(self): return [edge_of(ev) for ev in self.__request.read_edge_events()] def set_led(self, on): self.__request.set_value(LED, Value.ACTIVE if on else Value.INACTIVE)