Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import serial
- import time
- import itertools
- import operator
- from binascii import hexlify
- NACK = b'\x1f'
- ACK = b'\x79'
- def hex_spaced(bin_str):
- return " ".join(hex(b) for b in bin_str)
- def select_UART(ser):
- ser.write(b"\x7f") # Select UART
- ack = ser.read() # read one byte
- print("(N)ACK: ",ack)
- if ack == ACK:
- print("UART selection ACKed")
- else:
- raise RuntimeError("UART select failed")
- def send_command(ser, cmd_bin, expected=None):
- #line = ser.readline() # read a '\n' terminated line
- xor_byte = bytes(itertools.accumulate(cmd_bin, operator.xor))[-1:]
- print("XOR checksum:", xor_byte)
- ser.write(cmd_bin + xor_byte) # Get
- time.sleep(0.1)
- ack = ser.read(1)[0]
- if (ack == ord(ACK)):
- print("Command Acked")
- elif (ack == ord(NACK)):
- print("Command Nacked")
- raise RuntimeError("Command failed")
- else:
- print("dafuq!", ack)
- raise RuntimeError("Command failed")
- if expected is None:
- s = ser.read(ser.in_waiting) # read available bytes
- else:
- s = ser.read(expected-1)
- return s
- def send_command_print(ser, cmd_bin, expected=None):
- s = send_command(ser, cmd_bin, expected)
- print("Result: %d bytes, %s" % (len(s), hex_spaced(s)))
- with serial.Serial('/dev/ttyACM0', 38400, timeout=None) as ser:
- select_UART(ser)
- try:
- s = send_command_print(ser, b"\x00\xff", 15)
- s = send_command_print(ser, b"\x01\xfe")
- except KeyboardInterrupt:
- print("interrupted")
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement