import argparse import serial def send_command(ser, command): """Sends a command to the serial device and returns the response.""" full_command = f"!{command}\r\n" ser.write(full_command.encode("utf-8")) lines = [] # Determine the expected end marker end_marker = f"#{command.split('(')[0]}()" if command.startswith("RPF"): end_marker = "#RP()" while True: line = ser.readline().decode("utf-8").strip() if line == end_marker: break if line and line != f"!{command}": lines.append(line) return lines def execute_commands(ser, commands): """Executes a list of commands and checks for errors.""" for command in commands: print(f"--- {command} ---") response_lines = send_command(ser, command) for line in response_lines: print(line) if command == "ERROR()": if not response_lines or not response_lines[-1].endswith("0"): print("Error: Device reported an error. Exiting.") exit(1) def main(): # Parse command-line arguments parser = argparse.ArgumentParser( description="Open a serial device at a specified port." ) parser.add_argument( "port", type=str, help="The serial port to open (e.g., /dev/ttyUSB0)." ) parser.add_argument( "--channel", type=int, default=0, help="LED channel (default: 0).", ) args = parser.parse_args() # Open the serial port try: with serial.Serial(port=args.port, baudrate=115200, timeout=1) as ser: print(f"Successfully opened serial port {args.port} at 115200 baud.") commands1 = [ "SN()", "GETFILT()", "TEMP()", f"CALIBRATE({args.channel},-1)", "ERROR()", ] commands2 = [ f"RPF({args.channel},-1)", "ERROR()", ] execute_commands(ser, commands1) input("Insert plate and press Enter to continue...") execute_commands(ser, commands2) except serial.SerialException as e: print(f"Error: {e}") if __name__ == "__main__": main()