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."""
43 if isinstance(pin.id, tuple):
44 self._pin = str(pin.id[1])
45 self._chip = "gpiochip{}".format(pin.id[0])
47 self._pin = str(pin.id)
48 self._chip = "gpiochip0"
51 self._idle_state = idle_state
52 self._queue_key = random.randint(1, 9999)
54 self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
56 print("Message Queue Key: ", self._mq.key)
57 queues.append(self._mq)
58 except sysv_ipc.ExistentialError:
60 "Message queue creation failed"
61 ) from sysv_ipc.ExistentialError
63 # Check if OS is 64-bit
64 libgpiod_filename = "libgpiod_pulsein"
65 dir_path = os.path.dirname(os.path.realpath(__file__))
67 dir_path + "/" + libgpiod_filename,
75 cmd.append(self._chip)
80 self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
81 procs.append(self._process)
83 # wait for it to start up
85 print("Waiting for startup success message from subprocess")
86 message = self._wait_receive_msg(timeout=0.25)
87 if message[0] != b"!":
88 raise RuntimeError("Could not establish message queue with subprocess")
91 # pylint: disable=redefined-builtin
92 def _wait_receive_msg(self, timeout=0, type=2):
93 """Internal helper that will wait for new messages of a given type,
94 and throw an exception on timeout"""
96 stamp = time.monotonic()
97 while (time.monotonic() - stamp) < timeout:
99 message = self._mq.receive(block=False, type=type)
101 except sysv_ipc.BusyError:
102 time.sleep(0.001) # wait a bit then retry!
105 "Timed out waiting for PulseIn message. Make sure libgpiod is installed."
107 message = self._mq.receive(block=True, type=type)
110 # pylint: enable=redefined-builtin
113 """Deinitialises the PulseIn and releases any hardware and software
114 resources for reuse."""
115 # Clean up after ourselves
116 self._process.terminate()
117 procs.remove(self._process)
119 queues.remove(self._mq)
122 """No-op used by Context Managers."""
125 def __exit__(self, exc_type, exc_value, tb):
126 """Automatically deinitializes the hardware when exiting a context."""
129 def resume(self, trigger_duration=0):
130 """Resumes pulse capture after an optional trigger pulse."""
131 if trigger_duration != 0:
132 self._mq.send("t%d" % trigger_duration, True, type=1)
134 self._mq.send("r", True, type=1)
138 """Pause pulse capture"""
139 self._mq.send("p", True, type=1)
144 """True when pulse capture is paused as a result of pause() or
145 an error during capture such as a signal that is too fast."""
150 """The maximum length of the PulseIn. When len() is equal to maxlen,
151 it is unclear which pulses are active and which are idle."""
155 """Clears all captured pulses"""
156 self._mq.send("c", True, type=1)
159 """Removes and returns the oldest read pulse."""
160 self._mq.send("^", True, type=1)
161 message = self._wait_receive_msg()
162 reply = int(message[0].decode("utf-8"))
165 raise IndexError("pop from empty list")
169 """Returns the current pulse length"""
170 self._mq.send("l", True, type=1)
171 message = self._wait_receive_msg()
172 return int(message[0].decode("utf-8"))
174 # pylint: disable=redefined-builtin
175 def __getitem__(self, index, type=None):
176 """Returns the value at the given index or values in slice."""
177 self._mq.send("i%d" % index, True, type=1)
178 message = self._wait_receive_msg()
179 ret = int(message[0].decode("utf-8"))
181 raise IndexError("list index out of range")
184 # pylint: enable=redefined-builtin