| 1 | # SLIP handling |
| 2 | |
| 3 | end = b'\300' |
| 4 | esc = b'\333' |
| 5 | esc_end = b'\334' |
| 6 | esc_esc = b'\335' |
| 7 | delimiter = end |
| 8 | |
| 9 | def encode(packet): |
| 10 | return (packet |
| 11 | .replace(esc, esc + esc_esc) |
| 12 | .replace(end, esc + esc_end)) |
| 13 | |
| 14 | def decode(data, keep_tail=False): |
| 15 | #print('DECODE ', repr(data)) |
| 16 | out = [] |
| 17 | inp = data.split(end) |
| 18 | tail = [] |
| 19 | if keep_tail: |
| 20 | tail.append(inp.pop()) |
| 21 | for packet in inp: |
| 22 | pdata = b'' |
| 23 | while True: |
| 24 | eix = packet.find(esc) |
| 25 | if eix == -1: |
| 26 | pdata += packet |
| 27 | break |
| 28 | #print('ESC ', repr((pdata, packet, eix))) |
| 29 | pdata += packet[0 : eix] |
| 30 | ck = packet[eix+1] |
| 31 | #print('ESC... %o' % ck) |
| 32 | if ck == esc_esc[0]: pdata += esc |
| 33 | elif ck == esc_end[0]: pdata += end |
| 34 | else: raise ValueError('invalid SLIP escape 0%o %#x' % (ck, ck)) |
| 35 | packet = packet[eix+2 : ] |
| 36 | out.append(pdata) |
| 37 | #print('DECODED ', repr(out)) |
| 38 | out += tail |
| 39 | return out |
| 40 | # -*- python -*- |
| 41 | |