Advertisement
Guest User

Untitled

a guest
Dec 14th, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import serial
  4. import time
  5. import itertools
  6. import operator
  7. import sys
  8.  
  9. from binascii import hexlify
  10.  
  11. NACK = b'\x1f'
  12. ACK = b'\x79'
  13.  
  14. def hex_spaced(bin_str):
  15.     return " ".join(hex(b) for b in bin_str)
  16.  
  17. def select_UART(ser):
  18.     ser.write(b"\x7f") # Select UART
  19.     ack = ser.read()          # read one byte
  20.     print("(N)ACK: ",ack)
  21.  
  22.     if ack == ACK:
  23.         print("UART selection ACKed")
  24.     else:
  25.         raise RuntimeError("UART select failed")
  26.  
  27. def send_command(ser, cmd_bin, expected=None, use_xor=True):
  28.     #line = ser.readline()   # read a '\n' terminated line
  29.     xor_byte = bytes(itertools.accumulate(cmd_bin, operator.xor))[-1:]
  30.     if use_xor:
  31.         print("XOR checksum:", xor_byte)
  32.         ser.write(cmd_bin + xor_byte) # Get
  33.     else:
  34.         ser.write(cmd_bin) # Get
  35.     #time.sleep(0.1)
  36.     ack = ser.read(1)[0]
  37.     if (ack == ord(ACK)):
  38.         print("Command Acked")
  39.     elif (ack == ord(NACK)):
  40.         print("Command Nacked")
  41.         raise RuntimeError("Command failed")
  42.     else:
  43.         print("dafuq!", ack)
  44.         raise RuntimeError("Command failed")
  45.  
  46.     if expected is None:
  47.         s = ser.read(ser.in_waiting)        # read available bytes
  48.     else:
  49.         s = ser.read(expected-1)
  50.  
  51.     return s
  52.    
  53. def send_command_print(ser, cmd_bin, expected=None, use_xor=True):
  54.     s = send_command(ser, cmd_bin, expected, use_xor)
  55.     print("Result: %d bytes, %s" % (len(s), hex_spaced(s)))
  56.  
  57. with serial.Serial('/dev/ttyUSB0', 115200, timeout=None) as ser:
  58.         if len(sys.argv) > 1 and sys.argv[1] == "select_uart":
  59.             print("Selecting UART")
  60.             select_UART(ser)
  61.  
  62.         try:
  63.             #print("Unplug BOOT0")
  64.             #sys.stdin.readline()
  65.             for i in range(1):
  66.                 s = send_command_print(ser, b"\x00\xff", expected=15, use_xor=False)
  67.             s = send_command_print(ser, b"\x02\xfd", use_xor=False)
  68.         except KeyboardInterrupt:
  69.             print("interrupted")
  70.             pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement