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

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

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

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

13 14 15 16 17 18 19 20 21 22 23 24 25 26
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
27
def write(channel, data):
28 29
    if channel == 'ser':
        l = ser.write(data)
30
        f.write("Data sent to serial: " + str(data) + "\n")
31 32 33 34 35 36 37 38 39
    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
40
    l = str.encode(l)
Sebastian Renner committed
41
    f.write("Trying to read " + str(l) + "bytes from " + channel + "\n")
42 43 44 45 46 47
    (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
48
    write(channel, str.encode(data))
49 50 51 52 53

def main():
    #flash()
    while(1):
        action = read('std', 1)
54 55 56 57
        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)
58

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

62 63 64 65 66 67 68 69
        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))
70 71 72
                
if __name__ == "__main__":
    sys.exit(main())