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)
32 # pylint: disable=c-extension-no-member
34 """PulseIn Class to read PWM signals"""
36 def __init__(self, pin, maxlen=2, idle_state=False):
37 """Create a PulseIn object associated with the given pin.
38 The object acts as a read-only sequence of pulse lengths with
39 a given max length. When it is active, new pulse lengths are
40 added to the end of the list. When there is no more room
41 (len() == maxlen) the oldest pulse length is removed to make room."""
44 self._idle_state = idle_state
45 self._queue_key = random.randint(1, 9999)
47 self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
49 print("Message Queue Key: ", self._mq.key)
50 queues.append(self._mq)
51 except sysv_ipc.ExistentialError:
53 "Message queue creation failed"
54 ) from sysv_ipc.ExistentialError
56 # Check if OS is 64-bit
57 if struct.calcsize("P") * 8 == 64: # pylint: disable=no-member
58 libgpiod_filename = "libgpiod_pulsein64"
60 libgpiod_filename = "libgpiod_pulsein"
62 dir_path = os.path.dirname(os.path.realpath(__file__))
64 dir_path + "/" + libgpiod_filename,
72 cmd.append("gpiochip0")
77 self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
78 procs.append(self._process)
80 # wait for it to start up
82 print("Waiting for startup success message from subprocess")
83 message = self._wait_receive_msg(timeout=0.25)
84 if message[0] != b"!":
85 raise RuntimeError("Could not establish message queue with subprocess")
88 # pylint: disable=redefined-builtin
89 def _wait_receive_msg(self, timeout=0, type=2):
90 """Internal helper that will wait for new messages of a given type,
91 and throw an exception on timeout"""
93 stamp = time.monotonic()
94 while (time.monotonic() - stamp) < timeout:
96 message = self._mq.receive(block=False, type=type)
98 except sysv_ipc.BusyError:
99 time.sleep(0.001) # wait a bit then retry!
102 "Timed out waiting for PulseIn message. Make sure libgpiod is installed."
104 message = self._mq.receive(block=True, type=type)
107 # pylint: enable=redefined-builtin
110 """Deinitialises the PulseIn and releases any hardware and software
111 resources for reuse."""
112 # Clean up after ourselves
113 self._process.terminate()
114 procs.remove(self._process)
116 queues.remove(self._mq)
119 """No-op used by Context Managers."""
122 def __exit__(self, exc_type, exc_value, tb):
123 """Automatically deinitializes the hardware when exiting a context."""
126 def resume(self, trigger_duration=0):
127 """Resumes pulse capture after an optional trigger pulse."""
128 if trigger_duration != 0:
129 self._mq.send("t%d" % trigger_duration, True, type=1)
131 self._mq.send("r", True, type=1)
135 """Pause pulse capture"""
136 self._mq.send("p", True, type=1)
141 """True when pulse capture is paused as a result of pause() or
142 an error during capture such as a signal that is too fast."""
147 """The maximum length of the PulseIn. When len() is equal to maxlen,
148 it is unclear which pulses are active and which are idle."""
152 """Clears all captured pulses"""
153 self._mq.send("c", True, type=1)
156 """Removes and returns the oldest read pulse."""
157 self._mq.send("^", True, type=1)
158 message = self._wait_receive_msg()
159 reply = int(message[0].decode("utf-8"))
162 raise IndexError("pop from empty list")
166 """Returns the current pulse length"""
167 self._mq.send("l", True, type=1)
168 message = self._wait_receive_msg()
169 return int(message[0].decode("utf-8"))
171 # pylint: disable=redefined-builtin
172 def __getitem__(self, index, type=None):
173 """Returns the value at the given index or values in slice."""
174 self._mq.send("i%d" % index, True, type=1)
175 message = self._wait_receive_msg()
176 ret = int(message[0].decode("utf-8"))
178 raise IndexError("list index out of range")
181 # pylint: enable=redefined-builtin