1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """Custom PulseIn Class to read PWM signals"""
17 # The message queues live outside of python space, and must be formally cleaned!
19 """In case the program is cancelled or quit, we need to clean up the PulseIn
20 helper process and also the message queue, this is called at exit to do so"""
22 print("Cleaning up message queues", queues)
23 print("Cleaning up processes", procs)
30 atexit.register(final)
33 # pylint: disable=c-extension-no-member
35 """PulseIn Class to read PWM signals"""
37 def __init__(self, pin, maxlen=2, idle_state=False):
38 """Create a PulseIn object associated with the given pin.
39 The object acts as a read-only sequence of pulse lengths with
40 a given max length. When it is active, new pulse lengths are
41 added to the end of the list. When there is no more room
42 (len() == maxlen) the oldest pulse length is removed to make room."""
44 if isinstance(pin.id, tuple):
45 self._pin = str(pin.id[1])
46 self._chip = "gpiochip{}".format(pin.id[0])
48 self._pin = str(pin.id)
49 self._chip = "gpiochip0"
52 self._idle_state = idle_state
53 self._queue_key = random.randint(1, 9999)
55 self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
57 print("Message Queue Key: ", self._mq.key)
58 queues.append(self._mq)
59 except sysv_ipc.ExistentialError:
61 "Message queue creation failed"
62 ) from sysv_ipc.ExistentialError
64 # Check if OS is 64-bit
65 libgpiod_filename = "libgpiod_pulsein"
66 dir_path = os.path.dirname(os.path.realpath(__file__))
68 dir_path + "/" + libgpiod_filename,
76 cmd.append(self._chip)
81 self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
82 procs.append(self._process)
84 # wait for it to start up
86 print("Waiting for startup success message from subprocess")
87 message = self._wait_receive_msg(timeout=0.25)
88 if message[0] != b"!":
89 raise RuntimeError("Could not establish message queue with subprocess")
92 # pylint: disable=redefined-builtin
93 def _wait_receive_msg(self, timeout=0, type=2):
94 """Internal helper that will wait for new messages of a given type,
95 and throw an exception on timeout"""
97 stamp = time.monotonic()
98 while (time.monotonic() - stamp) < timeout:
100 message = self._mq.receive(block=False, type=type)
102 except sysv_ipc.BusyError:
103 time.sleep(0.001) # wait a bit then retry!
106 "Timed out waiting for PulseIn message. Make sure libgpiod is installed."
108 message = self._mq.receive(block=True, type=type)
111 # pylint: enable=redefined-builtin
114 """Deinitialises the PulseIn and releases any hardware and software
115 resources for reuse."""
116 # Clean up after ourselves
117 self._process.terminate()
118 procs.remove(self._process)
120 queues.remove(self._mq)
123 """No-op used by Context Managers."""
126 def __exit__(self, exc_type, exc_value, tb):
127 """Automatically deinitializes the hardware when exiting a context."""
130 def resume(self, trigger_duration=0):
131 """Resumes pulse capture after an optional trigger pulse."""
132 if trigger_duration != 0:
133 self._mq.send("t%d" % trigger_duration, True, type=1)
135 self._mq.send("r", True, type=1)
139 """Pause pulse capture"""
140 self._mq.send("p", True, type=1)
145 """True when pulse capture is paused as a result of pause() or
146 an error during capture such as a signal that is too fast."""
151 """The maximum length of the PulseIn. When len() is equal to maxlen,
152 it is unclear which pulses are active and which are idle."""
156 """Clears all captured pulses"""
157 self._mq.send("c", True, type=1)
160 """Removes and returns the oldest read pulse."""
161 self._mq.send("^", True, type=1)
162 message = self._wait_receive_msg()
163 reply = int(message[0].decode("utf-8"))
166 raise IndexError("pop from empty list")
170 """Returns the current pulse length"""
171 self._mq.send("l", True, type=1)
172 message = self._wait_receive_msg()
173 return int(message[0].decode("utf-8"))
175 # pylint: disable=redefined-builtin
176 def __getitem__(self, index, type=None):
177 """Returns the value at the given index or values in slice."""
178 self._mq.send("i%d" % index, True, type=1)
179 message = self._wait_receive_msg()
180 ret = int(message[0].decode("utf-8"))
182 raise IndexError("list index out of range")
185 # pylint: enable=redefined-builtin