middleware.py 1.92 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/env python3

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

Sebastian Renner committed
9 10
ser = serial.Serial('/dev/ttyUSB0', 115200)

11 12 13 14 15 16 17 18 19 20 21 22 23 24
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

Sebastian Renner committed
25
def write(channel, data):
26 27 28 29 30 31 32 33 34 35 36
    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)
Sebastian Renner committed
37
    l = str.encode(l)
38 39 40 41 42 43
    (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)
Sebastian Renner committed
44
    write(channel, str.encode(data))
45 46 47 48 49 50 51 52 53 54 55

def main():
    #flash()
    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':
Sebastian Renner committed
56
                write('ser', str.encode(action))
57 58

            elif action == 'C' or action == 'M' or action == 'A' or action == 'K' or action == 'S' or action == 'P':
Sebastian Renner committed
59
                write('ser', str.encode(action))
60 61 62 63 64 65 66
                data = obtain('ser')
                submit('std', action, data)
            else:
                raise Exception("no capiche aczione %s" % (action))
                
if __name__ == "__main__":
    sys.exit(main())