| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
"""Minimal example of asynchronously watching for edges on a single line.""" |
| 6 |
|
| 7 |
import gpiod |
| 8 |
import select |
| 9 |
|
| 10 |
from datetime import timedelta |
| 11 |
from gpiod.line import Bias, Edge |
| 12 |
|
| 13 |
|
| 14 |
def edge_type_str(event): |
| 15 |
if event.event_type is event.Type.RISING_EDGE: |
| 16 |
return "Rising" |
| 17 |
if event.event_type is event.Type.FALLING_EDGE: |
| 18 |
return "Falling" |
| 19 |
return "Unknown" |
| 20 |
|
| 21 |
|
| 22 |
def async_watch_line_value(chip_path, line_offset, done_fd): |
| 23 |
|
| 24 |
|
| 25 |
with gpiod.request_lines( |
| 26 |
chip_path, |
| 27 |
consumer="async-watch-line-value", |
| 28 |
config={ |
| 29 |
line_offset: gpiod.LineSettings( |
| 30 |
edge_detection=Edge.BOTH, |
| 31 |
bias=Bias.PULL_UP, |
| 32 |
debounce_period=timedelta(milliseconds=10), |
| 33 |
) |
| 34 |
}, |
| 35 |
) as request: |
| 36 |
poll = select.poll() |
| 37 |
poll.register(request.fd, select.POLLIN) |
| 38 |
|
| 39 |
|
| 40 |
poll.register(done_fd, select.POLLIN) |
| 41 |
while True: |
| 42 |
for fd, _event in poll.poll(): |
| 43 |
if fd == done_fd: |
| 44 |
|
| 45 |
return |
| 46 |
|
| 47 |
for event in request.read_edge_events(): |
| 48 |
print( |
| 49 |
"offset: {} type: {:<7} event #{}".format( |
| 50 |
event.line_offset, edge_type_str(event), event.line_seqno |
| 51 |
) |
| 52 |
) |
| 53 |
|
| 54 |
|
| 55 |
if __name__ == "__main__": |
| 56 |
import os |
| 57 |
import threading |
| 58 |
|
| 59 |
|
| 60 |
done_fd = os.eventfd(0) |
| 61 |
|
| 62 |
def bg_thread(): |
| 63 |
try: |
| 64 |
async_watch_line_value("/dev/gpiochip0", 5, done_fd) |
| 65 |
except OSError as ex: |
| 66 |
print(ex, "\nCustomise the example configuration to suit your situation") |
| 67 |
print("background thread exiting...") |
| 68 |
|
| 69 |
t = threading.Thread(target=bg_thread) |
| 70 |
t.start() |
| 71 |
|
| 72 |
|
| 73 |
t.join(timeout=120) |
| 74 |
if t.is_alive(): |
| 75 |
os.eventfd_write(done_fd, 1) |
| 76 |
t.join() |
| 77 |
os.close(done_fd) |
| 78 |
print("main thread exiting...") |