add OTA Update to web_client

This commit is contained in:
Wastl Kraus 2025-09-17 13:15:47 +02:00
parent 93ea08309b
commit 206a19ac41
3 changed files with 364 additions and 4 deletions

View File

@ -7,9 +7,11 @@
*/
#include <Arduino.h>
#include <Update.h>
#include <WiFi.h>
#include <DShotRMT.h>
#include <ota_update.h>
#include <web_content.h>
#include <ArduinoJson.h>
@ -62,6 +64,8 @@ void handleWebSocketMessage(void *arg, uint8_t *data, size_t len);
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len);
bool connectToWiFi();
void printWiFiStatus();
void setupOTA();
void handleOTAUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final);
//
void setup()
@ -79,15 +83,18 @@ void setup()
if (wifi_connected)
{
// Setup OTA first
setupOTA();
// Init WebSockets and Webserver
USB_SERIAL.println("\nStarting Webserver...");
ws.onEvent(onWsEvent);
server.addHandler(&ws);
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send_P(200, "text/html", index_html); });
server.begin();
USB_SERIAL.println("HTTP server started.");
@ -96,7 +103,7 @@ void setup()
else
{
USB_SERIAL.println("\n*** WARNING: WiFi connection failed! ***");
USB_SERIAL.println("*** Web interface not available ***");
USB_SERIAL.println("*** Web interface and OTA not available ***");
USB_SERIAL.println("*** Only serial control available ***");
}
@ -215,6 +222,87 @@ void loop()
}
}
// Setup OTA Update functionality
void setupOTA()
{
USB_SERIAL.println("Setting up OTA Update...");
// Serve OTA update page
server.on("/update", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send_P(200, "text/html", ota_html); });
// Handle OTA update upload
server.on("/update", HTTP_POST, [](AsyncWebServerRequest *request)
{
bool shouldReboot = !Update.hasError();
AsyncWebServerResponse *response = request->beginResponse(200, "text/plain",
shouldReboot ? "OK" : "FAIL");
response->addHeader("Connection", "close");
request->send(response);
if (shouldReboot) {
USB_SERIAL.println("OTA Update successful! Rebooting...");
delay(1000);
ESP.restart();
} else {
USB_SERIAL.println("OTA Update failed!");
} }, handleOTAUpload);
USB_SERIAL.println("OTA Update ready at: /update");
}
// Handle OTA upload process
void handleOTAUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final)
{
static unsigned long ota_progress_millis = 0;
if (!index)
{
// Safety: Ensure motor is stopped during update
motor01.sendCommand(DSHOT_CMD_MOTOR_STOP);
setArmingStatus(false);
USB_SERIAL.printf("OTA Update Start: %s\n", filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN))
{
Update.printError(USB_SERIAL);
return;
}
}
if (len)
{
if (Update.write(data, len) != len)
{
Update.printError(USB_SERIAL);
return;
}
// Print progress every 2 seconds to avoid spam
if (millis() - ota_progress_millis > 2000)
{
size_t progress = index + len;
USB_SERIAL.printf("OTA Progress: %zu bytes\n", progress);
ota_progress_millis = millis();
}
}
if (final)
{
if (Update.end(true))
{
USB_SERIAL.printf("OTA Update Success: %zu bytes\n", index + len);
}
else
{
Update.printError(USB_SERIAL);
}
}
}
// Connect to WiFi network
bool connectToWiFi()
{
@ -262,6 +350,7 @@ void printWiFiStatus()
USB_SERIAL.printf("MAC Address: %s\n", WiFi.macAddress().c_str());
USB_SERIAL.println("***********************************************");
USB_SERIAL.printf("Web Interface: http://%s\n", WiFi.localIP().toString().c_str());
USB_SERIAL.printf("OTA Update: http://%s/update\n", WiFi.localIP().toString().c_str());
USB_SERIAL.println("***********************************************");
}
else
@ -305,10 +394,12 @@ void printMenu()
if (wifi_connected)
{
USB_SERIAL.printf(" Web Interface: http://%s \n", WiFi.localIP().toString().c_str());
USB_SERIAL.printf(" OTA Update: http://%s/update \n", WiFi.localIP().toString().c_str());
}
else
{
USB_SERIAL.println(" Web Interface: NOT AVAILABLE ");
USB_SERIAL.println(" OTA Update: NOT AVAILABLE ");
}
USB_SERIAL.println("***********************************************");
@ -321,6 +412,7 @@ void printMenu()
USB_SERIAL.println(" info - Show motor info");
USB_SERIAL.println(" wifi - Show WiFi status");
USB_SERIAL.println(" reconnect - Reconnect to WiFi");
USB_SERIAL.println(" ota - Show OTA info");
if (IS_BIDIRECTIONAL)
{
USB_SERIAL.println(" rpm - Get telemetry data");
@ -362,6 +454,24 @@ void handleSerialInput(const String &input)
return;
}
if (input == "ota")
{
if (wifi_connected)
{
USB_SERIAL.println(" ");
USB_SERIAL.println("=== OTA UPDATE INFO ===");
USB_SERIAL.printf("OTA Update URL: http://%s/update\n", WiFi.localIP().toString().c_str());
USB_SERIAL.printf("Free Sketch Space: %u bytes\n", ESP.getFreeSketchSpace());
USB_SERIAL.printf("Sketch Size: %u bytes\n", ESP.getSketchSize());
USB_SERIAL.println("========================");
}
else
{
USB_SERIAL.println("OTA Update not available - WiFi not connected!");
}
return;
}
if (input == "reconnect")
{
USB_SERIAL.println("Reconnecting to WiFi...");
@ -431,6 +541,7 @@ void handleSerialInput(const String &input)
if (wifi_connected)
{
USB_SERIAL.printf("IP Address: %s\n", WiFi.localIP().toString().c_str());
USB_SERIAL.printf("OTA URL: http://%s/update\n", WiFi.localIP().toString().c_str());
}
return;
}

