middleware.py 1.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#!/usr/bin/env python3

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

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, direction):
    if channel == 'ser':
        l = ser.write(data)
    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)
    print(l)
    (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, data)

def main():
    #flash()
    ser = serial.Serial('/dev/ttyUSB0', 115200)
    while(1):
        action = read('std', 1)
        if (action):
            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', action)

            elif action == 'C' or action == 'M' or action == 'A' or action == 'K' or action == 'S' or action == 'P':
                write('ser', action)
                data = obtain('ser')
                submit('std', action, data)
            else:
                raise Exception("no capiche aczione %s" % (action))
                
if __name__ == "__main__":
    sys.exit(main())