import os
import sys
import argparse
import serial
import struct

CHUNK_SIZE = 1024
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 send')
args = parser.parse_args()

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

app_size = os.path.getsize(args.file)
print "file size: " + str(app_size)
written = 0

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

while True:
    while ser.inWaiting() == 0:
        pass

    byte = ser.read(1)
    if byte == SEND:
        if written >= app_size:
            print "sending DONE byte"
            ser.write(DONE)
            break
        else:
            ser.write(DATA)
            data = f.read(CHUNK_SIZE)
            data_len = len(data)
            size = struct.pack('<I', data_len & 0xFFFFFFFF)
            #ser.write(chr(data_len & 0x000000FF))
            #ser.write(chr((data_len & 0x0000FF00) >> 8))
            #ser.write(chr((data_len & 0x00FF0000) >> 16))
            #ser.write(chr((data_len & 0xFF000000) >> 24))
            ser.write(size)
            ser.write(data)
            written += data_len
            print "sent " + str(written) + "/" + str(app_size) + " bytes"
    elif byte == ERR:
        print "error transferring file"
        sys.exit(0)
    else:
        print "received unknown byte"
        sys.exit(0)

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

