Debian Codegraph @

bindings/python/examples/async_watch_line_value.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: GPL-2.0-or-later
3 # SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
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 # Assume a button connecting the pin to ground,
24 # so pull it up and provide some debounce.
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 # Other fds could be registered with the poll and be handled
39 # separately using the return value (fd, event) from poll():
40 poll.register(done_fd, select.POLLIN)
41 while True:
42 for fd, _event in poll.poll():
43 if fd == done_fd:
44 # perform any cleanup before exiting...
45 return
46 # handle any edge events
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 # run the async executor (select.poll) in a thread to demonstrate a graceful exit.
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 # Wait for two minutes, unless bg_thread exits earlier, then graceful exit.
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...")