middleware.py 2.39 KB
Newer Older
1
#!/usr/bin/python3 -u
2 3 4

import os
import sys
5
import time
6 7 8 9
import struct
import serial
from subprocess import Popen, PIPE, run

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

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

14 15 16 17 18 19 20
def flash():
        run("JLinkExe flash.jlink", shell=True, check=True)

def read(channel, l):
    if channel == 'ser':
        data = ser.read(l)
    elif channel == 'std':
21
        data = sys.stdin.buffer.read(l)
22 23
    else:
        raise Exception("read() complains: no sai channelino")
24 25
#    if channel == "std" and len(data) == 0:
#        sys.exit(0)
26 27 28 29
    if len(data) != l:
        raise Exception("could not read %d bytes of data (got %d)" % (l, len(data)))
    return data

Sebastian Renner committed
30
def write(channel, data):
31 32
    if channel == 'ser':
        l = ser.write(data)
33
        f.write("Data sent to serial: " + str(data) + "\n")
34
    elif channel == 'std':
35
        l = sys.stdout.buffer.write(data)
36 37 38 39 40 41 42 43
    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)
44
    f.write("Trying to read %d bytes from %s\n" % (l, channel))
45 46 47
    return read(channel, l)

def submit(channel, action, data):
48 49 50 51
    if channel == "std":
        h = struct.pack("<I", len(data))
    else:
        h = struct.pack("<BI", ord(action), len(data))
52
    write(channel, h)
53 54
    write(channel, data)
    time.sleep(0.1)
55 56 57

def main():
    #flash()
58
    print("Hello, World!")
59 60
    while(1):
        action = read('std', 1)
61 62
        f.write("Read following action from stdin: %s\n" % action)
        if action == b'c' or action == b'm' or action == b'a' or action == b'k' or action == b's' or action == b'p':
63 64
            data = obtain('std')
            submit('ser', action, data)
65

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

69 70
        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)
71
            data = obtain('ser')
72
            f.write("Obtained following data from serial: %s\n" % data)
73
            submit('std', action, data)
74
            f.write("Submitted following data to stdout: %s\n" % data)
75 76
        else:
            raise Exception("no capiche aczione %s" % (action))
77 78 79
                
if __name__ == "__main__":
    sys.exit(main())