View File

@ -8,4 +8,4 @@ paragraph=This library can control a BlHeli_S by using encoded DShot commands. F
category=Signal Input/Output
url=https://github.com/derdoktor667/DShotRMT
architectures=esp32
provides_includes=DShotRMT.h, DShotCommandManager.h, dshot_commands.h, web_content.h
provides_includes=DShotRMT.h, DShotCommandManager.h, dshot_commands.h, web_content.h, ota_update.h

249
src/ota_update.h Normal file
View File

@ -0,0 +1,249 @@
/**
* @file ota_update.h
* @brief DShot signal generation using ESP32 RMT with bidirectional support
* @author Wastl Kraus
* @date 2025-09-13
* @license MIT
*/
#pragma once
// OTA Update HTML
const char *ota_html = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>OTA Update - DShotRMT</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
background-color: #2c3e50;
color: #ecf0f1;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #34495e;
padding: 30px;
border-radius: 12px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
h1 {
text-align: center;
color: #3498db;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="file"] {
width: 100%;
padding: 8px;
border: 1px solid #7f8c8d;
border-radius: 4px;
background-color: #2c3e50;
color: #ecf0f1;
}
.btn {
background-color: #3498db;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
width: 100%;
font-size: 16px;
}
.btn:hover {
background-color: #2980b9;
}
.btn:disabled {
background-color: #7f8c8d;
cursor: not-allowed;
}
.progress {
width: 100%;
background-color: #2c3e50;
border-radius: 4px;
margin-top: 10px;
display: none;
}
.progress-bar {
width: 0%;
height: 30px;
background-color: #27ae60;
border-radius: 4px;
text-align: center;
line-height: 30px;
color: white;
}
.message {
margin-top: 20px;
padding: 10px;
border-radius: 4px;
display: none;
}
.success {
background-color: #27ae60;
}
.error {
background-color: #e74c3c;
}
.warning {
background-color: #f39c12;
color: #2c3e50;
margin-bottom: 20px;
padding: 15px;
border-radius: 8px;
font-weight: bold;
}
.back-link {
text-align: center;
margin-top: 20px;
}
.back-link a {
color: #3498db;
text-decoration: none;
}
.back-link a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<h1>OTA Firmware Update</h1>
<div class="warning">
WARNING: Stop motors before starting update!
</div>
<form id="upload_form" enctype="multipart/form-data">
<div class="form-group">
<label for="update">Firmware File (.bin):</label>
<input type="file" id="update" name="update" accept=".bin" required>
</div>
<button type="submit" class="btn" id="uploadBtn">Update!</button>
</form>
<div class="progress" id="progressDiv">
<div class="progress-bar" id="progressBar">0%</div>
</div>
<div class="message" id="message"></div>
</div>
<script>
document.getElementById('upload_form').addEventListener('submit', function (e) {
e.preventDefault();
const fileInput = document.getElementById('update');
const file = fileInput.files[0];
if (!file) {
showMessage('Choose a valid update file.', 'error');
return;
}
if (!file.name.endsWith('.bin')) {
showMessage('Choose a valid update file.', 'error');
return;
}
uploadFile(file);
});
function uploadFile(file) {
const formData = new FormData();
formData.append('update', file);
const xhr = new XMLHttpRequest();
// Progress tracking
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
updateProgress(percentComplete);
}
});
// Upload complete
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
showMessage('Update successfull! Restarting...', 'success');
setTimeout(() => {
window.location.href = '/';
}, 5000);
} else {
showMessage('Update failed: ' + xhr.responseText, 'error');
resetUpload();
}
});
// Upload error
xhr.addEventListener('error', function () {
showMessage('Connection error during Update.', 'error');
resetUpload();
});
// Start upload
document.getElementById('uploadBtn').disabled = true;
document.getElementById('uploadBtn').textContent = 'buffering...';
document.getElementById('progressDiv').style.display = 'block';
xhr.open('POST', '/update');
xhr.send(formData);
}
function updateProgress(percent) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = percent + '%';
progressBar.textContent = Math.round(percent) + '%';
}
function showMessage(text, type) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = text;
messageDiv.className = 'message ' + type;
messageDiv.style.display = 'block';
}
function resetUpload() {
document.getElementById('uploadBtn').disabled = false;
document.getElementById('uploadBtn').textContent = 'Update!';
document.getElementById('progressDiv').style.display = 'none';
document.getElementById('progressBar').style.width = '0%';
document.getElementById('progressBar').textContent = '0%';
}
</script>
</body>
</html>
)rawliteral";