chiark / gitweb /
wip, and move PacketQueue
[hippotat.git] / hippotat / __init__.py
index 2b13003..c1ce085 100644 (file)
@@ -73,3 +73,31 @@ def queue_inbound(packet):
   ipif.transport.write(slip.encode(packet))
   ipif.transport.write(slip.delimiter)
 
+#---------- packet queue ----------
+
+class PacketQueue():
+  def __init__(self, max_queue_time):
+    self._max_queue_time = max_queue_time
+    self._pq = collections.deque() # packets
+
+  def append(self, packet):
+    self._pq.append((time.monotonic(), packet))
+
+  def nonempty(self):
+    while True:
+      try: (queuetime, packet) = self._pq[0]
+      except IndexError: return False
+
+      age = time.monotonic() - queuetime
+      if age > self.max_queue_time:
+        # strip old packets off the front
+        self._pq.popleft()
+        continue
+
+      return True
+
+  def popleft(self):
+    # caller must have checked nonempty
+    try: (dummy, packet) = self._pq[0]
+    except IndexError: return None
+    return packet