import serial import sys import time PACKET_HEADER = b'\0\0\0\0\0\x01' SIGN_TYPE = b'Z' SIGN_ADDRESS = b'00' VALID_NAMES = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def encode_packet(command_code, data): return PACKET_HEADER + SIGN_TYPE + SIGN_ADDRESS + b'\x02' + command_code + data + b'\x04' def generate_memory_config(files: list[tuple[bytes, int]]): data = b'$' for name, size in files: if len(name) != 1: raise ValueError() if name not in VALID_NAMES: raise ValueError() data += name data += b'AU' data += hex(size).upper()[2:].encode().rjust(4, b'0') # data += b'00FF' data += b'FFFF' return encode_packet(b'E', data) def generate_run_order(files: list[bytes]): data = b'.TU' for name in files: if len(name) != 1: raise ValueError() if name not in VALID_NAMES: raise ValueError() data += name return encode_packet(b'E', data) def generate_write_text_file(name: bytes, content: bytes): return encode_packet(b'A', name + content) def main(args: list[str]): if len(args) < 3: print(f'Usage: {args[0]} ') exit(1) file_name = args[1] serial_port = args[2] with open(file_name) as f: lines = f.readlines() if len(lines) > len(VALID_NAMES): print('Too many lines! I dont have enough files!') exit(1) run_order = [] files = [] text_packets = [] for file_name, line in zip(VALID_NAMES, lines): file_name = bytes([file_name]) data = line.strip().encode() length = len(data) run_order.append(file_name) files.append((file_name, length)) text_packets.append(generate_write_text_file(file_name, data)) with serial.Serial(serial_port, 9600) as ser: print('Config memory') ser.write(generate_memory_config(files)) print('+', generate_memory_config(files).hex()) time.sleep(1) print('Send files') for tp in text_packets: ser.write(tp) print('+', tp.hex()) time.sleep(1) print('Send run order') ser.write(generate_run_order(run_order)) print('+', generate_run_order(run_order).hex()) print('Done!') if __name__ == '__main__': main(sys.argv)