#!/usr/bin/env python3 """ MimiCon Wireless Over-The-Air (OTA) Automated Flash Tool Usage: python ota_flash.py [binary_path] [host_url] Examples: python ota_flash.py python ota_flash.py build/mimicon.bin http://mimicon.local """ import sys import os import time import json import urllib.request import urllib.error DEFAULT_HOST = "http://mimicon.local" ALT_HOST = "http://esp32-hid.local" DEFAULT_BIN = os.path.join(os.path.dirname(__file__), "build", "mimicon.bin") ALT_BIN = os.path.join(os.path.dirname(__file__), "build", "esp32_s3_zero_skeleton.bin") def get_status(host, timeout=5): url = f"{host.rstrip('/')}/api/status" req = urllib.request.Request(url, headers={"User-Agent": "MimiCon-OTA-Tool"}) try: with urllib.request.urlopen(req, timeout=timeout) as resp: if resp.status == 200: return json.loads(resp.read().decode("utf-8")) except Exception: return None return None def flash_firmware(bin_path, host): if not os.path.isfile(bin_path): if bin_path == DEFAULT_BIN and os.path.isfile(ALT_BIN): bin_path = ALT_BIN else: print(f"[-] Error: Firmware binary not found at '{bin_path}'") return False file_size = os.path.getsize(bin_path) print("=" * 60) print(" MimiCon Wireless Over-The-Air (OTA) Flasher ") print("=" * 60) print(f"[*] Target Host: {host}") print(f"[*] Firmware Binary: {bin_path} ({file_size:,} bytes / {file_size / 1024:.1f} KB)") print("[*] Contacting device via mDNS...") initial_status = get_status(host, timeout=6) if not initial_status and host == DEFAULT_HOST: print(f"[*] Trying fallback host '{ALT_HOST}'...") initial_status = get_status(ALT_HOST, timeout=6) if initial_status: host = ALT_HOST if not initial_status: # Try fallback to IP if needed or print error print(f"[-] Could not reach device at '{host}'.") print(" Ensure the ESP32-S3 is powered on, Wi-Fi is active, and your PC is on the same network.") return False app_version = initial_status.get("app_version", "unknown") running_part = initial_status.get("running_part", "unknown") next_part = initial_status.get("next_part", "unknown") compile_time = initial_status.get("compile_time", "unknown") mode_name = initial_status.get("mode_name", "unknown") sta_ssid = initial_status.get("sta_ssid", "unknown") sta_ip = initial_status.get("sta_ip", "unknown") print(f"[+] Device Connected!") print(f" - Firmware: MimiCon v{app_version} (Built: {compile_time})") print(f" - Network: {sta_ssid} (IP: {sta_ip})") print(f" - Console Mode: {mode_name}") print(f" - Current Slot: {running_part} -> Target Slot: {next_part}") print() upload_url = f"{host.rstrip('/')}/api/ota/upload" print(f"[*] Uploading binary to {upload_url}...") with open(bin_path, "rb") as f: bin_data = f.read() req = urllib.request.Request( upload_url, data=bin_data, headers={ "Content-Type": "application/octet-stream", "Content-Length": str(len(bin_data)), "User-Agent": "ESP32-OTA-Tool" }, method="POST" ) start_time = time.time() try: with urllib.request.urlopen(req, timeout=120) as resp: resp_body = resp.read().decode("utf-8") elapsed = time.time() - start_time speed = (file_size / 1024) / elapsed if elapsed > 0 else 0 print(f"[+] Upload complete in {elapsed:.2f}s ({speed:.1f} KB/s)!") print(f"[+] Device response: {resp_body}") except urllib.error.HTTPError as e: print(f"[-] HTTP Error {e.code}: {e.read().decode('utf-8')}") return False except Exception as e: print(f"[-] Upload failed: {e}") return False print("\n[*] Waiting for ESP32-S3 reboot and reconnection (approx. 5-8 seconds)...") time.sleep(3) reconnected = False for attempt in range(15): time.sleep(1) st = get_status(host, timeout=2) if st: new_running = st.get("running_part", "unknown") new_compile = st.get("compile_time", "unknown") print(f"\n[+] ESP32-S3 is back online!") print(f" - Active Slot: {new_running}") print(f" - Build Time: {new_compile}") print(f" - Console Mode: {st.get('mode_name', 'unknown')}") if new_running == next_part: print(f"[SUCCESS] Successfully updated from {running_part} -> {new_running}!") else: print(f"[+] Partition status: {new_running}") reconnected = True break else: print(".", end="", flush=True) if not reconnected: print("\n[!] Device rebooted but took longer than 15s to reconnect to mDNS.") print(" Check the serial monitor or web portal to verify.") return True return True if __name__ == "__main__": target_bin = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_BIN target_host = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_HOST success = flash_firmware(target_bin, target_host) sys.exit(0 if success else 1)