1 """Custom PulseIn Class to read PWM signals"""
13 # The message queues live outside of python space, and must be formally cleaned!
15 """In case the program is cancelled or quit, we need to clean up the PulseIn
16 helper process and also the message queue, this is called at exit to do so"""
18 print("Cleaning up message queues", queues)
19 print("Cleaning up processes", procs)
26 atexit.register(final)
28 # pylint: disable=c-extension-no-member
30 """PulseIn Class to read PWM signals"""
32 def __init__(self, pin, maxlen=2, idle_state=False):
33 """Create a PulseIn object associated with the given pin.
34 The object acts as a read-only sequence of pulse lengths with
35 a given max length. When it is active, new pulse lengths are
36 added to the end of the list. When there is no more room
37 (len() == maxlen) the oldest pulse length is removed to make room."""
40 self._idle_state = idle_state
41 self._queue_key = random.randint(1, 9999)
43 self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
45 print("Message Queue Key: ", self._mq.key)
46 queues.append(self._mq)
47 except sysv_ipc.ExistentialError:
48 raise RuntimeError("Message queue creation failed")
50 dir_path = os.path.dirname(os.path.realpath(__file__))
52 dir_path + "/libgpiod_pulsein",
60 cmd.append("gpiochip0")
65 self._process = subprocess.Popen(cmd)
66 procs.append(self._process)
68 # wait for it to start up
70 print("Waiting for startup success message from subprocess")
71 message = self._wait_receive_msg()
72 if message[0] != b"!":
73 raise RuntimeError("Could not establish message queue with subprocess")
76 # pylint: disable=redefined-builtin
77 def _wait_receive_msg(self, timeout=0.25, type=2):
78 """Internal helper that will wait for new messages of a given type,
79 and throw an exception on timeout"""
80 stamp = time.monotonic()
81 while (time.monotonic() - stamp) < timeout:
83 message = self._mq.receive(block=False, type=type)
85 except sysv_ipc.BusyError:
86 time.sleep(0.001) # wait a bit then retry!
88 raise RuntimeError("Timed out waiting for PulseIn message")
90 # pylint: enable=redefined-builtin
93 """Deinitialises the PulseIn and releases any hardware and software
94 resources for reuse."""
95 # Clean up after ourselves
96 self._process.terminate()
97 procs.remove(self._process)
99 queues.remove(self._mq)
102 """No-op used by Context Managers."""
105 def __exit__(self, exc_type, exc_value, tb):
106 """Automatically deinitializes the hardware when exiting a context."""
109 def resume(self, trigger_duration=0):
110 """Resumes pulse capture after an optional trigger pulse."""
111 if trigger_duration != 0:
112 self._mq.send("t%d" % trigger_duration, True, type=1)
114 self._mq.send("r", True, type=1)
118 """Pause pulse capture"""
119 self._mq.send("p", True, type=1)
124 """True when pulse capture is paused as a result of pause() or
125 an error during capture such as a signal that is too fast."""
130 """The maximum length of the PulseIn. When len() is equal to maxlen,
131 it is unclear which pulses are active and which are idle."""
135 """Clears all captured pulses"""
136 self._mq.send("c", True, type=1)
139 """Removes and returns the oldest read pulse."""
140 self._mq.send("^", True, type=1)
141 message = self._wait_receive_msg()
142 reply = int(message[0].decode("utf-8"))
145 raise IndexError("pop from empty list")
149 """Returns the current pulse length"""
150 self._mq.send("l", True, type=1)
151 message = self._wait_receive_msg()
152 return int(message[0].decode("utf-8"))
154 # pylint: disable=redefined-builtin
155 def __getitem__(self, index, type=None):
156 """Returns the value at the given index or values in slice."""
157 self._mq.send("i%d" % index, True, type=1)
158 message = self._wait_receive_msg()
159 ret = int(message[0].decode("utf-8"))
161 raise IndexError("list index out of range")
164 # pylint: enable=redefined-builtin