Add firmware slices 1–2: skeleton and Wi-Fi provisioning

Implement ESP-IDF walking skeleton with SoftAP, health API, and host
tests, then Slice 2 ISecureStore/NvsSecureStore, STA join, POST
/api/wifi, and the provisioning web UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-06 09:10:37 +02:00
co-authored by Cursor
parent 9f04c4bb0c
commit ddbee70c23
63 changed files with 3771 additions and 19 deletions
@@ -0,0 +1,198 @@
/**
* @file NetBootstrap.cpp
* @brief NetBootstrap implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "net/NetBootstrap.hpp"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
namespace net {
namespace {
constexpr char kTag[] = "NetBootstrap";
/**
* @brief initPlatform — one-time NVS and TCP/IP stack bring-up.
*
* @dname initPlatform
* @return Ok on success, or a NetError describing the failure.
* @pubstate initialises NVS, esp_netif, and the default event loop.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<void, NetError> initPlatform()
{
esp_err_t nvsErr = nvs_flash_init();
if (nvsErr == ESP_ERR_NVS_NO_FREE_PAGES
|| nvsErr == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
nvsErr = nvs_flash_init();
}
if (nvsErr != ESP_OK) {
ESP_LOGE(kTag, "nvs_flash_init failed");
return std::unexpected(NetError::NvsInitFailed);
}
if (esp_netif_init() != ESP_OK) {
ESP_LOGE(kTag, "esp_netif_init failed");
return std::unexpected(NetError::NetifInitFailed);
}
if (esp_event_loop_create_default() != ESP_OK) {
ESP_LOGE(kTag, "esp_event_loop_create_default failed");
return std::unexpected(NetError::EventLoopFailed);
}
return {};
}
/**
* @brief initWifiStack — initialise the Wi-Fi driver once.
*
* @dname initWifiStack
* @return Ok on success, or NetError::WifiInitFailed.
* @pubstate calls esp_wifi_init.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<void, NetError> initWifiStack()
{
wifi_init_config_t initCfg = WIFI_INIT_CONFIG_DEFAULT();
if (esp_wifi_init(&initCfg) != ESP_OK) {
ESP_LOGE(kTag, "esp_wifi_init failed");
return std::unexpected(NetError::WifiInitFailed);
}
return {};
}
/**
* @brief startSetupMode — SoftAP plus HTTP for first-time provisioning.
*
* @dname startSetupMode
* @param store Store passed through to the web server routes.
* @return NetBootstrap in SoftApSetup, or a NetError.
* @pubstate creates default Wi-Fi AP netif and starts SoftAP.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<NetBootstrap, NetError>
startSetupMode(core::ISecureStore& store)
{
esp_netif_create_default_wifi_ap();
SoftApHost softAp(SoftApConfig::setupDefault());
if (auto apResult = softAp.start(); !apResult) {
return std::unexpected(apResult.error());
}
SetupWebServer webServer;
if (auto webResult = webServer.start(store, NetState::SoftApSetup);
!webResult) {
return std::unexpected(webResult.error());
}
ESP_LOGI(kTag, "setup mode ready — SSID DigiRadio-setup");
return NetBootstrap(std::move(softAp), std::nullopt, std::move(webServer),
NetState::SoftApSetup);
}
/**
* @brief startStaMode — join stored Wi-Fi and serve HTTP on STA.
*
* @dname startStaMode
* @param store Store supplying validated STA credentials.
* @return NetBootstrap in StaConnected, or a NetError.
* @pubstate creates default Wi-Fi STA netif and connects.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<NetBootstrap, NetError>
startStaMode(core::ISecureStore& store)
{
auto credsResult = store.loadWifiCredentials();
if (!credsResult) {
ESP_LOGE(kTag, "stored credentials missing");
return std::unexpected(NetError::CredentialsNotFound);
}
esp_netif_create_default_wifi_sta();
StaClient sta;
if (auto staResult = sta.connect(credsResult.value()); !staResult) {
return std::unexpected(staResult.error());
}
SetupWebServer webServer;
if (auto webResult = webServer.start(store, NetState::StaConnected);
!webResult) {
return std::unexpected(webResult.error());
}
ESP_LOGI(kTag, "STA mode ready");
return NetBootstrap(std::nullopt, std::move(sta), std::move(webServer),
NetState::StaConnected);
}
} // namespace
std::expected<NetBootstrap, NetError>
NetBootstrap::start(core::ISecureStore& store)
{
if (auto platform = initPlatform(); !platform) {
return std::unexpected(platform.error());
}
if (auto wifi = initWifiStack(); !wifi) {
return std::unexpected(wifi.error());
}
if (store.hasWifiCredentials()) {
auto staResult = startStaMode(store);
if (staResult) {
return staResult;
}
ESP_LOGW(kTag, "STA join failed — falling back to setup SoftAP");
}
return startSetupMode(store);
}
NetBootstrap::NetBootstrap(std::optional<SoftApHost> softAp,
std::optional<StaClient> sta,
SetupWebServer webServer,
NetState state)
: softAp_(std::move(softAp))
, sta_(std::move(sta))
, webServer_(std::move(webServer))
, state_(state)
{
}
NetState NetBootstrap::state() const noexcept
{
return state_;
}
} // namespace net
@@ -0,0 +1,295 @@
/**
* @file SetupWebServer.cpp
* @brief SetupWebServer implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "net/SetupWebServer.hpp"
#include "core/FirmwareVersion.hpp"
#include "core/HealthStatus.hpp"
#include "core/HealthStatusJson.hpp"
#include "core/ParseError.hpp"
#include "core/WifiProvisionJson.hpp"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <array>
#include <string>
namespace net {
namespace {
constexpr char kTag[] = "SetupWebServer";
constexpr char kFirmwareVersion[] = "0.2.0";
constexpr unsigned kRebootDelaySec = 3;
SetupWebServer* gActiveServer = nullptr;
core::ISecureStore* gStore = nullptr;
extern const uint8_t www_index_html_gz_start[] asm(
"_binary_www_index_html_gz_start");
extern const uint8_t www_index_html_gz_end[] asm(
"_binary_www_index_html_gz_end");
/**
* @brief rebootTask — restart after provisioning so STA mode can run.
*
* @dname rebootTask
* @param arg Unused.
* @pubstate calls esp_restart.
*
* @author Michele Bigi
* @date 2026-07-06
*/
void rebootTask(void* arg)
{
(void)arg;
vTaskDelay(pdMS_TO_TICKS(kRebootDelaySec * 1000));
esp_restart();
}
/**
* @brief parseErrorToken — map ParseError to a safe API reason string.
*
* @dname parseErrorToken
* @param error Parse failure from the pure core.
* @return Short reason token without secrets.
* @pubstate none
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] const char* parseErrorToken(core::ParseError error) noexcept
{
switch (error) {
case core::ParseError::InvalidJson:
return "invalid_json";
case core::ParseError::MissingField:
return "missing_field";
case core::ParseError::InvalidSsid:
return "invalid_ssid";
case core::ParseError::InvalidPassword:
return "invalid_password";
}
return "parse_error";
}
/**
* @brief healthGetHandler — serve GET /api/health as JSON.
*
* @dname healthGetHandler
* @param req HTTP request handle from esp_http_server.
* @return ESP_OK on success, or an esp_err_t error code.
* @pubstate none; serialises HealthStatus via the pure core.
*
* @author Michele Bigi
* @date 2026-07-06
*/
esp_err_t healthGetHandler(httpd_req_t* req)
{
const core::HealthStatus status =
core::HealthStatus::ok(core::FirmwareVersion(kFirmwareVersion));
const std::string json = core::serializeHealthStatusJson(status);
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
/**
* @brief indexGetHandler — serve gzipped setup page from flash.
*
* @dname indexGetHandler
* @param req HTTP request handle from esp_http_server.
* @return ESP_OK on success, or an esp_err_t error code.
* @pubstate none; reads embedded www/index.html.gz blob.
*
* @author Michele Bigi
* @date 2026-07-06
*/
esp_err_t indexGetHandler(httpd_req_t* req)
{
const size_t length =
static_cast<size_t>(www_index_html_gz_end - www_index_html_gz_start);
httpd_resp_set_type(req, "text/html");
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
return httpd_resp_send(req,
reinterpret_cast<const char*>(www_index_html_gz_start),
length);
}
/**
* @brief wifiPostHandler — accept POST /api/wifi provisioning JSON.
*
* @dname wifiPostHandler
* @param req HTTP request handle from esp_http_server.
* @return ESP_OK on success, or an esp_err_t error code.
* @pubstate uses gActiveServer->store_ for persistence.
*
* @author Michele Bigi
* @date 2026-07-06
*/
esp_err_t wifiPostHandler(httpd_req_t* req)
{
if (gStore == nullptr) {
httpd_resp_set_status(req, "500 Internal Server Error");
return httpd_resp_send(req, nullptr, 0);
}
std::array<char, 512> body{};
int received = 0;
while (received < static_cast<int>(body.size()) - 1) {
const int chunk = httpd_req_recv(req, body.data() + received,
body.size() - 1 - received);
if (chunk <= 0) {
break;
}
received += chunk;
}
body[static_cast<std::size_t>(received)] = '\0';
const auto parsed =
core::parseWifiProvisionJson(std::string_view(body.data()));
if (!parsed) {
const std::string json = core::serializeWifiProvisionErrorJson(
parseErrorToken(parsed.error()));
httpd_resp_set_status(req, "400 Bad Request");
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
if (!gStore->saveWifiCredentials(parsed.value())) {
const std::string json =
core::serializeWifiProvisionErrorJson("store_failed");
httpd_resp_set_status(req, "500 Internal Server Error");
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
const std::string json =
core::serializeWifiProvisionSavedJson(kRebootDelaySec);
httpd_resp_set_type(req, "application/json");
httpd_resp_send(req, json.c_str(), json.size());
xTaskCreate(rebootTask, "reboot", 2048, nullptr, 5, nullptr);
return ESP_OK;
}
} // namespace
SetupWebServer::SetupWebServer()
: server_(nullptr)
, store_(nullptr)
, netState_(NetState::Uninitialized)
{
}
SetupWebServer::SetupWebServer(SetupWebServer&& other) noexcept
: server_(other.server_)
, store_(other.store_)
, netState_(other.netState_)
{
other.server_ = nullptr;
other.store_ = nullptr;
other.netState_ = NetState::Uninitialized;
gActiveServer = this;
}
SetupWebServer& SetupWebServer::operator=(SetupWebServer&& other) noexcept
{
if (this != &other) {
if (server_ != nullptr) {
httpd_stop(server_);
}
server_ = other.server_;
store_ = other.store_;
netState_ = other.netState_;
other.server_ = nullptr;
other.store_ = nullptr;
other.netState_ = NetState::Uninitialized;
gActiveServer = this;
}
return *this;
}
SetupWebServer::~SetupWebServer()
{
if (gActiveServer == this) {
gActiveServer = nullptr;
}
if (gStore == store_) {
gStore = nullptr;
}
if (server_ != nullptr) {
httpd_stop(server_);
server_ = nullptr;
}
}
std::expected<void, NetError> SetupWebServer::start(core::ISecureStore& store,
NetState netState)
{
if (server_ != nullptr) {
return {};
}
store_ = &store;
netState_ = netState;
gActiveServer = this;
gStore = &store;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 80;
config.lru_purge_enable = true;
if (httpd_start(&server_, &config) != ESP_OK) {
ESP_LOGE(kTag, "httpd_start failed");
gActiveServer = nullptr;
gStore = nullptr;
return std::unexpected(NetError::HttpServerStartFailed);
}
const httpd_uri_t healthUri = {
.uri = "/api/health",
.method = HTTP_GET,
.handler = healthGetHandler,
.user_ctx = nullptr,
};
httpd_register_uri_handler(server_, &healthUri);
const httpd_uri_t indexUri = {
.uri = "/",
.method = HTTP_GET,
.handler = indexGetHandler,
.user_ctx = nullptr,
};
httpd_register_uri_handler(server_, &indexUri);
const httpd_uri_t wifiUri = {
.uri = "/api/wifi",
.method = HTTP_POST,
.handler = wifiPostHandler,
.user_ctx = nullptr,
};
httpd_register_uri_handler(server_, &wifiUri);
ESP_LOGI(kTag, "HTTP server listening on port 80");
return {};
}
} // namespace net
@@ -0,0 +1,58 @@
/**
* @file SoftApConfig.cpp
* @brief SoftApConfig implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "net/SoftApConfig.hpp"
namespace net {
namespace {
constexpr std::string_view kSetupSsid = "DigiRadio-setup";
constexpr std::uint8_t kSetupChannel = 1;
constexpr std::uint8_t kSetupMaxConnections = 4;
} // namespace
SoftApConfig SoftApConfig::setupDefault()
{
return SoftApConfig(kSetupSsid, kSetupChannel, kSetupMaxConnections);
}
SoftApConfig::SoftApConfig(std::string_view ssid,
std::uint8_t channel,
std::uint8_t maxConnections)
: ssid_(ssid)
, channel_(channel)
, maxConnections_(maxConnections)
{
}
std::string_view SoftApConfig::ssid() const noexcept
{
return ssid_;
}
std::uint8_t SoftApConfig::channel() const noexcept
{
return channel_;
}
std::uint8_t SoftApConfig::maxConnections() const noexcept
{
return maxConnections_;
}
} // namespace net
+101
View File
@@ -0,0 +1,101 @@
/**
* @file SoftApHost.cpp
* @brief SoftApHost implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "net/SoftApHost.hpp"
#include "esp_wifi.h"
#include "esp_log.h"
#include <cstring>
namespace net {
namespace {
constexpr char kTag[] = "SoftApHost";
} // namespace
SoftApHost::SoftApHost(SoftApConfig config)
: config_(config)
, started_(false)
{
}
SoftApHost::~SoftApHost()
{
if (started_) {
esp_wifi_stop();
started_ = false;
}
}
SoftApHost::SoftApHost(SoftApHost&& other) noexcept
: config_(other.config_)
, started_(other.started_)
{
other.started_ = false;
}
SoftApHost& SoftApHost::operator=(SoftApHost&& other) noexcept
{
if (this != &other) {
if (started_) {
esp_wifi_stop();
}
config_ = other.config_;
started_ = other.started_;
other.started_ = false;
}
return *this;
}
std::expected<void, NetError> SoftApHost::start()
{
if (started_) {
return {};
}
if (esp_wifi_set_mode(WIFI_MODE_AP) != ESP_OK) {
ESP_LOGE(kTag, "esp_wifi_set_mode failed");
return std::unexpected(NetError::WifiConfigFailed);
}
wifi_config_t wifiCfg = {};
const std::string_view ssid = config_.ssid();
std::memcpy(wifiCfg.ap.ssid, ssid.data(), ssid.size());
wifiCfg.ap.ssid_len = static_cast<int>(ssid.size());
wifiCfg.ap.channel = config_.channel();
wifiCfg.ap.max_connection = config_.maxConnections();
wifiCfg.ap.authmode = WIFI_AUTH_OPEN;
if (esp_wifi_set_config(WIFI_IF_AP, &wifiCfg) != ESP_OK) {
ESP_LOGE(kTag, "esp_wifi_set_config failed");
return std::unexpected(NetError::WifiConfigFailed);
}
if (esp_wifi_start() != ESP_OK) {
ESP_LOGE(kTag, "esp_wifi_start failed");
return std::unexpected(NetError::WifiStartFailed);
}
started_ = true;
ESP_LOGI(kTag, "SoftAP started: %.*s", static_cast<int>(ssid.size()),
ssid.data());
return {};
}
} // namespace net
+183
View File
@@ -0,0 +1,183 @@
/**
* @file StaClient.cpp
* @brief StaClient implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "net/StaClient.hpp"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include <algorithm>
#include <cstring>
namespace net {
namespace {
constexpr char kTag[] = "StaClient";
constexpr int kConnectedBit = BIT0;
constexpr int kFailedBit = BIT1;
constexpr TickType_t kConnectTimeout = pdMS_TO_TICKS(30000);
EventGroupHandle_t s_wifiEventGroup = nullptr;
/**
* @brief wifiEventHandler — signal connect success or failure.
*
* @dname wifiEventHandler
* @param arg Unused.
* @param eventBase Event base identifier.
* @param eventId Specific event id.
* @param eventData Event payload.
* @pubstate sets bits on s_wifiEventGroup.
*
* @author Michele Bigi
* @date 2026-07-06
*/
void wifiEventHandler(void* arg,
esp_event_base_t eventBase,
int32_t eventId,
void* eventData)
{
(void)arg;
(void)eventData;
if (eventBase == WIFI_EVENT && eventId == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (eventBase == WIFI_EVENT
&& eventId == WIFI_EVENT_STA_DISCONNECTED) {
if (s_wifiEventGroup != nullptr) {
xEventGroupSetBits(s_wifiEventGroup, kFailedBit);
}
} else if (eventBase == IP_EVENT && eventId == IP_EVENT_STA_GOT_IP) {
if (s_wifiEventGroup != nullptr) {
xEventGroupSetBits(s_wifiEventGroup, kConnectedBit);
}
}
}
} // namespace
StaClient::StaClient()
: connected_(false)
{
}
StaClient::~StaClient()
{
if (connected_) {
esp_wifi_stop();
connected_ = false;
}
}
StaClient::StaClient(StaClient&& other) noexcept
: connected_(other.connected_)
{
other.connected_ = false;
}
StaClient& StaClient::operator=(StaClient&& other) noexcept
{
if (this != &other) {
if (connected_) {
esp_wifi_stop();
}
connected_ = other.connected_;
other.connected_ = false;
}
return *this;
}
std::expected<void, NetError>
StaClient::connect(const core::WifiCredentials& creds)
{
if (connected_) {
return {};
}
s_wifiEventGroup = xEventGroupCreate();
if (s_wifiEventGroup == nullptr) {
return std::unexpected(NetError::StaConnectFailed);
}
esp_event_handler_instance_t instanceAnyId = nullptr;
esp_event_handler_instance_t instanceGotIp = nullptr;
esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&wifiEventHandler,
nullptr,
&instanceAnyId);
esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&wifiEventHandler,
nullptr,
&instanceGotIp);
if (esp_wifi_set_mode(WIFI_MODE_STA) != ESP_OK) {
return std::unexpected(NetError::WifiConfigFailed);
}
wifi_config_t wifiCfg = {};
const std::string_view ssid = creds.ssid().value();
const std::size_t ssidCopy =
std::min(ssid.size(), sizeof(wifiCfg.sta.ssid) - 1);
std::memcpy(wifiCfg.sta.ssid, ssid.data(), ssidCopy);
creds.password().usePlaintext([&](std::string_view pwd) {
const std::size_t pwdCopy =
std::min(pwd.size(), sizeof(wifiCfg.sta.password) - 1);
std::memcpy(wifiCfg.sta.password, pwd.data(), pwdCopy);
});
if (esp_wifi_set_config(WIFI_IF_STA, &wifiCfg) != ESP_OK) {
return std::unexpected(NetError::WifiConfigFailed);
}
if (esp_wifi_start() != ESP_OK) {
return std::unexpected(NetError::WifiStartFailed);
}
const EventBits_t bits = xEventGroupWaitBits(s_wifiEventGroup,
kConnectedBit | kFailedBit,
pdTRUE,
pdFALSE,
kConnectTimeout);
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP,
instanceGotIp);
esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID,
instanceAnyId);
vEventGroupDelete(s_wifiEventGroup);
s_wifiEventGroup = nullptr;
if ((bits & kConnectedBit) != 0) {
connected_ = true;
ESP_LOGI(kTag, "connected to %.*s",
static_cast<int>(ssid.size()), ssid.data());
return {};
}
esp_wifi_stop();
ESP_LOGW(kTag, "STA connect timed out or failed");
if ((bits & kFailedBit) != 0) {
return std::unexpected(NetError::StaConnectFailed);
}
return std::unexpected(NetError::StaConnectTimeout);
}
} // namespace net