import serial import time import sys def upload_via_serial(port, local_path, remote_path): print(f"Opening serial port {port}...") try: ser = serial.Serial(port, 115200, timeout=0.5) except Exception as e: print("Failed to open serial port:", e) return False print("Interrupting board (Ctrl+C)...") for _ in range(50): ser.write(b'\x03') time.sleep(0.02) time.sleep(0.5) ser.read_all() print("Entering raw REPL...") ser.write(b'\x01') time.sleep(0.2) resp = ser.read_all() if b'raw REPL' not in resp and b'OK' not in resp and b'raw' not in resp: print("Could not enter raw REPL:", resp) ser.close() return False with open(local_path, 'rb') as f: content = f.read() print(f"Uploading {local_path} to remote {remote_path} ({len(content)} bytes)...") # Open file cmd = f"f = open('{remote_path}', 'wb')\n".encode('utf-8') ser.write(cmd) ser.write(b'\x04') time.sleep(0.1) ser.read_all() # Write chunks chunk_size = 256 for i in range(0, len(content), chunk_size): chunk = content[i:i+chunk_size] cmd = b"f.write(" + repr(chunk).encode('utf-8') + b")\n" ser.write(cmd) ser.write(b'\x04') time.sleep(0.05) sys.stdout.write('.') sys.stdout.flush() cmd = b"f.close()\n" ser.write(cmd) ser.write(b'\x04') time.sleep(0.1) ser.read_all() print(f"\nUploaded {remote_path} successfully!") ser.write(b'\x02') ser.close() return True def main(): port = '/dev/cu.usbmodem101' files_to_upload = [ ("main.py", "main.py"), ("demo_websocket_voice.py", "demo_websocket_voice.py") ] for local, remote in files_to_upload: if not upload_via_serial(port, local, remote): print(f"Failed to upload {local}. Exiting.") sys.exit(1) print("Rebooting board...") try: ser = serial.Serial(port, 115200, timeout=0.5) ser.write(b'\x03') time.sleep(0.1) ser.write(b'import machine\nmachine.reset()\n') ser.close() print("Reset triggered successfully!") except Exception as e: print("Could not trigger reset:", e) if __name__ == "__main__": main()