| 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): |
| 15 | #print('DECODE ', repr(data)) |
| 16 | out = [] |
| 17 | for packet in data.split(end): |
| 18 | pdata = b'' |
| 19 | while True: |
| 20 | eix = packet.find(esc) |
| 21 | if eix == -1: |
| 22 | pdata += packet |
| 23 | break |
| 24 | #print('ESC ', repr((pdata, packet, eix))) |
| 25 | pdata += packet[0 : eix] |
| 26 | ck = packet[eix+1] |
| 27 | #print('ESC... %o' % ck) |
| 28 | if ck == esc_esc[0]: pdata += esc |
| 29 | elif ck == esc_end[0]: pdata += end |
| 30 | else: raise ValueError('invalid SLIP escape') |
| 31 | packet = packet[eix+2 : ] |
| 32 | out.append(pdata) |
| 33 | #print('DECODED ', repr(out)) |
| 34 | return out |
| 35 | # -*- python -*- |
| 36 | |