Layer: L7 Application ยท Build flags: PC_ENABLE_OTA
What this example teaches
This registers a streaming POST /update endpoint: a firmware image POSTed with valid HTTP Basic credentials is fed straight into the ESP32 Update API through the parser's streaming-body hook, so the image never has to fit in RAM, then the device reboots into the new firmware.
One call wires authenticated streaming OTA:
void pc_ota_begin(PC &server, const char *path, const char *user, const char *pass)
Register an authenticated streaming OTA endpoint.
The body is streamed chunk by chunk into flash as it arrives; only requests with the configured Basic credentials are accepted. Because it uses the same streaming-body hook as file upload, enable OTA or upload, not both (see FileUpload). Build your firmware.bin with pio run (it lands at .pio/build/<env>/firmware.bin).
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--project-option="build_flags=-DPC_ENABLE_OTA=1 -DMAX_CONNS=4" \
--lib="." examples/L7-Application/OTA/OTA.ino
curl -u admin:s3cret --data-binary @firmware.bin http://<ip>/update
Annotated source
The complete sketch (OTA.ino), reproduced verbatim with added explanatory comments:
#define PC_ENABLE_OTA 1
#include "services/ota_service.h"
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
void handle_root(uint8_t slot_id,
HttpReq *req)
{
(void)req;
server.
send(slot_id, 200,
"text/plain",
"OTA demo - POST a firmware image to /update");
}
void setup()
{
Serial.begin(115200);
delay(250);
Serial.print("IP: ");
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
if (server.
begin(80) < 0)
{
Serial.println("begin() failed");
return;
}
Serial.println("Server up; OTA at POST /update");
}
void loop()
{
}
Single-port HTTP server with deterministic, zero-allocation execution.
void send(uint8_t slot_id, int code, const char *content_type, const char *payload)
Send an HTTP response with a body and close the connection.
int32_t begin(const WebServerConfig *cfg=nullptr)
Initialize all connection slots and open all registered listeners.
void on(const char *path, HttpMethod method, Handler callback)
Register a route handler.
void handle()
Drive the server - call every Arduino loop() iteration.
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
@ HTTP_GET
Safe, idempotent read.
Fully-parsed HTTP/1.1 request.