chiark / gitweb /
hippotit -> hippotat
[hippotat.git] / hippotat / slip.py
diff --git a/hippotat/slip.py b/hippotat/slip.py
new file mode 100644 (file)
index 0000000..4e84194
--- /dev/null
@@ -0,0 +1,36 @@
+# SLIP handling
+
+end = b'\300'
+esc = b'\333'
+esc_end = b'\334'
+esc_esc = b'\335'
+delimiter = end
+
+def encode(packet):
+  return (packet
+          .replace(esc, esc + esc_esc)
+          .replace(end, esc + esc_end))
+
+def decode(data):
+  print('DECODE ', repr(data))
+  out = []
+  for packet in data.split(end):
+    pdata = b''
+    while True:
+      eix = packet.find(esc)
+      if eix == -1:
+        pdata += packet
+        break
+      #print('ESC ', repr((pdata, packet, eix)))
+      pdata += packet[0 : eix]
+      ck = packet[eix+1]
+      #print('ESC... %o' % ck)
+      if   ck == esc_esc[0]: pdata += esc
+      elif ck == esc_end[0]: pdata += end
+      else: raise ValueError('invalid SLIP escape')
+      packet = packet[eix+2 : ]
+    out.append(pdata)
+  print('DECODED ', repr(out))
+  return out
+# -*- python -*-
+