xmodem-linux / xmodem-send.py /
Yanik Cawidrone Creation
25cc758 2 months ago
1 contributor
87 lines | 1.801kb
#!/usr/bin/env python3
import serial
from xmodem import XMODEM
import argparse

# parse command-line arguments
parser = argparse.ArgumentParser(description="Send a file over XMODEM after sending ABWu")
parser.add_argument("-p", "--port", required=True, help="Serial port, e.g. /dev/ttyACM0")
parser.add_argument("-f", "--file", required=True, help="File to send")
args = parser.parse_args()

PORT = args.port
FILE = args.file
BAUD = 115200

def getc(size, timeout=1):
  return ser.read(size) or None

def putc(data, timeout=1):
  return ser.write(data)

# open serial port
ser = serial.Serial(
  PORT,
  BAUD,
  parity=serial.PARITY_NONE,
  stopbits=serial.STOPBITS_ONE,
  bytesize=serial.EIGHTBITS,
  timeout=1,
  rtscts=False,
  dsrdtr=False
)

# send init command
# ~ ser.write(b"ABWu\r\n")

# Check if Abeeway in bootloader
is_bootloader=False
buffer=b""
ser.write(b"i")
while True:
  c = ser.read(1)
  if not c:
    continue
  buffer += c
  if b"HWID" in buffer:
    is_bootloader=True
    break
buffer_str = buffer.decode(errors="replace")  # replace invalid bytes
print(f"{buffer_str}")

# Flush 
buffer=b""
while True:
  c = ser.read(1)
  if not c:
    break
  buffer += c
  
if not is_bootloader:
  print("Not in bootloader mode. Aborting")
  quit(1)
print(f"Found bootloader on {PORT}")
ser.write(b"A")
ser.write(b"B")
ser.write(b"W")
ser.write(b"u\r")
# wait until device says "Ready"
buffer = b""
while True:
  c = ser.read(1)
  if not c:
    continue
  buffer += c
  #print(f":: {buffer}")
  if b"Ready" in buffer:
    print("Device is ready, starting XMODEM...")
    break

# start xmodem transfer
modem = XMODEM(getc, putc)
with open(FILE, "rb") as stream:
  success = modem.send(stream, retry=16, timeout=10)
  print("Transfer success:", success)
  print("Reset")
  ser.write(b"r")