1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """Custom PulseIn Class to read PWM signals"""
18 # The message queues live outside of python space, and must be formally cleaned!
20 """In case the program is cancelled or quit, we need to clean up the PulseIn
21 helper process and also the message queue, this is called at exit to do so"""
23 print("Cleaning up message queues", queues)
24 print("Cleaning up processes", procs)
31 atexit.register(final)
34 # pylint: disable=c-extension-no-member
36 """PulseIn Class to read PWM signals"""
38 def __init__(self, pin, maxlen=2, idle_state=False):
39 """Create a PulseIn object associated with the given pin.
40 The object acts as a read-only sequence of pulse lengths with
41 a given max length. When it is active, new pulse lengths are
42 added to the end of the list. When there is no more room
43 (len() == maxlen) the oldest pulse length is removed to make room."""
46 self._idle_state = idle_state
47 self._queue_key = random.randint(1, 9999)
49 self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
51 print("Message Queue Key: ", self._mq.key)
52 queues.append(self._mq)
53 except sysv_ipc.ExistentialError:
55 "Message queue creation failed"
56 ) from sysv_ipc.ExistentialError
58 # Check if OS is 64-bit
59 if struct.calcsize("P") * 8 == 64: # pylint: disable=no-member
60 libgpiod_filename = "libgpiod_pulsein64"
62 libgpiod_filename = "libgpiod_pulsein"
64 dir_path = os.path.dirname(os.path.realpath(__file__))
66 dir_path + "/" + libgpiod_filename,
74 cmd.append("gpiochip0")
79 self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
80 procs.append(self._process)
82 # wait for it to start up
84 print("Waiting for startup success message from subprocess")
85 message = self._wait_receive_msg(timeout=0.25)
86 if message[0] != b"!":
87 raise RuntimeError("Could not establish message queue with subprocess")
90 # pylint: disable=redefined-builtin
91 def _wait_receive_msg(self, timeout=0, type=2):
92 """Internal helper that will wait for new messages of a given type,
93 and throw an exception on timeout"""
95 stamp = time.monotonic()
96 while (time.monotonic() - stamp) < timeout:
98 message = self._mq.receive(block=False, type=type)
100 except sysv_ipc.BusyError:
101 time.sleep(0.001) # wait a bit then retry!
104 "Timed out waiting for PulseIn message. Make sure libgpiod is installed."
106 message = self._mq.receive(block=True, type=type)
109 # pylint: enable=redefined-builtin
112 """Deinitialises the PulseIn and releases any hardware and software
113 resources for reuse."""
114 # Clean up after ourselves
115 self._process.terminate()
116 procs.remove(self._process)
118 queues.remove(self._mq)
121 """No-op used by Context Managers."""
124 def __exit__(self, exc_type, exc_value, tb):
125 """Automatically deinitializes the hardware when exiting a context."""
128 def resume(self, trigger_duration=0):
129 """Resumes pulse capture after an optional trigger pulse."""
130 if trigger_duration != 0:
131 self._mq.send("t%d" % trigger_duration, True, type=1)
133 self._mq.send("r", True, type=1)
137 """Pause pulse capture"""
138 self._mq.send("p", True, type=1)
143 """True when pulse capture is paused as a result of pause() or
144 an error during capture such as a signal that is too fast."""
149 """The maximum length of the PulseIn. When len() is equal to maxlen,
150 it is unclear which pulses are active and which are idle."""
154 """Clears all captured pulses"""
155 self._mq.send("c", True, type=1)
158 """Removes and returns the oldest read pulse."""
159 self._mq.send("^", True, type=1)
160 message = self._wait_receive_msg()
161 reply = int(message[0].decode("utf-8"))
164 raise IndexError("pop from empty list")
168 """Returns the current pulse length"""
169 self._mq.send("l", True, type=1)
170 message = self._wait_receive_msg()
171 return int(message[0].decode("utf-8"))
173 # pylint: disable=redefined-builtin
174 def __getitem__(self, index, type=None):
175 """Returns the value at the given index or values in slice."""
176 self._mq.send("i%d" % index, True, type=1)
177 message = self._wait_receive_msg()
178 ret = int(message[0].decode("utf-8"))
180 raise IndexError("list index out of range")
183 # pylint: enable=redefined-builtin