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

import os
import sys
5
import time
6 7
import struct
import serial
8
import subprocess
9

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

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

14
def flash():
15 16 17
        pipe = subprocess.PIPE
        p = subprocess.Popen(['JLinkExe', 'flash.jlink'], stdout=sys.stderr, stdin=pipe)
        stdout, stderr = p.communicate("")
18 19 20 21 22

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

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

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

58 59 60 61 62 63
def main(argv):
    script_dir = os.path.split(argv[0])[0]
    if len(script_dir ) > 0:
        os.chdir(script_dir)
    f.write(os.getcwd())
    flash()
64
    print("Hello, World!")
65 66
    while(1):
        action = read('std', 1)
67 68
        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':
69 70
            data = obtain('std')
            submit('ser', action, data)
71

72 73
        elif action == b'e' or action == b'd':
            write('ser', action)
74

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