#!/usr/bin/env python3

import argparse
import asyncio
import serial_asyncio
import sys
import time
import threading

parser = argparse.ArgumentParser()
parser.add_argument("input", help="input filename")
parser.add_argument("--port", help="serial port to interface with")
parser.add_argument("--start",
                    help="auto start the clock",
                    const=True,
                    type=bool, nargs='?', default=False
                    )

args = parser.parse_args()

try:
    in_file = open(args.input, "rb")

except IOError:
    print("Could not open file")
    in_file.close()
    sys.exit(2)

class SerialHandler(asyncio.Protocol):
    def connection_made(self, transport):
        print('connection made')
        self.transport = transport
        self.buf = bytes()
        self.init_done = False

        # clear any incoming data
        transport.serial.flushInput()

        transport.serial.write(b'1')
        time.sleep(.1)
        transport.serial.write(b'5')
        time.sleep(.1)
        transport.serial.write(b'6')
        time.sleep(.1)

        content = in_file.read()
        length = len(content)
        written = 0

        print("file size " + str(length))

        transport.serial.write(b'l')

        while (length - written > 0):
            written += transport.serial.write(content[length - (length - written):])

        print("wrote {} bytes of rom".format(written))

        if args.start:
            transport.serial.write(b'4')
            time.sleep(.1)
            transport.serial.write(b'0')
    
    def connection_lost(self, exc):
        pass

    def data_received(self, data):
        self.buf += data

        if b'\r\n' in self.buf:
            lines = self.buf.split(b'\r\n')

            self.buf = lines[-1]

            for line in lines[:-1]:
                s = line.decode('utf-8')

                print(s)

loop = asyncio.get_event_loop()

try:
    handler = SerialHandler
    coro = serial_asyncio.create_serial_connection(loop, handler, args.port, baudrate=115200)
    loop.run_until_complete(coro)
except Exception as E:
    print(E)
    print('failed to open serial port')

except Exception as E:
    print(E)
    print('failed to open port')
    port.close()

    sys.exit(1)

loop.run_forever()
