#!/usr/bin/python3 -u

import os
import sys
import time
import struct
import serial
import subprocess

DBG='1'


ser = serial.Serial('/dev/ttyUSB0', 115200)

def flash():
        pipe = subprocess.PIPE
        p = subprocess.Popen(['JLinkExe', 'flash.jlink'], stdout=sys.stderr, stdin=pipe)
        stdout, stderr = p.communicate("")

def read(channel, l):
    if channel == 'ser':
        data = ser.read(l)
    elif channel == 'std':
        data = sys.stdin.buffer.read(l)
    else:
        raise Exception("read() complains: no sai channelino")
    if len(data) != l:
        raise Exception("could not read %d bytes of data (got %d)" % (l, len(data)))
    return data

def write(channel, data):
    if channel == 'ser':
        l = ser.write(data)
        if DBG:
            print("Data sent to serial: " + str(data) + "\n", file=sys.stderr)
    elif channel == 'std':
        l = sys.stdout.buffer.write(data)
    else:
        raise Exception("write() complains: no sai channelino")
    if len(data) != l:
        raise Exception("could not write %d bytes of data (put %d)" % (len(data), l))
            
def obtain(channel):
    l = read(channel, 4)
    (l, ) = struct.unpack("<I", l)
    if DBG:
        print("Trying to read %d bytes from %s\n" % (l, channel), file=sys.stderr)
    return read(channel, l)

def submit(channel, action, data):
    if channel == "std":
        h = struct.pack("<I", len(data))
    else:
        h = struct.pack("<BI", ord(action), len(data))
    write(channel, h)
    write(channel, data)
    time.sleep(0.1)

def main(argv):
    if DBG:
        print(argv[0], file=sys.stderr)
    script_dir = os.path.split(argv[0])[0]
    if len(script_dir ) > 0:
        os.chdir(script_dir)
    flash()
    print("Hello, World!")
    while(1):
        action = read('std', 1)
        if DBG:
            print("Read following action from stdin: %s\n" % action, file=sys.stderr)
        if action == b'c' or action == b'm' or action == b'a' or action == b'k' or action == b's' or action == b'p':
            data = obtain('std')
            submit('ser', action, data)

        elif action == b'e' or action == b'd':
            write('ser', action)

        elif action == b'C' or action == b'M' or action == b'A' or action == b'K' or action == b'S' or action == b'P':
            write('ser', action)
            data = obtain('ser')
            if DBG:
                print("Obtained following data from serial: %s\n" % data, file=sys.stderr)
            submit('std', action, data)
            if DBG:
                print("Submitted following data to stdout: %s\n" % data, file=sys.stderr)
        else:
            raise Exception("no capiche aczione %s" % (action))
                
if __name__ == "__main__":
    sys.exit(main(sys.argv))
