#!/usr/bin/python3 -u

import os
import sys
import struct
import serial
from subprocess import Popen, PIPE, run

f = open("subprocess.log", "w+")

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

def flash():
        run("JLinkExe flash.jlink", shell=True, check=True)

def read(channel, l):
    if channel == 'ser':
        data = ser.read(l)
    elif channel == 'std':
        data = sys.stdin.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)
        f.write("Data sent to serial: " + str(data) + "\n")
    elif channel == 'std':
        l = sys.stdout.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 = str.encode(l)
    f.write("Trying to read " + str(l) + "bytes from " + channel + "\n")
    (l, ) = struct.unpack("<I", l)
    return read(channel, l)

def submit(channel, action, data):
    h = struct.pack("<BI", ord(action), len(data))
    write(channel, h)
    write(channel, str.encode(data))

def main():
    #flash()
    while(1):
        action = read('std', 1)
        f.write("Read following action from stdin: " + action + "\n")
        if action == 'c' or action == 'm' or action == 'a' or action == 'k' or action == 's' or action == 'p':
            data = obtain('std')
            submit('ser', action, data)

        elif action == 'e' or action == 'd':
            write('ser', str.encode(action))

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