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
+13
View File
@@ -0,0 +1,13 @@
idf_component_register(
SRCS
"src/SoftApConfig.cpp"
"src/SoftApHost.cpp"
"src/StaClient.cpp"
"src/SetupWebServer.cpp"
"src/NetBootstrap.cpp"
INCLUDE_DIRS "include"
EMBED_FILES "www/index.html.gz"
REQUIRES core esp_wifi esp_netif esp_event nvs_flash esp_http_server
)
target_compile_features(${COMPONENT_LIB} PUBLIC cxx_std_23)
@@ -0,0 +1,122 @@
/**
* @file NetBootstrap.hpp
* @brief Owns network resources for setup or STA mode for app lifetime.
*
* 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
*/
#pragma once
#include "core/ISecureStore.hpp"
#include "net/NetError.hpp"
#include "net/NetState.hpp"
#include "net/SetupWebServer.hpp"
#include "net/SoftApHost.hpp"
#include "net/StaClient.hpp"
#include <expected>
#include <optional>
namespace net {
/**
* @brief NetBootstrap — brings up SoftAP or STA plus the HTTP server.
*
* @dname NetBootstrap
* @return n/a (type)
* @pubstate Owns optional softAp_, optional sta_, and webServer_. Must
* outlive app_main; keep one instance alive for process lifetime.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class NetBootstrap {
public:
/**
* @brief start — init platform and join stored Wi-Fi or open SoftAP.
*
* @dname start
* @param store Secure store consulted for saved STA credentials.
* @return NetBootstrap on success, or a NetError.
* @pubstate none
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] static std::expected<NetBootstrap, NetError>
start(core::ISecureStore& store);
NetBootstrap(const NetBootstrap&) = delete;
NetBootstrap& operator=(const NetBootstrap&) = delete;
/**
* @brief NetBootstrap — move-construct from a started bootstrap.
*
* @dname NetBootstrap
* @param other Source instance; left empty after the move.
* @pubstate transfers softAp_, sta_, and webServer_ from other.
*
* @author Michele Bigi
* @date 2026-07-06
*/
NetBootstrap(NetBootstrap&& other) noexcept = default;
/**
* @brief operator= — move-assign from a started bootstrap.
*
* @dname operator=
* @param other Source instance; left empty after the move.
* @return Reference to this instance.
* @pubstate transfers softAp_, sta_, and webServer_ from other.
*
* @author Michele Bigi
* @date 2026-07-06
*/
NetBootstrap& operator=(NetBootstrap&& other) noexcept = default;
/**
* @brief ~NetBootstrap — tear down network subsystems.
*
* @dname ~NetBootstrap
* @pubstate destroys softAp_, sta_, and webServer_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
~NetBootstrap() = default;
/**
* @brief state — read the active network phase.
*
* @dname state
* @return Current NetState.
* @pubstate reads state_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] NetState state() const noexcept;
private:
NetBootstrap(std::optional<SoftApHost> softAp,
std::optional<StaClient> sta,
SetupWebServer webServer,
NetState state);
std::optional<SoftApHost> softAp_;
std::optional<StaClient> sta_;
SetupWebServer webServer_;
NetState state_;
};
} // namespace net
@@ -0,0 +1,46 @@
/**
* @file NetError.hpp
* @brief Typed errors for network bootstrap operations.
*
* 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
*/
#pragma once
namespace net {
/**
* @brief NetError — failure causes for network bring-up.
*
* @dname NetError
* @return n/a (type)
* @pubstate n/a
*
* @author Michele Bigi
* @date 2026-07-06
*/
enum class NetError {
NvsInitFailed,
NetifInitFailed,
EventLoopFailed,
WifiInitFailed,
WifiConfigFailed,
WifiStartFailed,
HttpServerStartFailed,
StaConnectTimeout,
StaConnectFailed,
StoreSaveFailed,
CredentialsNotFound,
};
} // namespace net
@@ -0,0 +1,41 @@
/**
* @file NetState.hpp
* @brief Explicit network provisioning state machine.
*
* 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
*/
#pragma once
namespace net {
/**
* @brief NetState — coarse network provisioning phase.
*
* @dname NetState
* @return n/a (type)
* @pubstate n/a
*
* Slice 1 starts in SoftApSetup; Slice 2 adds STA join after provisioning.
*
* @author Michele Bigi
* @date 2026-07-06
*/
enum class NetState {
Uninitialized,
SoftApSetup,
StaConnecting,
StaConnected,
};
} // namespace net
@@ -0,0 +1,114 @@
/**
* @file SetupWebServer.hpp
* @brief HTTP server for setup UI, health, and Wi-Fi provisioning API.
*
* 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
*/
#pragma once
#include "core/ISecureStore.hpp"
#include "net/NetError.hpp"
#include "net/NetState.hpp"
#include <expected>
struct httpd_handle;
namespace net {
/**
* @brief SetupWebServer — setup UI, health, and Wi-Fi provisioning API.
*
* @dname SetupWebServer
* @return n/a (type)
* @pubstate Owns server_ and borrows store_ while running. Routes delegate
* JSON work to the pure core.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class SetupWebServer {
public:
/**
* @brief SetupWebServer — construct an unstarted server.
*
* @dname SetupWebServer
* @pubstate clears server_, store_, and netState_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
SetupWebServer();
/**
* @brief ~SetupWebServer — stop the HTTP server if running.
*
* @dname ~SetupWebServer
* @pubstate stops server_ when non-null.
*
* @author Michele Bigi
* @date 2026-07-06
*/
~SetupWebServer();
SetupWebServer(const SetupWebServer&) = delete;
SetupWebServer& operator=(const SetupWebServer&) = delete;
/**
* @brief SetupWebServer — move-construct, transferring the handle.
*
* @dname SetupWebServer
* @param other Source server; left stopped after the move.
* @pubstate takes ownership of other.server_ and copies store pointer.
*
* @author Michele Bigi
* @date 2026-07-06
*/
SetupWebServer(SetupWebServer&& other) noexcept;
/**
* @brief operator= — move-assign, transferring the handle.
*
* @dname operator=
* @param other Source server; left stopped after the move.
* @return Reference to this instance.
* @pubstate takes ownership of other.server_ and copies store pointer.
*
* @author Michele Bigi
* @date 2026-07-06
*/
SetupWebServer& operator=(SetupWebServer&& other) noexcept;
/**
* @brief start — register routes and listen on port 80.
*
* @dname start
* @param store Secure store for POST /api/wifi persistence.
* @param netState Active network phase exposed to handlers.
* @return Ok on success, or NetError::HttpServerStartFailed.
* @pubstate writes server_, store_, and netState_ on success.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<void, NetError> start(core::ISecureStore& store,
NetState netState);
private:
httpd_handle* server_;
core::ISecureStore* store_;
NetState netState_;
};
} // namespace net
@@ -0,0 +1,98 @@
/**
* @file SoftApConfig.hpp
* @brief Configuration value type for the setup SoftAP.
*
* 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
*/
#pragma once
#include <cstdint>
#include <string_view>
namespace net {
/**
* @brief SoftApConfig — immutable SoftAP parameters for first-time setup.
*
* @dname SoftApConfig
* @param ssid Broadcast SSID (non-empty).
* @param channel Wi-Fi channel (113).
* @param maxConnections Maximum associated stations.
* @return n/a (type)
* @pubstate Owns no handles; pure configuration snapshot.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class SoftApConfig {
public:
/**
* @brief setupDefault — factory for the Slice 1 setup SoftAP.
*
* @dname setupDefault
* @return SoftApConfig with SSID DigiRadio-setup.
* @pubstate none
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] static SoftApConfig setupDefault();
/**
* @brief ssid — read the broadcast SSID.
*
* @dname ssid
* @return SSID string view.
* @pubstate reads ssid_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::string_view ssid() const noexcept;
/**
* @brief channel — read the Wi-Fi channel.
*
* @dname channel
* @return Channel number.
* @pubstate reads channel_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::uint8_t channel() const noexcept;
/**
* @brief maxConnections — read the station limit.
*
* @dname maxConnections
* @return Maximum associated clients.
* @pubstate reads maxConnections_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::uint8_t maxConnections() const noexcept;
private:
SoftApConfig(std::string_view ssid,
std::uint8_t channel,
std::uint8_t maxConnections);
std::string_view ssid_;
std::uint8_t channel_;
std::uint8_t maxConnections_;
};
} // namespace net
@@ -0,0 +1,111 @@
/**
* @file SoftApHost.hpp
* @brief RAII wrapper that brings up an ESP32 SoftAP.
*
* 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
*/
#pragma once
#include "net/NetError.hpp"
#include "net/SoftApConfig.hpp"
#include <expected>
namespace net {
/**
* @brief SoftApHost — owns SoftAP lifecycle on the ESP32 Wi-Fi stack.
*
* @dname SoftApHost
* @param config SoftAP parameters applied on start().
* @return n/a (type)
* @pubstate Owns started_ (whether Wi-Fi AP is running). Stops AP in the
* destructor when started.
*
* Imperative shell: wraps ESP-IDF Wi-Fi calls; no business logic.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class SoftApHost {
public:
/**
* @brief SoftApHost — construct with configuration to apply on start.
*
* @dname SoftApHost
* @param config SoftAP parameters.
* @pubstate writes config_, clears started_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
explicit SoftApHost(SoftApConfig config);
/**
* @brief ~SoftApHost — stop the SoftAP if running.
*
* @dname ~SoftApHost
* @pubstate stops AP when started_ is true.
*
* @author Michele Bigi
* @date 2026-07-06
*/
~SoftApHost();
SoftApHost(const SoftApHost&) = delete;
SoftApHost& operator=(const SoftApHost&) = delete;
/**
* @brief SoftApHost — move-construct, transferring started state.
*
* @dname SoftApHost
* @param other Source host; left stopped after the move.
* @pubstate transfers config_ and started_ from other.
*
* @author Michele Bigi
* @date 2026-07-06
*/
SoftApHost(SoftApHost&& other) noexcept;
/**
* @brief operator= — move-assign, transferring started state.
*
* @dname operator=
* @param other Source host; left stopped after the move.
* @return Reference to this instance.
* @pubstate transfers config_ and started_ from other.
*
* @author Michele Bigi
* @date 2026-07-06
*/
SoftApHost& operator=(SoftApHost&& other) noexcept;
/**
* @brief start — bring up the configured SoftAP.
*
* @dname start
* @return Ok on success, or a NetError describing the failure.
* @pubstate writes started_ on success; uses config_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<void, NetError> start();
private:
SoftApConfig config_;
bool started_;
};
} // namespace net
@@ -0,0 +1,109 @@
/**
* @file StaClient.hpp
* @brief RAII helper that joins a Wi-Fi network in STA mode.
*
* 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
*/
#pragma once
#include "core/WifiCredentials.hpp"
#include "net/NetError.hpp"
#include <expected>
namespace net {
/**
* @brief StaClient — connects the ESP32 to a stored Wi-Fi network.
*
* @dname StaClient
* @return n/a (type)
* @pubstate Owns connected_ (whether STA link + IP are up). Assumes
* esp_wifi_init() was already called by NetBootstrap.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class StaClient {
public:
/**
* @brief StaClient — construct an unconnected STA client.
*
* @dname StaClient
* @pubstate clears connected_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
StaClient();
/**
* @brief ~StaClient — disconnect STA if connected.
*
* @dname ~StaClient
* @pubstate stops Wi-Fi when connected_ is true.
*
* @author Michele Bigi
* @date 2026-07-06
*/
~StaClient();
StaClient(const StaClient&) = delete;
StaClient& operator=(const StaClient&) = delete;
/**
* @brief StaClient — move-construct, transferring connection state.
*
* @dname StaClient
* @param other Source client; left disconnected after the move.
* @pubstate transfers connected_ from other.
*
* @author Michele Bigi
* @date 2026-07-06
*/
StaClient(StaClient&& other) noexcept;
/**
* @brief operator= — move-assign, transferring connection state.
*
* @dname operator=
* @param other Source client; left disconnected after the move.
* @return Reference to this instance.
* @pubstate transfers connected_ from other.
*
* @author Michele Bigi
* @date 2026-07-06
*/
StaClient& operator=(StaClient&& other) noexcept;
/**
* @brief connect — join the network described by creds.
*
* @dname connect
* @param creds Validated domain credentials from ISecureStore.
* @return Ok on success, or NetError::StaConnectTimeout /
* NetError::StaConnectFailed.
* @pubstate writes connected_ on success; uses creds via Secret.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<void, NetError>
connect(const core::WifiCredentials& creds);
private:
bool connected_;
};
} // namespace net
@@ -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
+162
View File
@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DigiRadio Setup</title>
<style>
:root {
--space-1: 0.5rem;
--space-2: 1rem;
--space-3: 1.5rem;
--space-4: 2.5rem;
--text-base: 1rem;
--text-lg: 1.25rem;
--text-xl: 1.75rem;
--accent: #c47a2c;
--bg: #0f1114;
--surface: #1a1d22;
--text: #e8eaed;
--muted: #9aa0a6;
--radius: 0.5rem;
--font: system-ui, -apple-system, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--font);
font-size: var(--text-base);
line-height: 1.5;
background: var(--bg);
color: var(--text);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-3);
}
main {
background: var(--surface);
border-radius: var(--radius);
padding: var(--space-4);
max-width: 28rem;
width: 100%;
border-top: 3px solid var(--accent);
}
h1 { font-size: var(--text-xl); font-weight: 600; margin-bottom: var(--space-2); }
p { color: var(--muted); margin-bottom: var(--space-3); }
label {
display: block;
font-size: 0.875rem;
color: var(--muted);
margin-bottom: var(--space-1);
}
input {
width: 100%;
padding: var(--space-1) var(--space-2);
margin-bottom: var(--space-2);
border: 1px solid #333;
border-radius: var(--radius);
background: var(--bg);
color: var(--text);
font: inherit;
}
button {
width: 100%;
padding: var(--space-2);
border: none;
border-radius: var(--radius);
background: var(--accent);
color: var(--bg);
font: inherit;
font-weight: 600;
cursor: pointer;
}
button:disabled { opacity: 0.6; cursor: wait; }
.status {
display: flex;
align-items: center;
gap: var(--space-1);
font-size: var(--text-lg);
margin-bottom: var(--space-3);
}
.dot {
width: 0.6rem;
height: 0.6rem;
border-radius: 50%;
background: var(--accent);
}
.msg { font-size: 0.875rem; margin-top: var(--space-2); min-height: 1.25rem; }
.msg.ok { color: #7cb342; }
.msg.err { color: #e57373; }
code {
font-size: 0.9em;
background: var(--bg);
padding: 0.1em 0.35em;
border-radius: 0.25rem;
}
</style>
</head>
<body>
<main>
<h1>DigiRadio</h1>
<p>Connect this radio to your WiFi network.</p>
<div class="status" id="health">
<span class="dot" aria-hidden="true"></span>
<span>Checking health…</span>
</div>
<form id="wifi-form">
<label for="ssid">Network name (SSID)</label>
<input id="ssid" name="ssid" autocomplete="off" required maxlength="32">
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="off" maxlength="63">
<button type="submit" id="save-btn">Save &amp; connect</button>
</form>
<p class="msg" id="msg" aria-live="polite"></p>
</main>
<script>
fetch("/api/health")
.then(function (r) { return r.json(); })
.then(function (d) {
document.getElementById("health").innerHTML =
'<span class="dot"></span><span>Status: <code>' +
d.status + "</code> · FW <code>" + d.fw + "</code></span>";
})
.catch(function () {
document.getElementById("health").textContent = "Health check failed.";
});
document.getElementById("wifi-form").addEventListener("submit", function (e) {
e.preventDefault();
var btn = document.getElementById("save-btn");
var msg = document.getElementById("msg");
btn.disabled = true;
msg.textContent = "Saving…";
msg.className = "msg";
fetch("/api/wifi", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
ssid: document.getElementById("ssid").value,
password: document.getElementById("password").value
})
})
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (res) {
if (res.ok && res.d.status === "saved") {
msg.textContent = "Saved. Rebooting in " + res.d.reboot_in_sec + "s…";
msg.className = "msg ok";
} else {
msg.textContent = "Error: " + (res.d.reason || "unknown");
msg.className = "msg err";
btn.disabled = false;
}
})
.catch(function () {
msg.textContent = "Request failed.";
msg.className = "msg err";
btn.disabled = false;
});
});
</script>
</body>
</html>
Binary file not shown.