import os
import sys
import argparse
import serial
import struct
import time

SEND = b"\xAF"
DATA = b"\x1A"
DONE = b"\xFA"
ERR = b"\x1F"

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', dest='port', required=True, help='serial port to use')
parser.add_argument('-f', '--file', dest='file', required=True, help='file to recv')
args = parser.parse_args()

ser = serial.Serial(port=args.port, baudrate=230400, timeout=2)
ser.flushInput()
ser.flushOutput()

f = open(args.file, 'wb')

while True:
    ser.write(SEND)
    ser.flush()
    if ser.inWaiting() > 0:
        byte = ser.read(1)
        if byte == DATA:
            data = ser.read(4)
            if len(data) != 4:
                ser.write(ERR)
                print "bad length"
                break
            data_len = struct.unpack('<I', data)[0]
            data = ser.read(data_len)
            if len(data) != data_len:
                ser.write(ERR)
                print "bad data"
                break
            f.write(data)
            sys.stdout.write(".")
        elif byte == DONE:
            sys.stdout.write("\n")
            print "all data received"
            break
        elif byte == ERR:
            sys.stdout.write("\n")
            print "transfer failed"
            break
        else:
            ser.write(ERR)
            print "unknown packet type " + str(hex(ord(byte)))
            break

print "cleaning up"
f.close()
ser.close()

