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
- import sys
- 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, use_xor=True):
- #line = ser.readline() # read a '\n' terminated line
- xor_byte = bytes(itertools.accumulate(cmd_bin, operator.xor))[-1:]
- if use_xor:
- print("XOR checksum:", xor_byte)
- ser.write(cmd_bin + xor_byte) # Get
- else:
- ser.write(cmd_bin) # 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, use_xor=True):
- s = send_command(ser, cmd_bin, expected, use_xor)
- print("Result: %d bytes, %s" % (len(s), hex_spaced(s)))
- with serial.Serial('/dev/ttyUSB0', 115200, timeout=None) as ser:
- if len(sys.argv) > 1 and sys.argv[1] == "select_uart":
- print("Selecting UART")
- select_UART(ser)
- try:
- #print("Unplug BOOT0")
- #sys.stdin.readline()
- for i in range(1):
- s = send_command_print(ser, b"\x00\xff", expected=15, use_xor=False)
- s = send_command_print(ser, b"\x02\xfd", use_xor=False)
- except KeyboardInterrupt:
- print("interrupted")
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement