|
| 1 | +"""Meshtastic ESP32 Unified OTA |
| 2 | +""" |
| 3 | +import os |
| 4 | +import hashlib |
| 5 | +import socket |
| 6 | +import logging |
| 7 | +from typing import Optional, Callable |
| 8 | + |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +def _file_sha256(filename: str): |
| 14 | + """Calculate SHA256 hash of a file.""" |
| 15 | + sha256_hash = hashlib.sha256() |
| 16 | + |
| 17 | + with open(filename, "rb") as f: |
| 18 | + for byte_block in iter(lambda: f.read(4096), b""): |
| 19 | + sha256_hash.update(byte_block) |
| 20 | + |
| 21 | + return sha256_hash |
| 22 | + |
| 23 | + |
| 24 | +class OTAError(Exception): |
| 25 | + """Exception for OTA errors.""" |
| 26 | + |
| 27 | + |
| 28 | +class ESP32WiFiOTA: |
| 29 | + """ESP32 WiFi Unified OTA updates.""" |
| 30 | + |
| 31 | + def __init__(self, filename: str, hostname: str, port: int = 3232): |
| 32 | + self._filename = filename |
| 33 | + self._hostname = hostname |
| 34 | + self._port = port |
| 35 | + self._socket: Optional[socket.socket] = None |
| 36 | + |
| 37 | + if not os.path.exists(self._filename): |
| 38 | + raise FileNotFoundError(f"File {self._filename} does not exist") |
| 39 | + |
| 40 | + self._file_hash = _file_sha256(self._filename) |
| 41 | + |
| 42 | + def _read_line(self) -> str: |
| 43 | + """Read a line from the socket.""" |
| 44 | + if not self._socket: |
| 45 | + raise ConnectionError("Socket not connected") |
| 46 | + |
| 47 | + line = b"" |
| 48 | + while not line.endswith(b"\n"): |
| 49 | + char = self._socket.recv(1) |
| 50 | + |
| 51 | + if not char: |
| 52 | + raise ConnectionError("Connection closed while waiting for response") |
| 53 | + |
| 54 | + line += char |
| 55 | + |
| 56 | + return line.decode("utf-8").strip() |
| 57 | + |
| 58 | + def hash_bytes(self) -> bytes: |
| 59 | + """Return the hash as bytes.""" |
| 60 | + return self._file_hash.digest() |
| 61 | + |
| 62 | + def hash_hex(self) -> str: |
| 63 | + """Return the hash as a hex string.""" |
| 64 | + return self._file_hash.hexdigest() |
| 65 | + |
| 66 | + def update(self, progress_callback: Optional[Callable[[int, int], None]] = None): |
| 67 | + """Perform the OTA update.""" |
| 68 | + with open(self._filename, "rb") as f: |
| 69 | + data = f.read() |
| 70 | + size = len(data) |
| 71 | + |
| 72 | + logger.info(f"Starting OTA update with {self._filename} ({size} bytes, hash {self.hash_hex()})") |
| 73 | + |
| 74 | + self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 75 | + self._socket.settimeout(15) |
| 76 | + try: |
| 77 | + self._socket.connect((self._hostname, self._port)) |
| 78 | + logger.debug(f"Connected to {self._hostname}:{self._port}") |
| 79 | + |
| 80 | + # Send start command |
| 81 | + self._socket.sendall(f"OTA {size} {self.hash_hex()}\n".encode("utf-8")) |
| 82 | + |
| 83 | + # Wait for OK from the device |
| 84 | + while True: |
| 85 | + response = self._read_line() |
| 86 | + if response == "OK": |
| 87 | + break |
| 88 | + |
| 89 | + if response == "ERASING": |
| 90 | + logger.info("Device is erasing flash...") |
| 91 | + elif response.startswith("ERR "): |
| 92 | + raise OTAError(f"Device reported error: {response}") |
| 93 | + else: |
| 94 | + logger.warning(f"Unexpected response: {response}") |
| 95 | + |
| 96 | + # Stream firmware |
| 97 | + sent_bytes = 0 |
| 98 | + chunk_size = 1024 |
| 99 | + while sent_bytes < size: |
| 100 | + chunk = data[sent_bytes : sent_bytes + chunk_size] |
| 101 | + self._socket.sendall(chunk) |
| 102 | + sent_bytes += len(chunk) |
| 103 | + |
| 104 | + if progress_callback: |
| 105 | + progress_callback(sent_bytes, size) |
| 106 | + else: |
| 107 | + print(f"[{sent_bytes / size * 100:5.1f}%] Sent {sent_bytes} of {size} bytes...", end="\r") |
| 108 | + |
| 109 | + if not progress_callback: |
| 110 | + print() |
| 111 | + |
| 112 | + # Wait for OK from device |
| 113 | + logger.info("Firmware sent, waiting for verification...") |
| 114 | + while True: |
| 115 | + response = self._read_line() |
| 116 | + if response == "OK": |
| 117 | + logger.info("OTA update completed successfully!") |
| 118 | + break |
| 119 | + |
| 120 | + if response.startswith("ERR "): |
| 121 | + raise OTAError(f"OTA update failed: {response}") |
| 122 | + elif response != "ACK": |
| 123 | + logger.warning(f"Unexpected final response: {response}") |
| 124 | + |
| 125 | + finally: |
| 126 | + if self._socket: |
| 127 | + self._socket.close() |
| 128 | + self._socket = None |
0 commit comments