#!/usr/bin/env python3
import os, termios, time, select, sys

PORT = "/dev/ttyUSB1"
fd = os.open(PORT, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
a = termios.tcgetattr(fd)
a[0] = 0; a[1] = 0
a[2] = termios.CLOCAL | termios.CREAD | termios.CS8
a[3] = 0; a[4] = termios.B115200; a[5] = termios.B115200
a[6][termios.VMIN] = 0; a[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, a)

dur = float(sys.argv[1]) if len(sys.argv) > 1 else 10
out = bytearray()
end = time.time() + dur
while time.time() < end:
    r, _, _ = select.select([fd], [], [], 0.05)
    if r:
        try:
            out += os.read(fd, 4096)
        except OSError:
            pass
open(sys.argv[2] if len(sys.argv) > 2 else "/tmp/serial_cap.bin", "wb").write(out)
print("CAPTURE_BYTES=%d" % len(out))
print("HEAD=%r" % bytes(out[:80]))
