#!/usr/bin/env python3

from serial import Serial

port = Serial('/dev/buspirate', 115200, timeout=0.1)

try:
    # "you must now enter 0x00 at least 20 times to enter raw bitbang mode"
    count = 0
    done = False
    while count < 30 and not done:
        count += 1
        port.write(b'\x00')
        if port.read(5)[0:4] == b'BBIO':
            done = True
    if not done:
        raise RuntimeError()

    # Switch to I2C mode.
    port.write(b'\x02')
    if port.read(4) != b'I2C1':
        raise RuntimeError()

    # Start sniffer.
    port.write(b'\x0f')
    expecting_data = False
    while True:
        data = port.read(1)
        if data:
            if expecting_data:
                print('0x'+data.hex(), end='')
                expecting_data = False
            elif data in [b'[', b'+', b'-']:
                print(data.decode('ascii'), end='')
            elif data == b'\\':
                expecting_data = True
            elif data == b']':
                print(data.decode('ascii'))
            else:
                print()
                print('Unexpected data: 0x'+data.hex())
finally:
    # Exit sniffer.
    port.write(b'\x00')

    port.close()
