uart_test.py 983 Bytes
Newer Older
Marlene Böhmer's avatar
Marlene Böhmer committed
1 2 3 4
#!/usr/bin/python

import serial

Marlene Böhmer's avatar
Marlene Böhmer committed
5 6 7 8 9 10 11 12 13
MTU = 32
START_BYTE1 = 0xbc
START_BYTE2 = 0xcf
START = [START_BYTE1, START_BYTE2]

received_data = []

ser = serial.Serial("/dev/ttyS0", 115200)

Marlene Böhmer's avatar
Marlene Böhmer committed
14
while True:
Marlene Böhmer's avatar
Marlene Böhmer committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

    received_data = map(ord, list(ser.read_until(chr(START_BYTE1))))
    received_data += map(ord, list(ser.read(1)))
    if received_data[1] != START_BYTE2:
        print("ERROR START")
        continue

    received_data += map(ord, list(ser.read(2)))
    if received_data[3] > MTU:
        print("ERROR LENGTH")
        continue

    received_data += map(ord, list(ser.read(received_data[3]+2)))
    cksum0 = 0
    cksum1 = 0
    for c in received_data[2:-2]:
        cksum0 = (cksum0 + c) & 0xff
        cksum1 = (cksum1 + cksum0) & 0xff
    if cksum0 != received_data[-2] or cksum1 != received_data[-1]:
        print("ERROR CKSUM")

    print(" ".join("{:#04x}".format(n) for n in received_data))
Marlene Böhmer's avatar
Marlene Böhmer committed
37 38 39 40

    out_data = [1, 2]
    written = ser.write(bytearray(out_data))
    print(written)