-
Notifications
You must be signed in to change notification settings - Fork 317
feat: Add ESP32 WiFi Unified OTA update support #898
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ianmcorvidae
merged 5 commits into
meshtastic:master
from
skgsergio:feat/esp32-unified-ota
Mar 2, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1eb13c9
feat: Add ESP32 WiFi Unified OTA update support
skgsergio bf580c3
Update meshtastic/__main__.py
thebentern 4d8430d
fix: throw propper exceptions and cleanup code
skgsergio 4de19f5
fix: add tests
skgsergio 5721859
fix: cleanup imports in tests
skgsergio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| """Meshtastic ESP32 Unified OTA | ||
| """ | ||
| import os | ||
| import hashlib | ||
| import socket | ||
| import logging | ||
| from typing import Optional, Callable | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _file_sha256(filename: str): | ||
| """Calculate SHA256 hash of a file.""" | ||
| sha256_hash = hashlib.sha256() | ||
|
|
||
| with open(filename, "rb") as f: | ||
| for byte_block in iter(lambda: f.read(4096), b""): | ||
| sha256_hash.update(byte_block) | ||
|
|
||
| return sha256_hash | ||
|
|
||
|
|
||
| class OTAError(Exception): | ||
| """Exception for OTA errors.""" | ||
|
|
||
|
|
||
| class ESP32WiFiOTA: | ||
| """ESP32 WiFi Unified OTA updates.""" | ||
|
|
||
| def __init__(self, filename: str, hostname: str, port: int = 3232): | ||
| self._filename = filename | ||
| self._hostname = hostname | ||
| self._port = port | ||
| self._socket: Optional[socket.socket] = None | ||
|
|
||
| if not os.path.exists(self._filename): | ||
| raise FileNotFoundError(f"File {self._filename} does not exist") | ||
|
|
||
| self._file_hash = _file_sha256(self._filename) | ||
|
|
||
| def _read_line(self) -> str: | ||
| """Read a line from the socket.""" | ||
| if not self._socket: | ||
| raise ConnectionError("Socket not connected") | ||
|
|
||
| line = b"" | ||
| while not line.endswith(b"\n"): | ||
| char = self._socket.recv(1) | ||
|
|
||
| if not char: | ||
| raise ConnectionError("Connection closed while waiting for response") | ||
|
|
||
| line += char | ||
|
|
||
| return line.decode("utf-8").strip() | ||
|
|
||
| def hash_bytes(self) -> bytes: | ||
| """Return the hash as bytes.""" | ||
| return self._file_hash.digest() | ||
|
|
||
| def hash_hex(self) -> str: | ||
| """Return the hash as a hex string.""" | ||
| return self._file_hash.hexdigest() | ||
|
|
||
| def update(self, progress_callback: Optional[Callable[[int, int], None]] = None): | ||
| """Perform the OTA update.""" | ||
| with open(self._filename, "rb") as f: | ||
| data = f.read() | ||
| size = len(data) | ||
|
|
||
| logger.info(f"Starting OTA update with {self._filename} ({size} bytes, hash {self.hash_hex()})") | ||
|
|
||
| self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| self._socket.settimeout(15) | ||
| try: | ||
| self._socket.connect((self._hostname, self._port)) | ||
| logger.debug(f"Connected to {self._hostname}:{self._port}") | ||
|
|
||
| # Send start command | ||
| self._socket.sendall(f"OTA {size} {self.hash_hex()}\n".encode("utf-8")) | ||
|
|
||
| # Wait for OK from the device | ||
| while True: | ||
| response = self._read_line() | ||
| if response == "OK": | ||
| break | ||
|
|
||
| if response == "ERASING": | ||
| logger.info("Device is erasing flash...") | ||
| elif response.startswith("ERR "): | ||
| raise OTAError(f"Device reported error: {response}") | ||
| else: | ||
| logger.warning(f"Unexpected response: {response}") | ||
|
|
||
| # Stream firmware | ||
| sent_bytes = 0 | ||
| chunk_size = 1024 | ||
| while sent_bytes < size: | ||
| chunk = data[sent_bytes : sent_bytes + chunk_size] | ||
| self._socket.sendall(chunk) | ||
| sent_bytes += len(chunk) | ||
|
|
||
| if progress_callback: | ||
| progress_callback(sent_bytes, size) | ||
| else: | ||
| print(f"[{sent_bytes / size * 100:5.1f}%] Sent {sent_bytes} of {size} bytes...", end="\r") | ||
|
|
||
| if not progress_callback: | ||
| print() | ||
|
|
||
| # Wait for OK from device | ||
| logger.info("Firmware sent, waiting for verification...") | ||
| while True: | ||
| response = self._read_line() | ||
| if response == "OK": | ||
| logger.info("OTA update completed successfully!") | ||
| break | ||
|
|
||
| if response.startswith("ERR "): | ||
| raise OTAError(f"OTA update failed: {response}") | ||
| elif response != "ACK": | ||
| logger.warning(f"Unexpected final response: {response}") | ||
|
|
||
| finally: | ||
| if self._socket: | ||
| self._socket.close() | ||
| self._socket = None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.