15 # The message queues live outside of python space, and must be formally cleaned!
17 """In case the program is cancelled or quit, we need to clean up the PulseIn
18 helper process and also the message queue, this is called at exit to do so"""
20 print("Cleaning up message queues", queues)
21 print("Cleaning up processes", procs)
26 atexit.register(final)
29 def __init__(self, pin, maxlen=2, idle_state=False):
30 """Create a PulseIn object associated with the given pin.
31 The object acts as a read-only sequence of pulse lengths with
32 a given max length. When it is active, new pulse lengths are
33 added to the end of the list. When there is no more room
34 (len() == maxlen) the oldest pulse length is removed to make room."""
37 self._idle_state = idle_state
38 self._queue_key = random.randint(1, 9999)
40 self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
42 print("Message Queue Key: ", self._mq.key)
43 queues.append(self._mq)
44 except sysv_ipc.ExistentialError:
45 raise RuntimeError("Message queue creation failed")
47 cmd = ["/home/pi/libgpiod_pulsein/src/libgpiod_pulsein",
48 "--pulses", str(maxlen),
49 "--queue", str(self._mq.key)]
52 cmd.append("gpiochip0")
57 self._process = subprocess.Popen(cmd)
58 procs.append(self._process)
60 # wait for it to start up
62 print("Waiting for startup success message from subprocess")
63 message = self._wait_receive_msg()
64 if message[0] != b'!':
65 raise RuntimeError("Could not establish message queue with subprocess")
68 def _wait_receive_msg(self, timeout=0.25, type=2):
69 """Internal helper that will wait for new messages of a given type,
70 and throw an exception on timeout"""
71 stamp = time.monotonic()
72 while (time.monotonic() - stamp) < timeout:
74 message = self._mq.receive(block=False, type=2)
76 except sysv_ipc.BusyError:
77 time.sleep(0.001) # wait a bit then retry!
79 raise RuntimeError("Timed out waiting for PulseIn message")
82 """Deinitialises the PulseIn and releases any hardware and software
83 resources for reuse."""
84 # Clean up after ourselves
85 self._process.terminate()
86 procs.remove(self._process)
88 queues.remove(self._mq)
91 """No-op used by Context Managers."""
94 def __exit__(self, exc_type, exc_value, tb):
95 """Automatically deinitializes the hardware when exiting a context."""
98 def resume(self, trigger_duration=0):
99 """Resumes pulse capture after an optional trigger pulse."""
100 if trigger_duration != 0:
101 self._mq.send("t%d" % trigger_duration, True, type=1)
103 self._mq.send("r", True, type=1)
107 """Pause pulse capture"""
108 self._mq.send("p", True, type=1)
113 """True when pulse capture is paused as a result of pause() or
114 an error during capture such as a signal that is too fast."""
119 """The maximum length of the PulseIn. When len() is equal to maxlen,
120 it is unclear which pulses are active and which are idle."""
124 """Clears all captured pulses"""
125 self._mq.send("c", True, type=1)
128 """Removes and returns the oldest read pulse."""
129 self._mq.send("^", True, type=1)
130 message = self._wait_receive_msg()
131 reply = int(message[0].decode('utf-8'))
134 raise IndexError("pop from empty list")
138 """Returns the current pulse length"""
139 self._mq.send("l", True, type=1)
140 message = self._wait_receive_msg()
141 return int(message[0].decode('utf-8'))
143 def __getitem__(self, index, type=None):
144 """Returns the value at the given index or values in slice."""
145 self._mq.send("i%d" % index, True, type=1)
146 message = self._wait_receive_msg()
147 ret = int(message[0].decode('utf-8'))
149 raise IndexError("list index out of range")