feat(m1): hardware status firmware with wifi web provisioning

Add the M1 milestone tree under poc/ (m1_hardware + poc_a apps,
shared common components, evidence schema). Merges the plan's
'm1 baseline+fixes' and 'wifi provisioning' batches: the poc/ tree is
entirely untracked and both concerns share files.

M1 hardware baseline:
- landscape ST7305 RIP display via LVGL I1 driver
- TF-card status log: JSONL telemetry with CRC32C per line; append
  buffer widened to line[640] after the 512-byte truncation defect
  (payload ~550B with real values) was root-caused on-device
- PCF85063 RTC read, SHTC3 temperature/humidity with plausibility
  checks, KEY input with short/long/portal press thresholds
- boot-time partition identity check and M1-002 boot record fields
  (device_id, image_sha256, reset_reason, services status)

WiFi web provisioning:
- softAP portal Frame-Setup-xxxx with HTTP endpoints /scan, /connect,
  /clear; httpd handlers never call httpd_stop (deadlock hazard) — a
  1s monitor task executes stop/start/connect actions
- credentials persist to system_fs wifi.json (littlefs) per the
  SEC-010 development exception (plaintext, documented in _doc)
- fallback: 5 disconnects without IP or 60s no-IP -> stop retry,
  portal returns; GOT_IP tears the AP down
- KEY >=3s hold requests the portal; prov start/stop/status console
  commands; ap_active/ap_mode_requested surfaces in status JSON/text

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <[email protected]>
This commit is contained in:
2026-08-31 08:01:37 +08:00
co-authored by Sisyphus
parent e71bcce56e
commit 5f7c60c899
37 changed files with 3903 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.25)
set(FRAME_REQUIRED_IDF_TAG "v6.0.2" CACHE STRING
"Exact ESP-IDF release tag required by the architecture")
set(FRAME_REQUIRED_IDF_COMMIT "7101770dc6db2667b3c477cc31365dd1acd6db4e" CACHE STRING
"Exact ESP-IDF commit required by the architecture")
set(FRAME_REQUIRED_COMPILER_VERSION "15.2.0" CACHE STRING
"Exact Xtensa GCC version required by the architecture")
include("${CMAKE_CURRENT_LIST_DIR}/../../../cmake/FramePlatform.cmake")
frame_require_esp_idf("${FRAME_REQUIRED_IDF_TAG}")
if(NOT DEFINED SDKCONFIG)
set(SDKCONFIG "${CMAKE_BINARY_DIR}/sdkconfig")
endif()
if(NOT DEFINED SDKCONFIG_DEFAULTS)
set(SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
endif()
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(frame_m1_hardware)
frame_verify_platform("${FRAME_REQUIRED_IDF_COMMIT}" "${FRAME_REQUIRED_COMPILER_VERSION}")
idf_build_set_property(CXX_COMPILE_OPTIONS "-std=c++26" APPEND)
+28
View File
@@ -0,0 +1,28 @@
{
"version": 3,
"cmakeMinimumRequired": {
"major": 3,
"minor": 25,
"patch": 0
},
"configurePresets": [
{
"name": "default",
"displayName": "Frame M1 hardware",
"description": "ESP-IDF v6.0.2 Waveshare ESP32-S3-RLCD-4.2 hardware baseline",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/default",
"cacheVariables": {
"IDF_TARGET": "esp32s3",
"SDKCONFIG": "${sourceDir}/build/default/sdkconfig",
"SDKCONFIG_DEFAULTS": "${sourceDir}/sdkconfig.defaults"
}
}
],
"buildPresets": [
{
"name": "default",
"configurePreset": "default"
}
]
}
+51
View File
@@ -0,0 +1,51 @@
# Frame M1 Hardware Firmware
This isolated ESP-IDF application implements the `0.1.0-dev.1` hardware-status vertical slice for
the Waveshare ESP32-S3-RLCD-4.2 N16R8 board. It does not load dynamic plugins.
It checks the ESP32-S3 target, 16 MiB flash, 8 MiB PSRAM, ST7305 display, shared I2C RTC/SHTC3,
active-low KEY, SDMMC TF card transitions, Wi-Fi STA configuration with softAP web provisioning,
native landscape 400x300 display output, and USB Serial/JTAG console output.
Wi-Fi provisioning persists the last credentials as plaintext JSON at `/system/wifi.json` on the
internal `system_fs` partition. This is a user-approved development-board exception (SEC-010,
recorded in `_doc/requirements-v4.2.md` under M1-007): ESP-IDF v6.0.2 requires Flash Encryption or
an HMAC eFuse key to protect NVS encryption keys, and both provisioning steps are irreversible on
the single development board. Production boards must switch to NVS-encrypted credential storage
before shipping. The password never appears in UART output, logs, or status.
On boot the device auto-connects with the saved credentials. When no valid configuration exists, or
after 5 disconnects without an IP address or 60 seconds without obtaining one, it starts an open
setup hotspot `Frame-Setup-XXXX` at `192.168.4.1`. The portal's network list is populated from a
live scan; hidden networks cannot be typed into the browser form — configure those through the
console with `wifi set <ssid> hidden`. Holding KEY for 3 seconds or longer also requests the setup
hotspot; such a hold is a portal command and does not count as a button press.
Build with the exact IDF tag:
```sh
. "$IDF_PATH/export.sh"
cmake --preset default --fresh
cmake --build --preset default
```
The console is available through USB Serial/JTAG at 115200 baud. Useful commands:
```text
status [--json]
wifi set <ssid> [hidden]
wifi clear
wifi reconnect
wifi status
prov status
prov start
prov scan
storage probe
storage status
selftest
```
Do not place real credentials in command transcripts or committed evidence. `wifi set` asks for the
password after parsing the command so it is not stored in command history; terminal software must
also keep local echo disabled. The password is persisted only inside `/system/wifi.json` under the
SEC-010 development-board exception and is never echoed back.
+40
View File
@@ -0,0 +1,40 @@
dependencies:
espressif/cjson:
component_hash: e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.7.19~2
idf:
source:
type: idf
version: 6.0.2
joltwallet/littlefs:
component_hash: 3af20a3d75c49db9dc2286fd50862c34055c9f578419ad1f2bf7ed3ed01391fe
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.22.3
lvgl/lvgl:
component_hash: 17e68bfd21f0edf4c3ee838e2273da840bf3930e5dbc3bfa6c1190c3aed41f9f
dependencies: []
source:
registry_url: https://components.espressif.com/
type: service
version: 9.4.0
direct_dependencies:
- espressif/cjson
- idf
- joltwallet/littlefs
- lvgl/lvgl
manifest_hash: 6219a03b210d777e4f2e375ace42de6b65241330ad685425df38db111f0db7fb
target: esp32s3
version: 3.0.0
+51
View File
@@ -0,0 +1,51 @@
idf_component_register(
SRCS
"app_main.cc"
"board_service.cc"
"console_service.cc"
"display_service.cc"
"hardware_status.cc"
"sd_service.cc"
"st7305_panel.cc"
"status_log.cc"
"wifi_provision.cc"
"wifi_service.cc"
INCLUDE_DIRS "."
REQUIRES
app_update
cjson
console
esp_driver_gpio
esp_driver_i2c
esp_driver_sdmmc
esp_driver_spi
esp_event
esp_http_server
esp_hw_support
esp_lcd
esp_netif
esp_psram
esp_timer
esp_wifi
fatfs
littlefs
lvgl
mbedtls
nvs_flash
spi_flash
)
target_compile_options(${COMPONENT_LIB} PRIVATE
-std=c++26
-Wall
-Wextra
-Wconversion
-Werror=return-type
-fno-exceptions
-fno-rtti
-fno-unwind-tables
)
target_compile_definitions(${COMPONENT_LIB} PRIVATE
FRAME_TOOLCHAIN_VERSION="gcc-${CMAKE_CXX_COMPILER_VERSION}"
)
+62
View File
@@ -0,0 +1,62 @@
#include "board_config.hh"
#include "board_service.hh"
#include "console_service.hh"
#include "display_service.hh"
#include "esp_log.h"
#include "hardware_status.hh"
#include "nvs_flash.h"
#include "sd_service.hh"
#include "wifi_provision.hh"
#include "wifi_service.hh"
#include <cinttypes>
namespace {
constexpr char kTag[] = "frame-m1";
} // namespace
extern "C" void app_main(void) {
using namespace frame::m1;
static hardware_status status;
status.initialize_platform();
const status_snapshot initial = status.snapshot();
ESP_LOGI(kTag, "Frame M1 %s; IDF %s; toolchain %s", board::kFirmwareVersion,
initial.idf_version, initial.toolchain_version);
ESP_LOGI(kTag, "board=%s module=%s device=%s", board::kProduct, board::kModule,
initial.device_id);
ESP_LOGI(kTag,
"cores=%" PRIu32 " flash=%u psram=%u part=%s reset=%" PRIu32 " image_sha256=%.16s",
initial.cpu_cores, static_cast<unsigned>(initial.flash_bytes),
static_cast<unsigned>(initial.psram_bytes), initial.partitions_ok ? "OK" : "FAIL",
initial.reset_reason, initial.image_sha256);
const esp_err_t nvs_result = nvs_flash_init();
if (nvs_result != ESP_OK) {
ESP_LOGW(kTag, "NVS unavailable; Wi-Fi credentials will remain RAM-only: %s",
esp_err_to_name(nvs_result));
}
static board_service board(status);
static sd_service storage(status);
static wifi_service wifi(status);
static wifi_provision provision(status, wifi);
static display_service display(status);
static console_service console(status, storage, wifi, provision);
const esp_err_t board_result = board.start();
const esp_err_t storage_result = storage.start();
const esp_err_t provision_mount_result = provision.initialize();
const esp_err_t wifi_result = wifi.initialize();
const esp_err_t display_result = display.start();
const esp_err_t console_result = console.start();
const esp_err_t saved_result = provision.start_saved_or_pending();
ESP_LOGI(kTag, "services board=%s storage=%s wifi=%s display=%s console=%s",
esp_err_to_name(board_result), esp_err_to_name(storage_result),
esp_err_to_name(wifi_result), esp_err_to_name(display_result),
esp_err_to_name(console_result));
ESP_LOGI(kTag, "provision mount=%s saved=%s", esp_err_to_name(provision_mount_result),
esp_err_to_name(saved_result));
}
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "driver/gpio.h"
#include "driver/i2c_types.h"
#include "driver/spi_master.h"
namespace frame::m1::board {
inline constexpr char kProduct[] = "Waveshare ESP32-S3-RLCD-4.2";
inline constexpr char kModule[] = "ESP32-S3-WROOM-1-N16R8";
inline constexpr char kFirmwareVersion[] = "0.1.0-dev.1";
inline constexpr char kIdfTag[] = "v6.0.2";
inline constexpr std::size_t kFlashBytes = 16U * 1024U * 1024U;
inline constexpr std::size_t kPsramBytes = 8U * 1024U * 1024U;
inline constexpr int kDisplayWidth = 400;
inline constexpr int kDisplayHeight = 300;
inline constexpr std::size_t kDisplayBufferBytes =
static_cast<std::size_t>(kDisplayWidth) * static_cast<std::size_t>(kDisplayHeight) / 8U;
inline constexpr spi_host_device_t kDisplayHost = SPI3_HOST;
inline constexpr int kDisplayClockHz = 10 * 1000 * 1000;
inline constexpr gpio_num_t kDisplaySck = GPIO_NUM_11;
inline constexpr gpio_num_t kDisplayMosi = GPIO_NUM_12;
inline constexpr gpio_num_t kDisplayDc = GPIO_NUM_5;
inline constexpr gpio_num_t kDisplayCs = GPIO_NUM_40;
inline constexpr gpio_num_t kDisplayReset = GPIO_NUM_41;
inline constexpr gpio_num_t kDisplayTe = GPIO_NUM_6;
inline constexpr i2c_port_num_t kI2cPort = I2C_NUM_0;
inline constexpr gpio_num_t kI2cSda = GPIO_NUM_13;
inline constexpr gpio_num_t kI2cScl = GPIO_NUM_14;
inline constexpr uint16_t kRtcAddress = 0x51;
inline constexpr uint16_t kSensorAddress = 0x70;
inline constexpr gpio_num_t kKey = GPIO_NUM_18;
inline constexpr gpio_num_t kSdClock = GPIO_NUM_38;
inline constexpr gpio_num_t kSdCommand = GPIO_NUM_21;
inline constexpr gpio_num_t kSdData0 = GPIO_NUM_39;
inline constexpr char kSdMount[] = "/frame";
} // namespace frame::m1::board
+267
View File
@@ -0,0 +1,267 @@
#include "board_service.hh"
#include "board_config.hh"
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_timer.h"
namespace frame::m1 {
namespace {
constexpr char kTag[] = "frame-board";
constexpr uint16_t kSensorWake = 0x3517;
constexpr uint16_t kSensorMeasure = 0x7866;
constexpr uint16_t kSensorSleep = 0xB098;
constexpr uint8_t kRtcSecondsRegister = 0x04;
// KEY release bands: <1s short press, 1s..<3s long press, >=3s provisioning portal command.
constexpr int64_t kKeyLongPressUs = 1000000;
constexpr int64_t kKeyPortalHoldUs = 3000000;
// Days offset from 1970-01-01 (Howard Hinnant, public domain); avoids libc timegm portability.
int64_t days_from_civil(int64_t year, unsigned month, unsigned day) {
year -= month <= 2;
const int64_t era = (year >= 0 ? year : year - 399) / 400;
const unsigned yoe = static_cast<unsigned>(year - era * 400);
const unsigned doy = (153U * (month + (month > 2 ? -3U : 9U)) + 2U) / 5U + day - 1U;
const unsigned doe = yoe * 365U + yoe / 4U - yoe / 100U + doy;
return era * 146097LL + static_cast<int64_t>(doe) - 719468LL;
}
uint8_t from_bcd(uint8_t value) {
return static_cast<uint8_t>((value >> 4U) * 10U + (value & 0x0FU));
}
} // namespace
board_service::~board_service() {
if (sensor_ != nullptr) {
i2c_master_bus_rm_device(sensor_);
}
if (rtc_ != nullptr) {
i2c_master_bus_rm_device(rtc_);
}
if (bus_ != nullptr) {
i2c_del_master_bus(bus_);
}
}
esp_err_t board_service::start() {
gpio_config_t key_config{};
key_config.pin_bit_mask = UINT64_C(1) << board::kKey;
key_config.mode = GPIO_MODE_INPUT;
key_config.pull_up_en = GPIO_PULLUP_ENABLE;
key_config.intr_type = GPIO_INTR_DISABLE;
esp_err_t result = gpio_config(&key_config);
if (result != ESP_OK) {
return result;
}
result = initialize_i2c();
status_.update([&](status_snapshot& value) { value.board_error = result; });
if (result != ESP_OK) {
return result;
}
const BaseType_t created = xTaskCreatePinnedToCore(&board_service::task_entry, "frame-board",
4096, this, 8, &task_, 0);
return created == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
void board_service::task_entry(void* context) { static_cast<board_service*>(context)->run(); }
uint8_t board_service::crc8(const uint8_t* data, std::size_t size) {
uint8_t crc = 0xFF;
for (std::size_t index = 0; index < size; ++index) {
crc ^= data[index];
for (int bit = 0; bit < 8; ++bit) {
crc = (crc & 0x80U) != 0U ? static_cast<uint8_t>((crc << 1U) ^ 0x31U)
: static_cast<uint8_t>(crc << 1U);
}
}
return crc;
}
esp_err_t board_service::initialize_i2c() {
i2c_master_bus_config_t bus_config{};
bus_config.i2c_port = board::kI2cPort;
bus_config.sda_io_num = board::kI2cSda;
bus_config.scl_io_num = board::kI2cScl;
bus_config.clk_source = I2C_CLK_SRC_DEFAULT;
bus_config.glitch_ignore_cnt = 7;
bus_config.flags.enable_internal_pullup = true;
esp_err_t result = i2c_new_master_bus(&bus_config, &bus_);
if (result != ESP_OK) {
return result;
}
const bool rtc_present = i2c_master_probe(bus_, board::kRtcAddress, 100) == ESP_OK;
const bool sensor_present = i2c_master_probe(bus_, board::kSensorAddress, 100) == ESP_OK;
status_.update([&](status_snapshot& value) {
value.rtc_present = rtc_present;
value.sensor_present = sensor_present;
});
if (rtc_present) {
i2c_device_config_t rtc_config{};
rtc_config.dev_addr_length = I2C_ADDR_BIT_LEN_7;
rtc_config.device_address = board::kRtcAddress;
rtc_config.scl_speed_hz = 400000;
const esp_err_t rtc_result = i2c_master_bus_add_device(bus_, &rtc_config, &rtc_);
if (rtc_result != ESP_OK) {
return rtc_result;
}
}
if (!sensor_present) {
return rtc_present ? ESP_ERR_NOT_FOUND : ESP_FAIL;
}
i2c_device_config_t sensor_config{};
sensor_config.dev_addr_length = I2C_ADDR_BIT_LEN_7;
sensor_config.device_address = board::kSensorAddress;
sensor_config.scl_speed_hz = 400000;
return i2c_master_bus_add_device(bus_, &sensor_config, &sensor_);
}
esp_err_t board_service::send_sensor_sleep() {
const uint8_t sleep[]{static_cast<uint8_t>(kSensorSleep >> 8U),
static_cast<uint8_t>(kSensorSleep)};
return i2c_master_transmit(sensor_, sleep, sizeof(sleep), 100);
}
esp_err_t board_service::read_rtc() {
if (rtc_ == nullptr) {
return ESP_ERR_NOT_FOUND;
}
uint8_t registers[7]{};
esp_err_t result = i2c_master_transmit(rtc_, &kRtcSecondsRegister, 1, 100);
if (result == ESP_OK) {
result = i2c_master_receive(rtc_, registers, sizeof(registers), 100);
}
if (result != ESP_OK) {
status_.update([](status_snapshot& value) { value.rtc.valid = false; });
return result;
}
const unsigned second = from_bcd(registers[0] & 0x7FU);
const bool oscillator_stopped = (registers[0] & 0x80U) != 0U;
const unsigned minute = from_bcd(registers[1] & 0x7FU);
const unsigned hour = from_bcd(registers[2] & 0x3FU);
const unsigned day = from_bcd(registers[3] & 0x3FU);
const unsigned month = from_bcd(registers[5] & 0x1FU);
const int64_t year = 2000 + from_bcd(registers[6]);
const bool plausible = !oscillator_stopped && second < 60 && minute < 60 && hour < 24 &&
day >= 1 && day <= 31 && month >= 1 && month <= 12 && year <= 2099;
const int64_t unix_seconds = days_from_civil(year, month, day) * 86400LL +
static_cast<int64_t>(hour) * 3600LL +
static_cast<int64_t>(minute) * 60LL + static_cast<int64_t>(second);
const bool valid = plausible && unix_seconds > 0;
status_.update([&](status_snapshot& value) {
value.rtc = {.unix_seconds = valid ? unix_seconds : 0,
.valid = valid,
.read_at_us = esp_timer_get_time()};
});
return valid ? ESP_OK : ESP_ERR_INVALID_CRC;
}
esp_err_t board_service::sample_sensor() {
const uint8_t wake[]{static_cast<uint8_t>(kSensorWake >> 8U),
static_cast<uint8_t>(kSensorWake)};
esp_err_t result = i2c_master_transmit(sensor_, wake, sizeof(wake), 100);
if (result != ESP_OK) {
return result;
}
vTaskDelay(pdMS_TO_TICKS(1));
const uint8_t measure[]{static_cast<uint8_t>(kSensorMeasure >> 8U),
static_cast<uint8_t>(kSensorMeasure)};
result = i2c_master_transmit(sensor_, measure, sizeof(measure), 100);
if (result != ESP_OK) {
send_sensor_sleep();
return result;
}
vTaskDelay(pdMS_TO_TICKS(20));
uint8_t data[6]{};
result = i2c_master_receive(sensor_, data, sizeof(data), 100);
if (result == ESP_OK && (crc8(data, 2) != data[2] || crc8(data + 3, 2) != data[5])) {
result = ESP_ERR_INVALID_CRC;
}
if (result == ESP_OK) {
const uint16_t raw_temperature = static_cast<uint16_t>(data[0] << 8U) | data[1];
const uint16_t raw_humidity = static_cast<uint16_t>(data[3] << 8U) | data[4];
const int32_t temperature =
-450 + static_cast<int32_t>((1750LL * raw_temperature) / 65536LL);
const uint32_t humidity = static_cast<uint32_t>((1000ULL * raw_humidity) / 65536ULL);
if (temperature < -400 || temperature > 1250 || humidity > 1000) {
result = ESP_ERR_INVALID_RESPONSE;
}
if (result == ESP_OK) {
status_.update([&](status_snapshot& value) {
value.sensor = {
.temperature_tenths_celsius = static_cast<int16_t>(temperature),
.humidity_tenths_percent = static_cast<uint16_t>(humidity),
.valid = true,
.sampled_at_us = esp_timer_get_time(),
};
});
}
}
send_sensor_sleep();
return result;
}
void board_service::run() {
bool last_pressed = gpio_get_level(board::kKey) == 0;
bool stable_pressed = last_pressed;
int64_t changed_at = esp_timer_get_time();
int64_t pressed_at = stable_pressed ? changed_at : 0;
int64_t next_sensor_at = 0;
while (true) {
const int64_t now = esp_timer_get_time();
const bool pressed = gpio_get_level(board::kKey) == 0;
if (pressed != last_pressed) {
last_pressed = pressed;
changed_at = now;
}
if (pressed != stable_pressed && now - changed_at >= 30000) {
stable_pressed = pressed;
if (pressed) {
pressed_at = now;
} else if (pressed_at != 0) {
const int64_t held_us = now - pressed_at;
status_.update([&](status_snapshot& value) {
value.key_pressed = false;
if (held_us >= kKeyPortalHoldUs) {
value.ap_mode_requested = true;
} else if (held_us >= kKeyLongPressUs) {
++value.key_long_presses;
} else {
++value.key_short_presses;
}
});
pressed_at = 0;
}
if (pressed) {
status_.update([](status_snapshot& value) { value.key_pressed = true; });
}
}
if (now >= next_sensor_at) {
const esp_err_t sensor_result = sample_sensor();
if (sensor_result != ESP_OK) {
ESP_LOGW(kTag, "SHTC3 sample failed: %s", esp_err_to_name(sensor_result));
status_.update([](status_snapshot& value) { value.sensor.valid = false; });
}
const esp_err_t rtc_result = read_rtc();
if (rtc_result != ESP_OK) {
ESP_LOGW(kTag, "PCF85063 read failed: %s", esp_err_to_name(rtc_result));
}
next_sensor_at = now + 10LL * 1000LL * 1000LL;
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}
} // namespace frame::m1
@@ -0,0 +1,38 @@
#pragma once
#include "driver/i2c_master.h"
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "hardware_status.hh"
namespace frame::m1 {
class board_service {
public:
explicit board_service(hardware_status& status) : status_(status) {}
~board_service();
board_service(const board_service&) = delete;
board_service& operator=(const board_service&) = delete;
esp_err_t start();
private:
static void task_entry(void* context);
static uint8_t crc8(const uint8_t* data, std::size_t size);
esp_err_t initialize_i2c();
esp_err_t sample_sensor();
esp_err_t send_sensor_sleep();
esp_err_t read_rtc();
void run();
hardware_status& status_;
i2c_master_bus_handle_t bus_{};
i2c_master_dev_handle_t sensor_{};
i2c_master_dev_handle_t rtc_{};
TaskHandle_t task_{};
};
} // namespace frame::m1
@@ -0,0 +1,322 @@
#include "console_service.hh"
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <ctime>
#include "board_config.hh"
#include "esp_console.h"
#include "linenoise/linenoise.h"
namespace frame::m1 {
namespace {
constexpr char kSelftestSsid[] = "frame-selftest";
constexpr char kSelftestPassword[] = "frame-selftest-pass";
} // namespace
esp_err_t console_service::start() {
if (instance_ != nullptr) {
return ESP_ERR_INVALID_STATE;
}
instance_ = this;
const esp_console_cmd_t status_cmd{
.command = "status",
.help = "Show Frame M1 status; add --json for machine output",
.hint = nullptr,
.func = &console_service::status_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
const esp_console_cmd_t wifi_cmd{
.command = "wifi",
.help = "wifi set <ssid> [hidden] | wifi clear | wifi reconnect | wifi status; "
"provisioning: prov status | prov start | prov scan",
.hint = nullptr,
.func = &console_service::wifi_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
const esp_console_cmd_t prov_cmd{
.command = "prov",
.help = "prov status | prov start | prov scan",
.hint = nullptr,
.func = &console_service::prov_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
const esp_console_cmd_t storage_cmd{
.command = "storage",
.help = "storage probe | storage status",
.hint = nullptr,
.func = &console_service::storage_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
const esp_console_cmd_t selftest_cmd{
.command = "selftest",
.help = "Run the safe M1 status self-test",
.hint = nullptr,
.func = &console_service::selftest_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
esp_err_t result = esp_console_cmd_register(&status_cmd);
if (result == ESP_OK) {
result = esp_console_cmd_register(&wifi_cmd);
}
if (result == ESP_OK) {
result = esp_console_cmd_register(&prov_cmd);
}
if (result == ESP_OK) {
result = esp_console_cmd_register(&storage_cmd);
}
if (result == ESP_OK) {
result = esp_console_cmd_register(&selftest_cmd);
}
if (result != ESP_OK) {
return result;
}
linenoiseSetDumbMode(1);
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
repl_config.prompt = "frame> ";
repl_config.max_cmdline_length = 160;
repl_config.max_cmdline_args = 8;
repl_config.task_stack_size = 6144;
repl_config.task_priority = 5;
repl_config.task_core_id = 1;
esp_console_dev_usb_serial_jtag_config_t device_config =
ESP_CONSOLE_DEV_USB_SERIAL_JTAG_CONFIG_DEFAULT();
esp_console_repl_t* repl = nullptr;
result = esp_console_new_repl_usb_serial_jtag(&device_config, &repl_config, &repl);
return result == ESP_OK ? esp_console_start_repl(repl) : result;
}
int console_service::status_command(int argc, char** argv) {
const bool json = argc == 2 && std::strcmp(argv[1], "--json") == 0;
if (argc > 2 || (argc == 2 && !json)) {
std::printf("usage: status [--json]\n");
return 1;
}
instance_->print_status(json);
return 0;
}
int console_service::wifi_command(int argc, char** argv) {
if (argc == 2 && std::strcmp(argv[1], "status") == 0) {
instance_->print_status(false);
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "clear") == 0) {
const esp_err_t result = instance_->wifi_.disconnect();
std::printf("wifi clear: %s\n", esp_err_to_name(result));
return result == ESP_OK ? 0 : 1;
}
if (argc == 2 && std::strcmp(argv[1], "reconnect") == 0) {
const esp_err_t result = instance_->wifi_.reconnect();
std::printf("wifi reconnect: %s\n", esp_err_to_name(result));
return result == ESP_OK ? 0 : 1;
}
if ((argc == 3 || argc == 4) && std::strcmp(argv[1], "set") == 0) {
const bool hidden = argc == 4 && std::strcmp(argv[3], "hidden") == 0;
if (argc == 4 && !hidden) {
std::printf("usage: wifi set <ssid> [hidden]\n");
return 1;
}
char password[64]{};
std::printf("Password (input is not stored): ");
std::fflush(stdout);
if (std::fgets(password, sizeof(password), stdin) == nullptr) {
std::printf("\nwifi set: input failed\n");
return 1;
}
password[std::strcspn(password, "\r\n")] = '\0';
const esp_err_t result = instance_->wifi_.connect_ephemeral(argv[2], password, hidden);
std::memset(password, 0, sizeof(password));
std::printf("wifi set: %s; credentials remain in RAM only\n", esp_err_to_name(result));
return result == ESP_OK ? 0 : 1;
}
std::printf("usage: wifi set <ssid> [hidden] | wifi clear | wifi reconnect | wifi status\n");
return 1;
}
int console_service::prov_command(int argc, char** argv) {
if (argc == 2 && std::strcmp(argv[1], "status") == 0) {
std::printf("AP: %s\n",
instance_->provision_.ap_active() ? "up http://192.168.4.1/" : "down");
std::printf("saved config: %s\n",
instance_->provision_.config_present() ? "present" : "absent");
const status_snapshot value = instance_->status_.snapshot();
std::printf("wifi: %s\n", hardware_status::wifi_state_name(value.wifi));
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "start") == 0) {
if (instance_->provision_.ap_active()) {
std::printf("provision AP already up\n");
return 0;
}
instance_->wifi_.disconnect();
const esp_err_t result = instance_->provision_.start_provision();
std::printf("prov start: %s\n", esp_err_to_name(result));
return result == ESP_OK ? 0 : 1;
}
if (argc == 2 && std::strcmp(argv[1], "scan") == 0) {
provision_ap_info networks[15]{};
std::size_t count = 0;
const esp_err_t result = instance_->provision_.scan_networks(networks, 15, &count);
if (result != ESP_OK) {
std::printf("prov scan: %s\n", esp_err_to_name(result));
return 1;
}
if (count == 0) {
std::printf("no networks found\n");
}
for (std::size_t entry = 0; entry < count; ++entry) {
std::printf("%2u) %-32s %4d dBm %s\n", static_cast<unsigned>(entry + 1),
networks[entry].ssid, networks[entry].rssi,
networks[entry].secure ? "secure" : "open");
}
return 0;
}
std::printf("usage: prov status | prov start | prov scan\n");
return 1;
}
int console_service::storage_command(int argc, char** argv) {
if (argc == 2 && std::strcmp(argv[1], "probe") == 0) {
instance_->storage_.request_probe();
std::printf("storage probe requested\n");
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "status") == 0) {
instance_->print_status(false);
return 0;
}
std::printf("usage: storage probe | storage status\n");
return 1;
}
int console_service::selftest_command(int argc, char** argv) {
if (argc != 1) {
std::printf("usage: selftest\n");
return 1;
}
instance_->storage_.request_probe();
instance_->print_status(true);
instance_->run_wifi_config_selftest();
return 0;
}
void console_service::run_wifi_config_selftest() const {
const esp_err_t save_result = provision_.config_save(kSelftestSsid, kSelftestPassword, false);
char ssid[33]{};
char password[64]{};
bool hidden = true;
esp_err_t load_result = ESP_ERR_INVALID_STATE;
if (save_result == ESP_OK) {
load_result = provision_.config_load(ssid, password, hidden);
}
const bool round_trip = save_result == ESP_OK && load_result == ESP_OK &&
std::strcmp(ssid, kSelftestSsid) == 0 &&
std::strcmp(password, kSelftestPassword) == 0 && !hidden;
std::printf("wifi_config: %s\n", round_trip ? "ok" : "FAIL");
provision_.config_clear();
char bad_ssid[33]{};
char bad_password[64]{};
bool bad_hidden = false;
const esp_err_t bad_result =
wifi_provision::parse_config("{not json", bad_ssid, bad_password, bad_hidden);
std::printf("wifi_config: %s\n", bad_result == ESP_ERR_NOT_FOUND ? "bad ignored" : "FAIL");
}
void console_service::print_status(bool json) const {
const status_snapshot value = status_.snapshot();
const char* health = hardware_status::health_name(hardware_status::overall_health(value));
if (json) {
char utc[32]{};
if (value.rtc.valid) {
const time_t seconds = static_cast<time_t>(value.rtc.unix_seconds);
struct tm utc_time{};
if (gmtime_r(&seconds, &utc_time) != nullptr) {
const unsigned year = static_cast<unsigned>(utc_time.tm_year + 1900);
std::snprintf(utc, sizeof(utc), "%04u-%02u-%02uT%02u:%02u:%02uZ", year,
static_cast<unsigned>(utc_time.tm_mon + 1),
static_cast<unsigned>(utc_time.tm_mday),
static_cast<unsigned>(utc_time.tm_hour),
static_cast<unsigned>(utc_time.tm_min),
static_cast<unsigned>(utc_time.tm_sec));
}
}
std::printf(
"{\"schema_version\":1,\"firmware\":\"%s\",\"idf\":\"%s\","
"\"toolchain\":\"%s\",\"device_id\":\"%s\",\"health\":\"%s\",\"target_ok\":%s,"
"\"cores\":%" PRIu32 ",\"flash_bytes\":%u,\"psram_bytes\":%u,\"partitions_ok\":%s,"
"\"reset_reason\":%" PRIu32 ",\"display\":\"%s\",\"tf\":\"%s\",\"rtc\":%s,"
"\"rtc_valid\":%s,\"utc\":\"%s\",\"shtc3\":%s,\"sensor_valid\":%s,"
"\"wifi\":\"%s\",\"ap_active\":%s,\"credentials_persisted\":%s,"
"\"tf_logging\":%s,\"logging_error\":%d,\"temperature_tenths_c\":%d,"
"\"humidity_tenths_percent\":%u,\"key_short\":%" PRIu64 ",\"key_long\":%" PRIu64
",\"elf_sha256\":\"%s\",\"image_sha256\":\"%s\"}\n",
board::kFirmwareVersion, board::kIdfTag, value.toolchain_version, value.device_id,
health, value.target_ok ? "true" : "false", value.cpu_cores,
static_cast<unsigned>(value.flash_bytes), static_cast<unsigned>(value.psram_bytes),
value.partitions_ok ? "true" : "false", value.reset_reason,
value.display_error == ESP_OK ? "OK" : "FAILED",
hardware_status::sd_state_name(value.storage), value.rtc_present ? "true" : "false",
value.rtc.valid ? "true" : "false", utc, value.sensor_present ? "true" : "false",
value.sensor.valid ? "true" : "false", hardware_status::wifi_state_name(value.wifi),
value.ap_active ? "true" : "false", provision_.config_present() ? "true" : "false",
value.tf_logging_ok ? "true" : "false", static_cast<int>(value.logging_error),
value.sensor.valid ? static_cast<int>(value.sensor.temperature_tenths_celsius) : 0,
value.sensor.valid ? static_cast<unsigned>(value.sensor.humidity_tenths_percent) : 0U,
value.key_short_presses, value.key_long_presses, value.elf_sha256, value.image_sha256);
return;
}
char rtc_text[32]{};
if (value.rtc.valid) {
const time_t seconds = static_cast<time_t>(value.rtc.unix_seconds);
struct tm utc_time{};
if (gmtime_r(&seconds, &utc_time) != nullptr) {
const unsigned year = static_cast<unsigned>(utc_time.tm_year + 1900);
std::snprintf(
rtc_text, sizeof(rtc_text), "%04u-%02u-%02u %02u:%02u:%02u", year,
static_cast<unsigned>(utc_time.tm_mon + 1), static_cast<unsigned>(utc_time.tm_mday),
static_cast<unsigned>(utc_time.tm_hour), static_cast<unsigned>(utc_time.tm_min),
static_cast<unsigned>(utc_time.tm_sec));
}
}
std::printf("Frame M1 %s (%s)\n", board::kFirmwareVersion, health);
std::printf(" device: %s image: %.16s\n IDF: %s toolchain: %s\n", value.device_id,
value.image_sha256, value.idf_version, value.toolchain_version);
std::printf(" target: %s cores: %" PRIu32 " flash: %u PSRAM: %u part: %s\n",
value.target_ok ? "OK" : "FAIL", value.cpu_cores,
static_cast<unsigned>(value.flash_bytes), static_cast<unsigned>(value.psram_bytes),
value.partitions_ok ? "OK" : "FAIL");
std::printf(" display: %s TF: %s logging: %s reset: %" PRIu32 "\n",
value.display_error == ESP_OK ? "OK" : "FAILED",
hardware_status::sd_state_name(value.storage), value.tf_logging_ok ? "OK" : "WAIT",
value.reset_reason);
std::printf(" RTC: %s %s SHTC3: %s KEY: %" PRIu64 "/%" PRIu64 "\n",
value.rtc_present ? "OK" : "MISS", rtc_text[0] == '\0' ? "-" : rtc_text,
value.sensor_present ? "OK" : "MISS", value.key_short_presses,
value.key_long_presses);
std::printf(" WiFi: %s SSID: %s IPv4: %s credentials: system_fs (dev)\n",
hardware_status::wifi_state_name(value.wifi), value.ssid_configured ? "set" : "-",
value.ip_address[0] == '\0' ? "-" : value.ip_address);
if (value.ap_active) {
std::printf(" AP: up 192.168.4.1\n");
}
}
} // namespace frame::m1
@@ -0,0 +1,36 @@
#pragma once
#include "esp_err.h"
#include "hardware_status.hh"
#include "sd_service.hh"
#include "wifi_provision.hh"
#include "wifi_service.hh"
namespace frame::m1 {
class console_service {
public:
console_service(hardware_status& status, sd_service& storage, wifi_service& wifi,
wifi_provision& provision)
: status_(status), storage_(storage), wifi_(wifi), provision_(provision) {}
esp_err_t start();
private:
static int status_command(int argc, char** argv);
static int wifi_command(int argc, char** argv);
static int storage_command(int argc, char** argv);
static int selftest_command(int argc, char** argv);
static int prov_command(int argc, char** argv);
void print_status(bool json) const;
void run_wifi_config_selftest() const;
inline static console_service* instance_{};
hardware_status& status_;
sd_service& storage_;
wifi_service& wifi_;
wifi_provision& provision_;
};
} // namespace frame::m1
@@ -0,0 +1,213 @@
#include "display_service.hh"
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <ctime>
#include "board_config.hh"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_timer.h"
namespace frame::m1 {
namespace {
constexpr char kTag[] = "frame-display";
constexpr int kDrawRows = 40;
constexpr std::size_t kDrawBytes =
board::kDisplayWidth / 8U * static_cast<std::size_t>(kDrawRows) + 2U * sizeof(lv_color32_t);
constexpr int64_t kRenderIntervalUs = 10LL * 1000LL * 1000LL;
uint32_t tick_milliseconds() { return static_cast<uint32_t>(esp_timer_get_time() / 1000); }
void format_rtc_time(const status_snapshot& value, char* output, std::size_t capacity) {
output[0] = '\0';
if (!value.rtc.valid) {
return;
}
const time_t seconds = static_cast<time_t>(value.rtc.unix_seconds);
struct tm utc_time{};
if (gmtime_r(&seconds, &utc_time) != nullptr) {
const unsigned year = static_cast<unsigned>(utc_time.tm_year + 1900);
std::snprintf(
output, capacity, "%04u-%02u-%02u %02u:%02u:%02u", year,
static_cast<unsigned>(utc_time.tm_mon + 1), static_cast<unsigned>(utc_time.tm_mday),
static_cast<unsigned>(utc_time.tm_hour), static_cast<unsigned>(utc_time.tm_min),
static_cast<unsigned>(utc_time.tm_sec));
}
}
} // namespace
esp_err_t display_service::start() {
esp_err_t result = panel_.initialize();
const test_pattern patterns[]{test_pattern::all_black, test_pattern::all_white,
test_pattern::checker, test_pattern::border};
for (const test_pattern pattern : patterns) {
if (result == ESP_OK) {
result = panel_.draw_pattern(pattern);
}
vTaskDelay(pdMS_TO_TICKS(400));
}
status_.update([&](status_snapshot& value) { value.display_error = result; });
if (result != ESP_OK) {
return result;
}
const BaseType_t created = xTaskCreatePinnedToCore(&display_service::task_entry,
"frame-display", 8192, this, 12, &task_, 0);
return created == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
void display_service::task_entry(void* context) { static_cast<display_service*>(context)->run(); }
void display_service::flush(lv_display_t* display, const lv_area_t* area, uint8_t* pixels) {
auto* self = static_cast<display_service*>(lv_display_get_user_data(display));
lv_draw_buf_t* active_buffer = lv_display_get_buf_active(display);
pixels = static_cast<uint8_t*>(lv_draw_buf_goto_xy(active_buffer, 0, 0));
const int width = lv_area_get_width(area);
const int height = lv_area_get_height(area);
const int source_stride = width / 8;
constexpr int target_stride = board::kDisplayWidth / 8;
for (int row = 0; row < height; ++row) {
std::memcpy(self->framebuffer_ + (area->y1 + row) * target_stride + area->x1 / 8,
pixels + row * source_stride, static_cast<std::size_t>(source_stride));
}
if (lv_display_flush_is_last(display)) {
const esp_err_t result =
self->panel_.draw_full(self->framebuffer_, board::kDisplayBufferBytes);
self->status_.update([&](status_snapshot& value) { value.display_error = result; });
}
lv_display_flush_ready(display);
}
esp_err_t display_service::initialize_lvgl() {
framebuffer_ = static_cast<uint8_t*>(
heap_caps_malloc(board::kDisplayBufferBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
draw_buffer_one_ = static_cast<uint8_t*>(
heap_caps_calloc(1, kDrawBytes, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
draw_buffer_two_ = static_cast<uint8_t*>(
heap_caps_calloc(1, kDrawBytes, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
if (framebuffer_ == nullptr || draw_buffer_one_ == nullptr || draw_buffer_two_ == nullptr) {
return ESP_ERR_NO_MEM;
}
std::memset(framebuffer_, 0xFF, board::kDisplayBufferBytes);
lv_init();
lv_tick_set_cb(&tick_milliseconds);
display_ = lv_display_create(board::kDisplayWidth, board::kDisplayHeight);
if (display_ == nullptr) {
return ESP_ERR_NO_MEM;
}
lv_display_set_user_data(display_, this);
lv_display_set_color_format(display_, LV_COLOR_FORMAT_I1);
lv_display_set_buffers(display_, draw_buffer_one_, draw_buffer_two_, kDrawBytes,
LV_DISPLAY_RENDER_MODE_PARTIAL);
lv_display_set_flush_cb(display_, &display_service::flush);
lv_obj_t* screen = lv_screen_active();
lv_obj_set_style_bg_color(screen, lv_color_white(), LV_PART_MAIN);
lv_obj_set_style_text_color(screen, lv_color_black(), LV_PART_MAIN);
lv_obj_set_style_pad_all(screen, 12, LV_PART_MAIN);
lv_obj_set_flex_flow(screen, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(screen, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_t* title = lv_label_create(screen);
lv_obj_set_style_text_font(title, &lv_font_montserrat_24, LV_PART_MAIN);
lv_label_set_text(title, "Frame System Status");
health_label_ = lv_label_create(screen);
lv_obj_t* columns = lv_obj_create(screen);
lv_obj_remove_style_all(columns);
lv_obj_set_width(columns, LV_PCT(100));
lv_obj_set_flex_grow(columns, 1);
lv_obj_set_flex_flow(columns, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(columns, 18, LV_PART_MAIN);
lv_obj_t* left = lv_obj_create(columns);
lv_obj_remove_style_all(left);
lv_obj_set_flex_grow(left, 1);
lv_obj_set_height(left, LV_PCT(100));
lv_obj_set_flex_flow(left, LV_FLEX_FLOW_COLUMN);
platform_label_ = lv_label_create(left);
peripherals_label_ = lv_label_create(left);
lv_obj_t* right = lv_obj_create(columns);
lv_obj_remove_style_all(right);
lv_obj_set_flex_grow(right, 1);
lv_obj_set_height(right, LV_PCT(100));
lv_obj_set_flex_flow(right, LV_FLEX_FLOW_COLUMN);
network_label_ = lv_label_create(right);
memory_label_ = lv_label_create(right);
lv_obj_set_style_text_font(health_label_, &lv_font_montserrat_16, LV_PART_MAIN);
lv_obj_set_style_text_font(platform_label_, &lv_font_montserrat_16, LV_PART_MAIN);
lv_obj_set_style_text_font(peripherals_label_, &lv_font_montserrat_16, LV_PART_MAIN);
lv_obj_set_style_text_font(network_label_, &lv_font_montserrat_16, LV_PART_MAIN);
lv_obj_set_style_text_font(memory_label_, &lv_font_montserrat_16, LV_PART_MAIN);
return ESP_OK;
}
void display_service::render_status(const status_snapshot& value) {
const health_level health = hardware_status::overall_health(value);
lv_label_set_text_fmt(health_label_, "Health: %s\nDevice: %s",
hardware_status::health_name(health), value.device_id);
lv_label_set_text_fmt(platform_label_,
"Chip: S3 rev%" PRIu32 " / %" PRIu32 " cores\n"
"Flash: %u MiB [%s]\nPSRAM: %u MiB [%s]\nPart: [%s]",
value.chip_revision, value.cpu_cores,
static_cast<unsigned>(value.flash_bytes / (1024U * 1024U)),
value.flash_ok ? "OK" : "FAIL",
static_cast<unsigned>(value.psram_bytes / (1024U * 1024U)),
value.psram_ok ? "OK" : "FAIL", value.partitions_ok ? "OK" : "FAIL");
char rtc_text[32]{};
format_rtc_time(value, rtc_text, sizeof(rtc_text));
lv_label_set_text_fmt(
peripherals_label_,
"Display: %s\nTF: %s / log:%s\nRTC: %s %s\nSHTC3: %s\n"
"KEY short:%" PRIu64 " long:%" PRIu64,
value.display_error == ESP_OK ? "OK" : "FAIL",
hardware_status::sd_state_name(value.storage), value.tf_logging_ok ? "OK" : "WAIT",
value.rtc_present ? "OK" : "MISS", rtc_text[0] == '\0' ? "-" : rtc_text,
value.sensor_present ? "OK" : "MISS", value.key_short_presses, value.key_long_presses);
lv_label_set_text_fmt(
network_label_, "WiFi: %s\nSSID: %s\nIPv4: %s\nCredentials: system_fs (dev)",
value.ap_active ? "AP-SETUP 192.168.4.1" : hardware_status::wifi_state_name(value.wifi),
value.ssid_configured ? "set" : "-", value.ip_address[0] == '\0' ? "-" : value.ip_address);
lv_label_set_text_fmt(memory_label_,
"RAM free: %u KiB\n"
"RAM block: %u KiB\n"
"PS free: %u KiB\n"
"PS block: %u KiB",
static_cast<unsigned>(value.internal_free_bytes / 1024U),
static_cast<unsigned>(value.internal_largest_block / 1024U),
static_cast<unsigned>(value.psram_free_bytes / 1024U),
static_cast<unsigned>(value.psram_largest_block / 1024U));
}
void display_service::run() {
const esp_err_t result = initialize_lvgl();
status_.update([&](status_snapshot& value) { value.display_error = result; });
if (result != ESP_OK) {
ESP_LOGE(kTag, "LVGL initialization failed: %s", esp_err_to_name(result));
vTaskDelete(nullptr);
return;
}
int64_t next_render_at = 0;
while (true) {
const int64_t now = esp_timer_get_time();
if (now >= next_render_at) {
status_.refresh_memory_metrics();
render_status(status_.snapshot());
next_render_at = now + kRenderIntervalUs;
}
const uint32_t delay = std::clamp(lv_timer_handler(), UINT32_C(10), UINT32_C(1000));
vTaskDelay(pdMS_TO_TICKS(delay));
}
}
} // namespace frame::m1
@@ -0,0 +1,45 @@
#pragma once
#include <cstdint>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lvgl.h"
#include "hardware_status.hh"
#include "st7305_panel.hh"
namespace frame::m1 {
class display_service {
public:
explicit display_service(hardware_status& status) : status_(status) {}
display_service(const display_service&) = delete;
display_service& operator=(const display_service&) = delete;
esp_err_t start();
private:
static void task_entry(void* context);
static void flush(lv_display_t* display, const lv_area_t* area, uint8_t* pixels);
esp_err_t initialize_lvgl();
void render_status(const status_snapshot& value);
void run();
hardware_status& status_;
st7305_panel panel_{};
lv_display_t* display_{};
lv_obj_t* health_label_{};
lv_obj_t* platform_label_{};
lv_obj_t* peripherals_label_{};
lv_obj_t* network_label_{};
lv_obj_t* memory_label_{};
uint8_t* framebuffer_{};
uint8_t* draw_buffer_one_{};
uint8_t* draw_buffer_two_{};
TaskHandle_t task_{};
};
} // namespace frame::m1
@@ -0,0 +1,224 @@
#include "hardware_status.hh"
#include <cstdio>
#include <cstring>
#include "board_config.hh"
#include "esp_app_desc.h"
#include "esp_chip_info.h"
#include "esp_flash.h"
#include "esp_heap_caps.h"
#include "esp_mac.h"
#include "esp_ota_ops.h"
#include "esp_partition.h"
#include "esp_psram.h"
#include "esp_system.h"
#include "psa/crypto.h"
#include "sdkconfig.h"
#ifndef FRAME_TOOLCHAIN_VERSION
#define FRAME_TOOLCHAIN_VERSION "unknown"
#endif
namespace frame::m1 {
namespace {
constexpr char kHex[] = "0123456789abcdef";
struct expected_partition {
const char* label;
esp_partition_type_t type;
esp_partition_subtype_t subtype;
uint32_t offset;
uint32_t size;
};
// Mirrors partitions.csv; validated on boot per M1-002 (PART-001 identity).
constexpr expected_partition kExpectedPartitions[]{
{"nvs", ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, 0x9000, 0x14000},
{"nvs_keys", ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS, 0x1D000, 0x1000},
{"otadata", ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, 0x1E000, 0x2000},
{"coredump", ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_COREDUMP, 0x20000, 0x20000},
{"ota_0", ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, 0x40000, 0x500000},
{"ota_1", ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, 0x540000, 0x500000},
{"plugin_fs", ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_LITTLEFS, 0xA40000, 0x4C0000},
{"system_fs", ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_LITTLEFS, 0xF00000, 0x100000},
};
bool verify_partitions() {
for (const expected_partition& expected : kExpectedPartitions) {
const esp_partition_t* partition =
esp_partition_find_first(expected.type, expected.subtype, expected.label);
if (partition == nullptr || partition->address != expected.offset ||
partition->size != expected.size) {
return false;
}
}
return true;
}
void bytes_to_hex(const uint8_t* bytes, std::size_t count, char* output) {
for (std::size_t index = 0; index < count; ++index) {
output[index * 2U] = kHex[bytes[index] >> 4U];
output[index * 2U + 1U] = kHex[bytes[index] & 0x0FU];
}
output[count * 2U] = '\0';
}
void derive_device_id(char* output) {
constexpr char domain[] = "frame-device-id-v1";
uint8_t mac[6]{};
uint8_t input[sizeof(domain) - 1U + sizeof(mac)]{};
uint8_t digest[32]{};
if (esp_efuse_mac_get_default(mac) != ESP_OK) {
std::memcpy(output, "000000000000", 13U);
return;
}
std::memcpy(input, domain, sizeof(domain) - 1U);
std::memcpy(input + sizeof(domain) - 1U, mac, sizeof(mac));
std::size_t digest_size = 0;
const psa_status_t result = psa_hash_compute(PSA_ALG_SHA_256, input, sizeof(input), digest,
sizeof(digest), &digest_size);
if (result != PSA_SUCCESS || digest_size != sizeof(digest)) {
std::memcpy(output, "000000000000", 13U);
return;
}
bytes_to_hex(digest, 6U, output);
}
} // namespace
hardware_status::hardware_status() : mutex_(xSemaphoreCreateMutex()) {
configASSERT(mutex_ != nullptr);
}
void hardware_status::initialize_platform() {
status_snapshot initial{};
esp_chip_info_t chip{};
uint32_t flash_size = 0;
esp_chip_info(&chip);
derive_device_id(initial.device_id);
initial.chip_revision = chip.revision;
initial.cpu_cores = chip.cores;
initial.reset_reason = static_cast<uint32_t>(esp_reset_reason());
initial.target_ok = chip.model == CHIP_ESP32S3 && chip.cores == 2U;
if (esp_flash_get_size(nullptr, &flash_size) == ESP_OK) {
initial.flash_bytes = flash_size;
initial.flash_ok = flash_size == board::kFlashBytes;
}
initial.psram_bytes = esp_psram_get_size();
initial.psram_ok = initial.psram_bytes == board::kPsramBytes;
initial.internal_free_bytes = heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
initial.internal_largest_block =
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
initial.psram_free_bytes = heap_caps_get_free_size(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
initial.psram_largest_block =
heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
const esp_app_desc_t* app = esp_app_get_description();
bytes_to_hex(app->app_elf_sha256, sizeof(app->app_elf_sha256), initial.elf_sha256);
std::snprintf(initial.app_version, sizeof(initial.app_version), "%s", app->version);
std::snprintf(initial.idf_version, sizeof(initial.idf_version), "%s", app->idf_ver);
std::snprintf(initial.toolchain_version, sizeof(initial.toolchain_version), "%s",
FRAME_TOOLCHAIN_VERSION);
uint8_t image_digest[32]{};
const esp_partition_t* running = esp_ota_get_running_partition();
if (running != nullptr && esp_partition_get_sha256(running, image_digest) == ESP_OK) {
bytes_to_hex(image_digest, sizeof(image_digest), initial.image_sha256);
}
initial.partitions_ok = verify_partitions();
initial.nvs_encrypted = false;
update([&](status_snapshot& value) { value = initial; });
}
void hardware_status::refresh_memory_metrics() {
const std::size_t internal_free =
heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
const std::size_t internal_largest =
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
const std::size_t psram_free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
const std::size_t psram_largest =
heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
update([&](status_snapshot& value) {
value.internal_free_bytes = internal_free;
value.internal_largest_block = internal_largest;
value.psram_free_bytes = psram_free;
value.psram_largest_block = psram_largest;
});
}
status_snapshot hardware_status::snapshot() const {
status_snapshot result{};
if (xSemaphoreTake(mutex_, portMAX_DELAY) == pdTRUE) {
result = value_;
xSemaphoreGive(mutex_);
}
return result;
}
health_level hardware_status::overall_health(const status_snapshot& value) {
if (!value.target_ok || !value.flash_ok || !value.psram_ok || !value.partitions_ok ||
value.display_error != ESP_OK) {
return health_level::failed;
}
// M1 policy: RAM-only Wi-Fi credentials are expected (SEC-010 blocks encrypted NVS on this
// board), so an unconfigured SSID or plaintext NVS never lowers M1 health.
if (value.storage != sd_state::ready || !value.rtc_present || !value.sensor_present ||
value.board_error != ESP_OK || !value.sensor.valid) {
return health_level::degraded;
}
return health_level::ok;
}
const char* hardware_status::health_name(health_level value) {
switch (value) {
case health_level::ok:
return "OK";
case health_level::degraded:
return "DEGRADED";
case health_level::failed:
return "FAILED";
case health_level::recovery:
return "RECOVERY";
}
return "UNKNOWN";
}
const char* hardware_status::sd_state_name(sd_state value) {
switch (value) {
case sd_state::absent:
return "ABSENT";
case sd_state::health_checking:
return "HEALTH_CHECKING";
case sd_state::ready:
return "READY";
case sd_state::failed:
return "FAILED";
case sd_state::recovering:
return "RECOVERING";
}
return "UNKNOWN";
}
const char* hardware_status::wifi_state_name(wifi_state value) {
switch (value) {
case wifi_state::unconfigured:
return "UNCONFIG";
case wifi_state::disconnected:
return "DISCONNECTED";
case wifi_state::connecting:
return "CONNECTING";
case wifi_state::connected:
return "CONNECTED";
}
return "UNKNOWN";
}
} // namespace frame::m1
@@ -0,0 +1,117 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
namespace frame::m1 {
enum class health_level : uint8_t {
ok,
degraded,
failed,
recovery,
};
enum class sd_state : uint8_t {
absent,
health_checking,
ready,
failed,
recovering,
};
enum class wifi_state : uint8_t {
unconfigured,
disconnected,
connecting,
connected,
};
struct sensor_sample {
int16_t temperature_tenths_celsius{};
uint16_t humidity_tenths_percent{};
bool valid{};
int64_t sampled_at_us{};
};
struct rtc_time {
int64_t unix_seconds{};
bool valid{};
int64_t read_at_us{};
};
struct status_snapshot {
char device_id[13]{};
char elf_sha256[65]{};
char image_sha256[65]{};
char app_version[32]{};
char idf_version[32]{};
char toolchain_version[48]{};
char ip_address[16]{};
std::size_t flash_bytes{};
std::size_t psram_bytes{};
std::size_t internal_free_bytes{};
std::size_t internal_largest_block{};
std::size_t psram_free_bytes{};
std::size_t psram_largest_block{};
uint32_t chip_revision{};
uint32_t cpu_cores{};
uint32_t reset_reason{};
uint64_t key_short_presses{};
uint64_t key_long_presses{};
bool target_ok{};
bool flash_ok{};
bool psram_ok{};
bool partitions_ok{};
bool rtc_present{};
bool sensor_present{};
bool ssid_configured{};
bool ap_active{};
bool ap_mode_requested{};
bool key_pressed{};
bool nvs_encrypted{};
bool tf_logging_ok{};
sd_state storage{sd_state::absent};
wifi_state wifi{wifi_state::unconfigured};
sensor_sample sensor{};
rtc_time rtc{};
esp_err_t display_error{ESP_ERR_INVALID_STATE};
esp_err_t storage_error{ESP_ERR_INVALID_STATE};
esp_err_t board_error{ESP_ERR_INVALID_STATE};
esp_err_t wifi_error{ESP_ERR_INVALID_STATE};
esp_err_t logging_error{ESP_ERR_INVALID_STATE};
};
class hardware_status {
public:
hardware_status();
hardware_status(const hardware_status&) = delete;
hardware_status& operator=(const hardware_status&) = delete;
void initialize_platform();
void refresh_memory_metrics();
[[nodiscard]] status_snapshot snapshot() const;
template <typename Function> void update(Function&& function) {
if (xSemaphoreTake(mutex_, portMAX_DELAY) == pdTRUE) {
function(value_);
xSemaphoreGive(mutex_);
}
}
[[nodiscard]] static health_level overall_health(const status_snapshot& value);
[[nodiscard]] static const char* health_name(health_level value);
[[nodiscard]] static const char* sd_state_name(sd_state value);
[[nodiscard]] static const char* wifi_state_name(wifi_state value);
private:
mutable SemaphoreHandle_t mutex_{};
status_snapshot value_{};
};
} // namespace frame::m1
@@ -0,0 +1,5 @@
dependencies:
idf: "==6.0.2"
espressif/cjson: "^1"
joltwallet/littlefs: "^1"
lvgl/lvgl: "==9.4.0"
+211
View File
@@ -0,0 +1,211 @@
#include "sd_service.hh"
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <unistd.h>
#include "board_config.hh"
#include "driver/sdmmc_host.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "esp_vfs_fat.h"
#include "psa/crypto.h"
#include "status_log.hh"
namespace frame::m1 {
namespace {
constexpr char kTag[] = "frame-sd";
constexpr char kHealthDirectory[] = "/frame/.health";
constexpr char kHealthPath[] = "/frame/.health/m1.tmp";
constexpr char kHealthPayload[] = "frame-m1-sd-health-v1\n";
constexpr char kLogDirectory[] = "/frame/logs";
constexpr char kLogPath[] = "/frame/logs/m1-current.jsonl";
constexpr int64_t kLogIntervalUs = 10LL * 1000LL * 1000LL;
} // namespace
sd_service::~sd_service() { unmount(); }
esp_err_t sd_service::start() {
const BaseType_t created =
xTaskCreatePinnedToCore(&sd_service::task_entry, "frame-sd", 6144, this, 7, &task_, 1);
return created == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
void sd_service::request_probe() {
if (task_ != nullptr) {
xTaskNotifyGive(task_);
}
}
void sd_service::task_entry(void* context) { static_cast<sd_service*>(context)->run(); }
esp_err_t sd_service::mount_and_check() {
status_.update([](status_snapshot& value) { value.storage = sd_state::health_checking; });
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
host.max_freq_khz = SDMMC_FREQ_DEFAULT;
sdmmc_slot_config_t slot = SDMMC_SLOT_CONFIG_DEFAULT();
slot.width = 1;
slot.clk = board::kSdClock;
slot.cmd = board::kSdCommand;
slot.d0 = board::kSdData0;
slot.d1 = GPIO_NUM_NC;
slot.d2 = GPIO_NUM_NC;
slot.d3 = GPIO_NUM_NC;
slot.cd = SDMMC_SLOT_NO_CD;
slot.wp = SDMMC_SLOT_NO_WP;
slot.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
esp_vfs_fat_sdmmc_mount_config_t mount{};
mount.format_if_mount_failed = false;
mount.max_files = 8;
mount.allocation_unit_size = 16 * 1024;
esp_err_t result = esp_vfs_fat_sdmmc_mount(board::kSdMount, &host, &slot, &mount, &card_);
if (result != ESP_OK) {
card_ = nullptr;
const bool card_absent = result == ESP_ERR_NOT_FOUND || result == ESP_ERR_TIMEOUT;
status_.update([&](status_snapshot& value) {
value.storage = card_absent ? sd_state::absent : sd_state::failed;
value.storage_error = result;
});
return result;
}
result = health_check();
status_.update([&](status_snapshot& value) {
value.storage = result == ESP_OK ? sd_state::ready : sd_state::failed;
value.storage_error = result;
});
if (result != ESP_OK) {
unmount();
}
return result;
}
esp_err_t sd_service::health_check() {
if (mkdir(kHealthDirectory, 0755) != 0 && errno != EEXIST) {
return ESP_FAIL;
}
if (mkdir(kLogDirectory, 0755) != 0 && errno != EEXIST) {
return ESP_FAIL;
}
FILE* output = std::fopen(kHealthPath, "wb");
if (output == nullptr) {
return ESP_FAIL;
}
const std::size_t written = std::fwrite(kHealthPayload, 1, sizeof(kHealthPayload) - 1U, output);
const int flush_result = std::fflush(output);
const int sync_result = fsync(fileno(output));
const int close_result = std::fclose(output);
if (written != sizeof(kHealthPayload) - 1U || flush_result != 0 || sync_result != 0 ||
close_result != 0) {
unlink(kHealthPath);
return ESP_FAIL;
}
char readback[sizeof(kHealthPayload) - 1U]{};
FILE* input = std::fopen(kHealthPath, "rb");
if (input == nullptr) {
return ESP_FAIL;
}
const std::size_t read = std::fread(readback, 1, sizeof(readback), input);
const int read_close_result = std::fclose(input);
uint8_t expected_hash[32]{};
uint8_t actual_hash[32]{};
std::size_t expected_size = 0;
std::size_t actual_size = 0;
const psa_status_t expected_result =
psa_hash_compute(PSA_ALG_SHA_256, reinterpret_cast<const uint8_t*>(kHealthPayload),
sizeof(readback), expected_hash, sizeof(expected_hash), &expected_size);
const psa_status_t actual_result =
psa_hash_compute(PSA_ALG_SHA_256, reinterpret_cast<const uint8_t*>(readback),
sizeof(readback), actual_hash, sizeof(actual_hash), &actual_size);
unlink(kHealthPath);
return read == sizeof(readback) && read_close_result == 0 && expected_result == PSA_SUCCESS &&
actual_result == PSA_SUCCESS && expected_size == sizeof(expected_hash) &&
actual_size == sizeof(actual_hash) &&
std::memcmp(expected_hash, actual_hash, sizeof(expected_hash)) == 0
? ESP_OK
: ESP_FAIL;
}
void sd_service::unmount() {
if (card_ != nullptr) {
esp_vfs_fat_sdcard_unmount(board::kSdMount, card_);
card_ = nullptr;
}
}
esp_err_t sd_service::append_status_log() {
// Must exceed the ~550-byte payload: format_status_log returns 0 on truncation (= ESP_FAIL).
char line[640];
const status_snapshot snapshot = status_.snapshot();
const std::size_t length =
format_status_log(snapshot, ++log_sequence_, esp_timer_get_time(), line, sizeof(line));
if (length == 0) {
return ESP_FAIL;
}
const std::size_t mirrored = std::fwrite(line, 1, length, stdout);
std::fflush(stdout);
if (mirrored != length) {
return ESP_FAIL;
}
FILE* output = std::fopen(kLogPath, "a");
if (output == nullptr) {
return ESP_FAIL;
}
const std::size_t written = std::fwrite(line, 1, length, output);
const int flush_result = std::fflush(output);
const int sync_result = fsync(fileno(output));
const int close_result = std::fclose(output);
if (written != length || flush_result != 0 || sync_result != 0 || close_result != 0) {
return ESP_FAIL;
}
return ESP_OK;
}
void sd_service::run() {
int64_t next_log_at = 0;
while (true) {
const int64_t now = esp_timer_get_time();
if (card_ == nullptr) {
const esp_err_t result = mount_and_check();
if (result != ESP_OK) {
ESP_LOGW(kTag, "TF probe failed: %s", esp_err_to_name(result));
} else {
next_log_at = now;
}
} else {
const esp_err_t result = sdmmc_get_status(card_);
if (result != ESP_OK) {
ESP_LOGW(kTag, "TF removed or unhealthy: %s", esp_err_to_name(result));
status_.update([&](status_snapshot& value) {
value.storage = sd_state::recovering;
value.storage_error = result;
});
unmount();
status_.update([](status_snapshot& value) {
value.storage = sd_state::absent;
value.tf_logging_ok = false;
});
} else if (now >= next_log_at) {
const esp_err_t log_result = append_status_log();
status_.update([&](status_snapshot& value) {
value.tf_logging_ok = log_result == ESP_OK;
value.logging_error = log_result;
});
next_log_at = now + kLogIntervalUs;
}
}
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2000));
}
}
} // namespace frame::m1
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sdmmc_cmd.h"
#include "hardware_status.hh"
namespace frame::m1 {
class sd_service {
public:
explicit sd_service(hardware_status& status) : status_(status) {}
~sd_service();
sd_service(const sd_service&) = delete;
sd_service& operator=(const sd_service&) = delete;
esp_err_t start();
void request_probe();
private:
static void task_entry(void* context);
esp_err_t mount_and_check();
esp_err_t health_check();
esp_err_t append_status_log();
void unmount();
void run();
hardware_status& status_;
sdmmc_card_t* card_{};
TaskHandle_t task_{};
uint64_t log_sequence_{};
};
} // namespace frame::m1
+262
View File
@@ -0,0 +1,262 @@
#include "st7305_panel.hh"
#include <array>
#include <cstring>
#include "board_config.hh"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
namespace frame::m1 {
namespace {
struct init_command {
uint8_t command;
std::array<uint8_t, 10> data;
uint8_t length;
};
constexpr std::array kInitialization{
init_command{0xD6, {0x17, 0x02}, 2},
init_command{0xD1, {0x01}, 1},
init_command{0xC0, {0x11, 0x04}, 2},
init_command{0xC1, {0x69, 0x69, 0x69, 0x69}, 4},
init_command{0xC2, {0x19, 0x19, 0x19, 0x19}, 4},
init_command{0xC4, {0x4B, 0x4B, 0x4B, 0x4B}, 4},
init_command{0xC5, {0x19, 0x19, 0x19, 0x19}, 4},
init_command{0xD8, {0x80, 0xE9}, 2},
init_command{0xB2, {0x02}, 1},
init_command{0xB3, {0xE5, 0xF6, 0x05, 0x46, 0x77, 0x77, 0x77, 0x77, 0x76, 0x45}, 10},
init_command{0xB4, {0x05, 0x46, 0x77, 0x77, 0x77, 0x77, 0x76, 0x45}, 8},
init_command{0x62, {0x32, 0x03, 0x1F}, 3},
init_command{0xB7, {0x13}, 1},
init_command{0xB0, {0x64}, 1},
};
} // namespace
st7305_panel::~st7305_panel() {
if (io_ != nullptr) {
esp_lcd_panel_io_del(io_);
}
if (bus_initialized_) {
spi_bus_free(board::kDisplayHost);
}
heap_caps_free(native_buffer_);
if (transfer_complete_ != nullptr) {
vSemaphoreDelete(transfer_complete_);
}
}
esp_err_t st7305_panel::initialize() {
spi_bus_config_t bus{};
bus.miso_io_num = GPIO_NUM_NC;
bus.mosi_io_num = board::kDisplayMosi;
bus.sclk_io_num = board::kDisplaySck;
bus.quadwp_io_num = GPIO_NUM_NC;
bus.quadhd_io_num = GPIO_NUM_NC;
bus.max_transfer_sz = static_cast<int>(board::kDisplayBufferBytes);
esp_err_t result = spi_bus_initialize(board::kDisplayHost, &bus, SPI_DMA_CH_AUTO);
if (result != ESP_OK) {
return result;
}
bus_initialized_ = true;
esp_lcd_panel_io_spi_config_t io_config{};
io_config.dc_gpio_num = board::kDisplayDc;
io_config.cs_gpio_num = board::kDisplayCs;
io_config.pclk_hz = board::kDisplayClockHz;
io_config.spi_mode = 0;
io_config.trans_queue_depth = 4;
io_config.lcd_cmd_bits = 8;
io_config.lcd_param_bits = 8;
result = esp_lcd_new_panel_io_spi(board::kDisplayHost, &io_config, &io_);
if (result != ESP_OK) {
return result;
}
native_buffer_ = static_cast<uint8_t*>(
heap_caps_malloc(board::kDisplayBufferBytes, MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA));
transfer_complete_ = xSemaphoreCreateBinary();
if (native_buffer_ == nullptr || transfer_complete_ == nullptr) {
return ESP_ERR_NO_MEM;
}
const esp_lcd_panel_io_callbacks_t callbacks{
.on_color_trans_done = &st7305_panel::transfer_done,
};
result = esp_lcd_panel_io_register_event_callbacks(io_, &callbacks, this);
if (result != ESP_OK) {
return result;
}
gpio_config_t reset_config{};
reset_config.pin_bit_mask = UINT64_C(1) << board::kDisplayReset;
reset_config.mode = GPIO_MODE_OUTPUT;
reset_config.pull_up_en = GPIO_PULLUP_ENABLE;
result = gpio_config(&reset_config);
if (result != ESP_OK) {
return result;
}
result = reset();
if (result != ESP_OK) {
return result;
}
for (const init_command& item : kInitialization) {
result = command(item.command, item.data.data(), item.length);
if (result != ESP_OK) {
return result;
}
}
result = command(0x11);
if (result != ESP_OK) {
return result;
}
vTaskDelay(pdMS_TO_TICKS(200));
const uint8_t c9[]{0x00};
const uint8_t memory_access[]{0x48};
const uint8_t pixel_format[]{0x11};
const uint8_t b9[]{0x20};
const uint8_t b8[]{0x29};
const uint8_t columns[]{0x12, 0x2A};
const uint8_t rows[]{0x00, 0xC7};
const uint8_t tearing[]{0x00};
const uint8_t d0[]{0xFF};
const std::array tail{
init_command{0xC9, {c9[0]}, 1},
init_command{0x36, {memory_access[0]}, 1},
init_command{0x3A, {pixel_format[0]}, 1},
init_command{0xB9, {b9[0]}, 1},
init_command{0xB8, {b8[0]}, 1},
init_command{0x21, {}, 0},
init_command{0x2A, {columns[0], columns[1]}, 2},
init_command{0x2B, {rows[0], rows[1]}, 2},
init_command{0x35, {tearing[0]}, 1},
init_command{0xD0, {d0[0]}, 1},
init_command{0x38, {}, 0},
init_command{0x29, {}, 0},
};
for (const init_command& item : tail) {
result = command(item.command, item.data.data(), item.length);
if (result != ESP_OK) {
return result;
}
}
return ESP_OK;
}
esp_err_t st7305_panel::draw_full(const uint8_t* row_major_i1, std::size_t size) {
if (io_ == nullptr || row_major_i1 == nullptr || size != board::kDisplayBufferBytes) {
return ESP_ERR_INVALID_ARG;
}
if (transfer_pending_) {
return ESP_ERR_INVALID_STATE;
}
if (native_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
std::memset(native_buffer_, 0, board::kDisplayBufferBytes);
constexpr int source_stride = board::kDisplayWidth / 8;
constexpr int native_column_bytes = board::kDisplayHeight / 4;
for (int y = 0; y < board::kDisplayHeight; ++y) {
for (int x = 0; x < board::kDisplayWidth; ++x) {
const bool white =
(row_major_i1[y * source_stride + x / 8] & (UINT8_C(1) << (7 - x % 8))) != 0;
const int inverted_y = board::kDisplayHeight - 1 - y;
const std::size_t target =
static_cast<std::size_t>((x / 2) * native_column_bytes + inverted_y / 4);
const uint8_t bit = static_cast<uint8_t>(7 - ((inverted_y % 4) * 2 + (x % 2)));
if (white) {
native_buffer_[target] |= static_cast<uint8_t>(UINT8_C(1) << bit);
} else {
native_buffer_[target] &= static_cast<uint8_t>(~(UINT8_C(1) << bit));
}
}
}
const uint8_t columns[]{0x12, 0x2A};
const uint8_t rows[]{0x00, 0xC7};
esp_err_t result = command(0x2A, columns, sizeof(columns));
if (result == ESP_OK) {
result = command(0x2B, rows, sizeof(rows));
}
if (result == ESP_OK) {
transfer_pending_ = true;
result = esp_lcd_panel_io_tx_color(io_, 0x2C, native_buffer_, board::kDisplayBufferBytes);
if (result != ESP_OK) {
transfer_pending_ = false;
}
}
if (result == ESP_OK && xSemaphoreTake(transfer_complete_, pdMS_TO_TICKS(2000)) != pdTRUE) {
result = ESP_ERR_TIMEOUT;
}
return result;
}
bool st7305_panel::transfer_done(esp_lcd_panel_io_handle_t, esp_lcd_panel_io_event_data_t*,
void* context) {
auto* panel = static_cast<st7305_panel*>(context);
panel->transfer_pending_ = false;
BaseType_t task_woken = pdFALSE;
xSemaphoreGiveFromISR(panel->transfer_complete_, &task_woken);
return task_woken == pdTRUE;
}
esp_err_t st7305_panel::draw_pattern(test_pattern pattern) {
auto* buffer =
static_cast<uint8_t*>(heap_caps_malloc(board::kDisplayBufferBytes, MALLOC_CAP_SPIRAM));
if (buffer == nullptr) {
return ESP_ERR_NO_MEM;
}
std::memset(buffer, pattern == test_pattern::all_black ? 0x00 : 0xFF,
board::kDisplayBufferBytes);
if (pattern == test_pattern::checker || pattern == test_pattern::border) {
constexpr int stride = board::kDisplayWidth / 8;
for (int y = 0; y < board::kDisplayHeight; ++y) {
for (int x = 0; x < board::kDisplayWidth; ++x) {
const bool ring = x == 0 || y == 0 || x == board::kDisplayWidth - 1 ||
y == board::kDisplayHeight - 1;
const bool black = pattern == test_pattern::border
? ring
: ring || (((x / 20) + (y / 20)) % 2 == 0);
if (black) {
buffer[y * stride + x / 8] &=
static_cast<uint8_t>(~(UINT8_C(1) << (7 - x % 8)));
}
}
}
}
const esp_err_t result = draw_full(buffer, board::kDisplayBufferBytes);
heap_caps_free(buffer);
return result;
}
esp_err_t st7305_panel::reset() {
esp_err_t result = gpio_set_level(board::kDisplayReset, 1);
if (result != ESP_OK) {
return result;
}
vTaskDelay(pdMS_TO_TICKS(50));
result = gpio_set_level(board::kDisplayReset, 0);
if (result != ESP_OK) {
return result;
}
vTaskDelay(pdMS_TO_TICKS(20));
result = gpio_set_level(board::kDisplayReset, 1);
vTaskDelay(pdMS_TO_TICKS(50));
return result;
}
esp_err_t st7305_panel::command(uint8_t value) { return command(value, nullptr, 0); }
esp_err_t st7305_panel::command(uint8_t value, const uint8_t* parameters, std::size_t count) {
return esp_lcd_panel_io_tx_param(io_, value, parameters, count);
}
} // namespace frame::m1
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "esp_err.h"
#include "esp_lcd_panel_io.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
namespace frame::m1 {
enum class test_pattern : uint8_t {
all_black,
all_white,
checker,
border,
};
class st7305_panel {
public:
st7305_panel() = default;
~st7305_panel();
st7305_panel(const st7305_panel&) = delete;
st7305_panel& operator=(const st7305_panel&) = delete;
esp_err_t initialize();
esp_err_t draw_full(const uint8_t* row_major_i1, std::size_t size);
esp_err_t draw_pattern(test_pattern pattern);
private:
static bool transfer_done(esp_lcd_panel_io_handle_t panel_io,
esp_lcd_panel_io_event_data_t* event_data, void* context);
esp_err_t reset();
esp_err_t command(uint8_t value);
esp_err_t command(uint8_t value, const uint8_t* parameters, std::size_t count);
esp_lcd_panel_io_handle_t io_{};
bool bus_initialized_{};
uint8_t* native_buffer_{};
SemaphoreHandle_t transfer_complete_{};
volatile bool transfer_pending_{};
};
} // namespace frame::m1
+83
View File
@@ -0,0 +1,83 @@
#include "status_log.hh"
#include <cinttypes>
#include <cstdio>
#include <ctime>
namespace frame::m1 {
namespace {
uint32_t crc32c(const uint8_t* data, std::size_t size) {
uint32_t crc = UINT32_MAX;
for (std::size_t index = 0; index < size; ++index) {
crc ^= data[index];
for (int bit = 0; bit < 8; ++bit) {
const uint32_t mask = 0U - (crc & 1U);
crc = (crc >> 1U) ^ (UINT32_C(0x82F63B78) & mask);
}
}
return ~crc;
}
} // namespace
std::size_t format_status_log(const status_snapshot& status, uint64_t sequence, int64_t uptime_us,
char* output, std::size_t capacity, const char* event,
const char* mode) {
if (output == nullptr || capacity == 0 || event == nullptr || mode == nullptr) {
return 0;
}
char utc[32]{};
if (status.rtc.valid) {
const time_t seconds = static_cast<time_t>(status.rtc.unix_seconds);
struct tm utc_time{};
if (gmtime_r(&seconds, &utc_time) != nullptr) {
const unsigned year = static_cast<unsigned>(utc_time.tm_year + 1900);
std::snprintf(
utc, sizeof(utc), "%04u-%02u-%02uT%02u:%02u:%02uZ", year,
static_cast<unsigned>(utc_time.tm_mon + 1), static_cast<unsigned>(utc_time.tm_mday),
static_cast<unsigned>(utc_time.tm_hour), static_cast<unsigned>(utc_time.tm_min),
static_cast<unsigned>(utc_time.tm_sec));
}
}
const int payload_length = std::snprintf(
output, capacity,
"{\"schema_version\":1,\"sequence\":%" PRIu64 ",\"uptime_us\":%" PRId64
",\"utc_valid\":%s,\"utc\":\"%s\",\"source\":\"m1\",\"event\":\"%s\","
"\"mode\":\"%s\",\"status\":\"%s\",\"device_id\":\"%s\","
"\"app\":\"%s\",\"idf\":\"%s\",\"toolchain\":\"%s\",\"image_sha256\":\"%s\","
"\"partitions\":%s,\"reset_reason\":%" PRIu32 ",\"tf\":\"%s\",\"wifi\":\"%s\","
"\"ap_setup\":%s,"
"\"rtc\":%s,\"shtc3\":%s,\"sensor_valid\":%s,"
"\"temperature_tenths_c\":%d,\"humidity_tenths_percent\":%u,"
"\"key_short\":%" PRIu64 ",\"key_long\":%" PRIu64,
sequence, uptime_us, status.rtc.valid ? "true" : "false", utc, event, mode,
hardware_status::health_name(hardware_status::overall_health(status)), status.device_id,
status.app_version, status.idf_version, status.toolchain_version, status.image_sha256,
status.partitions_ok ? "true" : "false", status.reset_reason,
hardware_status::sd_state_name(status.storage),
hardware_status::wifi_state_name(status.wifi), status.ap_active ? "true" : "false",
status.rtc_present ? "true" : "false", status.sensor_present ? "true" : "false",
status.sensor.valid ? "true" : "false",
status.sensor.valid ? static_cast<int>(status.sensor.temperature_tenths_celsius) : 0,
status.sensor.valid ? static_cast<unsigned>(status.sensor.humidity_tenths_percent) : 0U,
status.key_short_presses, status.key_long_presses);
if (payload_length < 0 || static_cast<std::size_t>(payload_length) >= capacity) {
output[0] = '\0';
return 0;
}
const std::size_t payload_size = static_cast<std::size_t>(payload_length);
const uint32_t checksum = crc32c(reinterpret_cast<const uint8_t*>(output), payload_size);
const int suffix_length = std::snprintf(output + payload_size, capacity - payload_size,
",\"crc32c\":\"%08" PRIx32 "\"}\n", checksum);
if (suffix_length < 0 || static_cast<std::size_t>(suffix_length) >= capacity - payload_size) {
output[0] = '\0';
return 0;
}
return payload_size + static_cast<std::size_t>(suffix_length);
}
} // namespace frame::m1
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "hardware_status.hh"
namespace frame::m1 {
[[nodiscard]] std::size_t format_status_log(const status_snapshot& status, uint64_t sequence,
int64_t uptime_us, char* output, std::size_t capacity,
const char* event = "status",
const char* mode = "normal");
} // namespace frame::m1
+818
View File
@@ -0,0 +1,818 @@
#include "wifi_provision.hh"
#include <cerrno>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include "cJSON.h"
#include "esp_littlefs.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
namespace frame::m1 {
namespace {
constexpr char kTag[] = "frame-prov";
constexpr char kMountPoint[] = "/system";
constexpr char kPartitionLabel[] = "system_fs";
constexpr char kConfigPath[] = "/system/wifi.json";
constexpr char kTempPath[] = "/system/wifi.json.tmp";
constexpr std::size_t kMaxBodyLength = 512;
constexpr std::size_t kMaxScanRecords = 24;
constexpr std::size_t kMaxScanResults = 15;
constexpr int kFallbackDisconnects = 5;
constexpr int kFallbackNoIpSeconds = 60;
constexpr int kMonitorTickMs = 1000;
constexpr char kPageHead[] =
"<!DOCTYPE html>\n"
"<html lang=\"en\">\n"
"<head>\n"
"<meta charset=\"utf-8\">\n"
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
"<title>Frame Setup</title>\n"
"<style>\n"
"body{font-family:sans-serif;background:#111;color:#eee;max-width:30rem;margin:2rem auto;"
"padding:0 1rem}\n"
"form{background:#1d1d1d;border:1px solid #333;border-radius:8px;padding:1rem;margin:1rem 0}\n"
"label{display:block;margin:.6rem 0 .2rem;font-size:.9rem;color:#aaa}\n"
"select,input[type=password]{width:100%;box-sizing:border-box;padding:.5rem;font-size:1rem;"
"border-radius:4px;border:1px solid #444;background:#111;color:#eee}\n"
"button{margin-top:1rem;padding:.6rem 1.4rem;font-size:1rem;border:0;border-radius:4px;"
"background:#4a7dff;color:#fff;cursor:pointer}\n"
".small{color:#888;font-size:.8rem}\n"
"</style>\n"
"</head>\n"
"<body>\n"
"<h1>Frame Setup</h1>\n"
"<p class=\"small\">Pick a Wi-Fi network for this Frame device.</p>\n"
"<form method=\"post\" action=\"/connect\">\n"
"<label for=\"ssid\">Network</label>\n"
"<select id=\"ssid\" name=\"ssid\" required>\n";
constexpr char kPageTail[] =
"</select>\n"
"<label for=\"password\">Password</label>\n"
"<input id=\"password\" type=\"password\" name=\"password\" minlength=\"8\" maxlength=\"63\" "
"required>\n"
"<label><input type=\"checkbox\" name=\"hidden\" value=\"on\"> Hidden network</label>\n"
"<button type=\"submit\">Save &amp; connect</button>\n"
"</form>\n"
"<form method=\"post\" action=\"/clear\">\n"
"<button type=\"submit\">Forget saved network</button>\n"
"</form>\n"
"<p class=\"small\">After saving, the device connects and this hotspot disappears. "
"If it fails, the hotspot returns.</p>\n"
"</body>\n"
"</html>\n";
constexpr char kConnectPage[] =
"<!DOCTYPE html>\n"
"<html lang=\"en\">\n"
"<head><meta charset=\"utf-8\"><meta name=\"viewport\" "
"content=\"width=device-width,initial-scale=1\"><title>Frame Setup</title></head>\n"
"<body style=\"font-family:sans-serif;background:#111;color:#eee;max-width:30rem;"
"margin:2rem auto;padding:0 1rem\">\n"
"<h1>Saved</h1>\n"
"<p>Connecting &mdash; check the device screen; if it fails the AP returns.</p>\n"
"</body>\n"
"</html>\n";
constexpr char kClearPage[] =
"<!DOCTYPE html>\n"
"<html lang=\"en\">\n"
"<head><meta charset=\"utf-8\"><meta name=\"viewport\" "
"content=\"width=device-width,initial-scale=1\"><title>Frame Setup</title></head>\n"
"<body style=\"font-family:sans-serif;background:#111;color:#eee;max-width:30rem;"
"margin:2rem auto;padding:0 1rem\">\n"
"<h1>Cleared</h1>\n"
"<p>Saved Wi-Fi credentials removed. The setup hotspot is restarting.</p>\n"
"</body>\n"
"</html>\n";
int hex_value(char digit) {
if (digit >= '0' && digit <= '9') {
return digit - '0';
}
if (digit >= 'a' && digit <= 'f') {
return digit - 'a' + 10;
}
if (digit >= 'A' && digit <= 'F') {
return digit - 'A' + 10;
}
return -1;
}
std::size_t url_decode(const char* source, std::size_t length, char* destination,
std::size_t capacity) {
std::size_t out = 0;
for (std::size_t i = 0; i < length && out + 1 < capacity; ++i) {
char decoded = source[i];
if (decoded == '+') {
decoded = ' ';
} else if (decoded == '%' && i + 2 < length) {
const int high = hex_value(source[i + 1]);
const int low = hex_value(source[i + 2]);
if (high >= 0 && low >= 0) {
decoded = static_cast<char>((high << 4) | low);
i += 2;
}
}
destination[out++] = decoded;
}
destination[out] = '\0';
return out;
}
void parse_form(const char* body, char (&ssid)[129], char (&password)[129], bool& hidden) {
ssid[0] = '\0';
password[0] = '\0';
hidden = false;
std::size_t cursor = 0;
const std::size_t length = std::strlen(body);
while (cursor <= length) {
std::size_t pair_end = cursor;
while (pair_end < length && body[pair_end] != '&') {
++pair_end;
}
const void* found = std::memchr(body + cursor, '=', pair_end - cursor);
if (found != nullptr) {
const std::size_t equal =
static_cast<std::size_t>(static_cast<const char*>(found) - (body + cursor));
char key[32]{};
char value[129]{};
url_decode(body + cursor, equal < sizeof(key) - 1 ? equal : 0, key, sizeof(key));
url_decode(body + cursor + equal + 1, pair_end - cursor - equal - 1, value,
sizeof(value));
if (std::strcmp(key, "ssid") == 0) {
std::memcpy(ssid, value, sizeof(ssid));
} else if (std::strcmp(key, "password") == 0) {
std::memcpy(password, value, sizeof(password));
} else if (std::strcmp(key, "hidden") == 0) {
hidden = std::strcmp(value, "on") == 0;
}
}
if (pair_end >= length) {
break;
}
cursor = pair_end + 1;
}
}
void html_escape(const char* text, char (&output)[193]) {
std::size_t out = 0;
for (std::size_t i = 0; text[i] != '\0' && out + 6 < sizeof(output); ++i) {
const char digit = text[i];
if (digit == '&') {
std::memcpy(output + out, "&amp;", 5);
out += 5;
} else if (digit == '<') {
std::memcpy(output + out, "&lt;", 4);
out += 4;
} else if (digit == '>') {
std::memcpy(output + out, "&gt;", 4);
out += 4;
} else if (digit == '"') {
std::memcpy(output + out, "&#34;", 5);
out += 5;
} else if (digit == '\'') {
std::memcpy(output + out, "&#39;", 5);
out += 5;
} else if (digit >= ' ') {
output[out++] = digit;
}
}
output[out] = '\0';
}
void wipe_credentials(char* ssid, char* password) {
std::memset(ssid, 0, 33);
std::memset(password, 0, 64);
}
std::size_t bounded_length(const char* text, std::size_t capacity) {
std::size_t length = 0;
while (length < capacity && text[length] != '\0') {
++length;
}
return length;
}
} // namespace
esp_err_t wifi_provision::initialize() {
esp_vfs_littlefs_conf_t config{};
config.base_path = kMountPoint;
config.partition_label = kPartitionLabel;
config.format_if_mount_failed = false;
const esp_err_t result = esp_vfs_littlefs_register(&config);
if (result != ESP_OK) {
mounted_ = false;
ESP_LOGW(kTag, "system_fs unavailable: %s", esp_err_to_name(result));
return ESP_ERR_INVALID_STATE;
}
mounted_ = true;
ESP_LOGI(kTag, "system_fs mounted");
return ESP_OK;
}
esp_err_t wifi_provision::config_load(char ssid[33], char password[64], bool& hidden) {
FILE* file = std::fopen(kConfigPath, "r");
if (file == nullptr) {
return ESP_ERR_NOT_FOUND;
}
char text[512]{};
const std::size_t length = std::fread(text, 1, sizeof(text) - 1, file);
const bool overlong = length == sizeof(text) - 1 && std::fgetc(file) != EOF;
std::fclose(file);
if (overlong) {
return ESP_ERR_NOT_FOUND;
}
text[length] = '\0';
return parse_config(text, ssid, password, hidden);
}
esp_err_t wifi_provision::parse_config(const char* text, char ssid[33], char password[64],
bool& hidden) {
if (text == nullptr) {
return ESP_ERR_NOT_FOUND;
}
cJSON* root = cJSON_Parse(text);
if (root == nullptr) {
return ESP_ERR_NOT_FOUND;
}
const cJSON* ssid_item = cJSON_GetObjectItem(root, "ssid");
const cJSON* password_item = cJSON_GetObjectItem(root, "password");
const cJSON* hidden_item = cJSON_GetObjectItem(root, "hidden");
esp_err_t result = ESP_ERR_NOT_FOUND;
if (cJSON_IsString(ssid_item) && cJSON_IsString(password_item) &&
(hidden_item == nullptr || cJSON_IsBool(hidden_item))) {
const char* ssid_value = ssid_item->valuestring;
const char* password_value = password_item->valuestring;
if (ssid_value != nullptr && password_value != nullptr) {
const std::size_t ssid_length = std::strlen(ssid_value);
const std::size_t password_length = std::strlen(password_value);
if (ssid_length >= 1 && ssid_length <= 32 && password_length >= 8 &&
password_length <= 63) {
std::memcpy(ssid, ssid_value, ssid_length + 1);
std::memcpy(password, password_value, password_length + 1);
hidden = cJSON_IsTrue(hidden_item) != 0;
result = ESP_OK;
}
}
}
cJSON_Delete(root);
return result;
}
esp_err_t wifi_provision::config_save(const char* ssid, const char* password, bool hidden) {
if (!mounted_ || ssid == nullptr || password == nullptr) {
return ESP_ERR_INVALID_STATE;
}
const std::size_t ssid_length = std::strlen(ssid);
const std::size_t password_length = std::strlen(password);
if (ssid_length == 0 || ssid_length > 32 || password_length < 8 || password_length > 63) {
return ESP_ERR_INVALID_ARG;
}
cJSON* root = cJSON_CreateObject();
if (root == nullptr) {
return ESP_ERR_NO_MEM;
}
esp_err_t result = ESP_ERR_NO_MEM;
if (cJSON_AddStringToObject(root, "ssid", ssid) != nullptr &&
cJSON_AddStringToObject(root, "password", password) != nullptr &&
cJSON_AddBoolToObject(root, "hidden", hidden) != nullptr) {
char* text = cJSON_Print(root);
if (text != nullptr) {
result = write_config_atomic(text);
cJSON_free(text);
}
}
cJSON_Delete(root);
return result;
}
esp_err_t wifi_provision::write_config_atomic(const char* text) {
const int descriptor = open(kTempPath, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (descriptor < 0) {
return ESP_ERR_INVALID_STATE;
}
const std::size_t length = std::strlen(text);
std::size_t written = 0;
while (written < length) {
const ssize_t chunk = write(descriptor, text + written, length - written);
if (chunk <= 0) {
close(descriptor);
std::remove(kTempPath);
return ESP_FAIL;
}
written += static_cast<std::size_t>(chunk);
}
const int sync_result = fsync(descriptor);
const int close_result = close(descriptor);
if (sync_result != 0 || close_result != 0) {
std::remove(kTempPath);
return ESP_FAIL;
}
if (std::rename(kTempPath, kConfigPath) != 0) {
std::remove(kTempPath);
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t wifi_provision::config_clear() {
if (std::remove(kConfigPath) != 0 && errno != ENOENT) {
return ESP_FAIL;
}
if (std::remove(kTempPath) != 0 && errno != ENOENT) {
return ESP_FAIL;
}
return ESP_OK;
}
bool wifi_provision::config_present() {
char ssid[33]{};
char password[64]{};
bool hidden = false;
const bool present = config_load(ssid, password, hidden) == ESP_OK;
wipe_credentials(ssid, password);
return present;
}
esp_err_t wifi_provision::start_saved_or_pending() {
const esp_err_t runtime = ensure_runtime();
if (runtime != ESP_OK) {
return runtime;
}
char ssid[33]{};
char password[64]{};
bool hidden = false;
const esp_err_t result = config_load(ssid, password, hidden);
if (result == ESP_OK) {
const esp_err_t connect = wifi_.connect_stored(ssid, password, hidden);
wipe_credentials(ssid, password);
return connect;
}
wipe_credentials(ssid, password);
ESP_LOGI(kTag, "wifi provision pending");
return start_provision();
}
esp_err_t wifi_provision::ensure_runtime() {
if (runtime_ready_.load()) {
return ESP_OK;
}
esp_err_t result = esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
&wifi_provision::event_trampoline, this);
if (result == ESP_OK) {
result = esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
&wifi_provision::event_trampoline, this);
}
if (result == ESP_OK && monitor_ == nullptr) {
if (xTaskCreate(&wifi_provision::monitor_trampoline, "prov-mon", 6144, this, 5,
&monitor_) != pdPASS) {
monitor_ = nullptr;
result = ESP_ERR_NO_MEM;
}
}
if (result == ESP_OK) {
runtime_ready_.store(true);
}
return result;
}
void wifi_provision::build_ap_name(char (&name)[17]) const {
const status_snapshot value = status_.snapshot();
const std::size_t length = bounded_length(value.device_id, sizeof(value.device_id));
const char* suffix = length >= 4 ? value.device_id + length - 4 : "0000";
std::snprintf(name, sizeof(name), "Frame-Setup-%.4s", suffix);
}
esp_err_t wifi_provision::start_provision() {
if (mutex_ == nullptr) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
if (ap_active_.load()) {
xSemaphoreGive(mutex_);
return ESP_OK;
}
esp_err_t result = ensure_runtime();
if (result == ESP_OK) {
result = esp_wifi_stop();
}
if (result == ESP_OK) {
result = esp_wifi_set_mode(WIFI_MODE_APSTA);
}
if (result == ESP_OK && !ap_netif_created_) {
if (esp_netif_create_default_wifi_ap() == nullptr) {
result = ESP_ERR_NO_MEM;
} else {
ap_netif_created_ = true;
}
}
char ap_name[17]{};
if (result == ESP_OK) {
build_ap_name(ap_name);
wifi_config_t ap{};
const std::size_t ssid_length = std::strlen(ap_name);
std::memcpy(ap.ap.ssid, ap_name, ssid_length);
ap.ap.ssid_len = static_cast<uint8_t>(ssid_length);
ap.ap.channel = 1;
ap.ap.authmode = WIFI_AUTH_OPEN;
ap.ap.max_connection = 2;
ap.ap.beacon_interval = 100;
result = esp_wifi_set_config(WIFI_IF_AP, &ap);
}
if (result == ESP_OK) {
result = esp_wifi_start();
}
if (result == ESP_OK) {
result = start_httpd();
}
if (result == ESP_OK) {
ap_active_.store(true);
status_.update([](status_snapshot& value) { value.ap_active = true; });
ESP_LOGI(kTag, "provision AP up %s at 192.168.4.1", ap_name);
} else {
ESP_LOGW(kTag, "provision AP start failed: %s", esp_err_to_name(result));
status_.update([](status_snapshot& value) { value.ap_active = false; });
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_start();
}
xSemaphoreGive(mutex_);
return result;
}
esp_err_t wifi_provision::stop_provision() {
if (mutex_ == nullptr) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
if (!ap_active_.load()) {
xSemaphoreGive(mutex_);
return ESP_OK;
}
if (server_ != nullptr) {
httpd_stop(server_);
server_ = nullptr;
}
const esp_err_t result = esp_wifi_set_mode(WIFI_MODE_STA);
if (result == ESP_OK) {
ap_active_.store(false);
status_.update([](status_snapshot& value) { value.ap_active = false; });
ESP_LOGI(kTag, "provision AP down");
} else {
ESP_LOGW(kTag, "provision AP stop failed: %s", esp_err_to_name(result));
}
xSemaphoreGive(mutex_);
return result;
}
esp_err_t wifi_provision::start_httpd() {
if (server_ != nullptr) {
return ESP_OK;
}
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.stack_size = 8192;
config.max_uri_handlers = 8;
config.lru_purge_enable = true;
esp_err_t result = httpd_start(&server_, &config);
if (result != ESP_OK) {
server_ = nullptr;
return result;
}
const httpd_uri_t root{
.uri = "/",
.method = HTTP_GET,
.handler = &wifi_provision::root_handler,
.user_ctx = this,
};
const httpd_uri_t scan{
.uri = "/scan",
.method = HTTP_GET,
.handler = &wifi_provision::scan_handler,
.user_ctx = this,
};
const httpd_uri_t connect{
.uri = "/connect",
.method = HTTP_POST,
.handler = &wifi_provision::connect_handler,
.user_ctx = this,
};
const httpd_uri_t clear{
.uri = "/clear",
.method = HTTP_POST,
.handler = &wifi_provision::clear_handler,
.user_ctx = this,
};
result = httpd_register_uri_handler(server_, &root);
if (result == ESP_OK) {
result = httpd_register_uri_handler(server_, &scan);
}
if (result == ESP_OK) {
result = httpd_register_uri_handler(server_, &connect);
}
if (result == ESP_OK) {
result = httpd_register_uri_handler(server_, &clear);
}
if (result != ESP_OK) {
httpd_stop(server_);
server_ = nullptr;
}
return result;
}
void wifi_provision::monitor_trampoline(void* context) {
static_cast<wifi_provision*>(context)->monitor_loop();
}
void wifi_provision::event_trampoline(void* context, esp_event_base_t base, int32_t id,
void* /*data*/) {
static_cast<wifi_provision*>(context)->handle_event(base, id);
}
void wifi_provision::handle_event(esp_event_base_t base, int32_t id) {
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
has_ip_.store(false);
disconnect_count_.fetch_add(1);
return;
}
if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
has_ip_.store(true);
disconnect_count_.store(0);
no_ip_ticks_.store(0);
if (ap_active_.load()) {
pending_action expected = pending_action::none;
pending_.compare_exchange_strong(expected, pending_action::stop_ap);
}
}
}
void wifi_provision::monitor_loop() {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(kMonitorTickMs));
const pending_action action = pending_.exchange(pending_action::none);
if (action == pending_action::sta_connect) {
stop_provision();
disconnect_count_.store(0);
no_ip_ticks_.store(0);
wifi_.connect_stored(pending_ssid_, pending_password_, pending_hidden_);
std::memset(pending_ssid_, 0, sizeof(pending_ssid_));
std::memset(pending_password_, 0, sizeof(pending_password_));
continue;
}
if (action == pending_action::restart_ap) {
stop_provision();
disconnect_count_.store(0);
no_ip_ticks_.store(0);
start_provision();
continue;
}
if (action == pending_action::stop_ap) {
stop_provision();
continue;
}
bool portal_requested = false;
status_.update([&](status_snapshot& value) {
if (value.ap_mode_requested) {
value.ap_mode_requested = false;
portal_requested = true;
}
});
if (portal_requested) {
wifi_.disconnect();
disconnect_count_.store(0);
no_ip_ticks_.store(0);
start_provision();
continue;
}
const int disconnects = disconnect_count_.load();
if (disconnects >= kFallbackDisconnects) {
ESP_LOGI(kTag, "wifi fallback: %d disconnects without IP", disconnects);
wifi_.disconnect();
disconnect_count_.store(0);
no_ip_ticks_.store(0);
start_provision();
continue;
}
if (wifi_.configured() && !has_ip_.load()) {
const int ticks = no_ip_ticks_.fetch_add(1) + 1;
if (ticks >= kFallbackNoIpSeconds) {
ESP_LOGI(kTag, "wifi fallback: no IP for %ds", ticks);
wifi_.disconnect();
disconnect_count_.store(0);
no_ip_ticks_.store(0);
start_provision();
}
} else {
no_ip_ticks_.store(0);
}
}
}
esp_err_t wifi_provision::scan_networks(provision_ap_info* results, std::size_t capacity,
std::size_t* count) {
*count = 0;
if (results == nullptr || capacity == 0) {
return ESP_ERR_INVALID_ARG;
}
if (mutex_ == nullptr || xSemaphoreTake(mutex_, pdMS_TO_TICKS(5000)) != pdTRUE) {
return ESP_ERR_INVALID_STATE;
}
static wifi_ap_record_t records[kMaxScanRecords];
wifi_scan_config_t scan{};
scan.scan_time.active.min = 0;
scan.scan_time.active.max = 80;
scan.scan_time.passive = 120;
esp_err_t result = esp_wifi_scan_start(&scan, true);
if (result == ESP_OK) {
uint16_t number = static_cast<uint16_t>(kMaxScanRecords);
result = esp_wifi_scan_get_ap_records(&number, records);
if (result == ESP_OK) {
provision_ap_info unique[kMaxScanRecords]{};
std::size_t unique_count = 0;
for (uint16_t i = 0; i < number; ++i) {
const char* ssid = reinterpret_cast<const char*>(records[i].ssid);
const std::size_t ssid_length = bounded_length(ssid, 32);
if (ssid_length == 0) {
continue;
}
std::size_t found = unique_count;
for (std::size_t entry = 0; entry < unique_count; ++entry) {
if (std::memcmp(unique[entry].ssid, ssid, ssid_length) == 0 &&
unique[entry].ssid[ssid_length] == '\0') {
found = entry;
break;
}
}
if (found < unique_count) {
if (records[i].rssi > unique[found].rssi) {
unique[found].rssi = records[i].rssi;
unique[found].secure = records[i].authmode != WIFI_AUTH_OPEN;
}
continue;
}
if (unique_count < kMaxScanRecords) {
std::memcpy(unique[unique_count].ssid, ssid, ssid_length);
unique[unique_count].rssi = records[i].rssi;
unique[unique_count].secure = records[i].authmode != WIFI_AUTH_OPEN;
++unique_count;
}
}
for (std::size_t outer = 1; outer < unique_count; ++outer) {
const provision_ap_info candidate = unique[outer];
std::size_t inner = outer;
while (inner > 0 && unique[inner - 1].rssi < candidate.rssi) {
unique[inner] = unique[inner - 1];
--inner;
}
unique[inner] = candidate;
}
*count = unique_count < capacity ? unique_count : capacity;
std::memcpy(results, unique, *count * sizeof(provision_ap_info));
}
}
xSemaphoreGive(mutex_);
return result;
}
esp_err_t wifi_provision::root_handler(httpd_req_t* request) {
auto* self = static_cast<wifi_provision*>(request->user_ctx);
httpd_resp_set_type(request, HTTPD_TYPE_TEXT);
httpd_resp_set_hdr(request, "Cache-Control", "no-store");
httpd_resp_send_chunk(request, kPageHead, HTTPD_RESP_USE_STRLEN);
provision_ap_info networks[kMaxScanResults]{};
std::size_t count = 0;
const esp_err_t scan_result = self->scan_networks(networks, kMaxScanResults, &count);
if (scan_result != ESP_OK || count == 0) {
httpd_resp_send_chunk(request, "<option value=\"\">(no networks found)</option>\n",
HTTPD_RESP_USE_STRLEN);
}
for (std::size_t entry = 0; entry < count; ++entry) {
char escaped_value[193]{};
char escaped_text[193]{};
html_escape(networks[entry].ssid, escaped_value);
html_escape(networks[entry].ssid, escaped_text);
char option[512]{};
const int written =
std::snprintf(option, sizeof(option), "<option value=\"%s\">%s (%d dBm)</option>\n",
escaped_value, escaped_text, networks[entry].rssi);
if (written > 0) {
httpd_resp_send_chunk(request, option, static_cast<std::size_t>(written));
}
}
httpd_resp_send_chunk(request, kPageTail, HTTPD_RESP_USE_STRLEN);
httpd_resp_send_chunk(request, nullptr, 0);
return ESP_OK;
}
esp_err_t wifi_provision::scan_handler(httpd_req_t* request) {
auto* self = static_cast<wifi_provision*>(request->user_ctx);
provision_ap_info networks[kMaxScanResults]{};
std::size_t count = 0;
const esp_err_t scan_result = self->scan_networks(networks, kMaxScanResults, &count);
cJSON* root = cJSON_CreateObject();
cJSON* array = cJSON_AddArrayToObject(root, "aps");
if (root == nullptr || array == nullptr) {
cJSON_Delete(root);
return httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "scan failed");
}
if (scan_result == ESP_OK) {
for (std::size_t entry = 0; entry < count; ++entry) {
cJSON* item = cJSON_CreateObject();
if (item == nullptr ||
cJSON_AddStringToObject(item, "ssid", networks[entry].ssid) == nullptr ||
cJSON_AddNumberToObject(item, "rssi", static_cast<double>(networks[entry].rssi)) ==
nullptr ||
cJSON_AddBoolToObject(item, "secure", networks[entry].secure ? 1 : 0) == nullptr) {
cJSON_Delete(item);
continue;
}
cJSON_AddItemToArray(array, item);
}
}
char* text = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
if (text == nullptr) {
return httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "scan failed");
}
httpd_resp_set_type(request, HTTPD_TYPE_JSON);
httpd_resp_set_hdr(request, "Cache-Control", "no-store");
const esp_err_t result = httpd_resp_send(request, text, HTTPD_RESP_USE_STRLEN);
cJSON_free(text);
return result;
}
esp_err_t wifi_provision::connect_handler(httpd_req_t* request) {
auto* self = static_cast<wifi_provision*>(request->user_ctx);
if (request->content_len > kMaxBodyLength) {
return httpd_resp_send_err(request, HTTPD_413_CONTENT_TOO_LARGE, "body too large");
}
char body[kMaxBodyLength + 1]{};
std::size_t received = 0;
while (received < request->content_len) {
const int chunk = httpd_req_recv(request, body + received,
static_cast<std::size_t>(request->content_len) - received);
if (chunk <= 0) {
return httpd_resp_send_err(request, HTTPD_408_REQ_TIMEOUT, "body incomplete");
}
received += static_cast<std::size_t>(chunk);
}
char ssid[129]{};
char password[129]{};
bool hidden = false;
parse_form(body, ssid, password, hidden);
std::memset(body, 0, sizeof(body));
const std::size_t ssid_length = std::strlen(ssid);
const std::size_t password_length = std::strlen(password);
if (ssid_length == 0 || ssid_length > 32 || password_length < 8 || password_length > 63) {
std::memset(ssid, 0, sizeof(ssid));
std::memset(password, 0, sizeof(password));
return httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST,
"usage: ssid 1..32 characters, password 8..63 characters");
}
const esp_err_t save_result = self->config_save(ssid, password, hidden);
if (save_result != ESP_OK) {
std::memset(ssid, 0, sizeof(ssid));
std::memset(password, 0, sizeof(password));
ESP_LOGW(kTag, "provision save failed: %s", esp_err_to_name(save_result));
return httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR,
"save failed on device storage");
}
std::memcpy(self->pending_ssid_, ssid, ssid_length + 1);
std::memcpy(self->pending_password_, password, password_length + 1);
self->pending_hidden_ = hidden;
self->pending_.store(pending_action::sta_connect);
std::memset(ssid, 0, sizeof(ssid));
std::memset(password, 0, sizeof(password));
httpd_resp_set_type(request, HTTPD_TYPE_TEXT);
return httpd_resp_send(request, kConnectPage, HTTPD_RESP_USE_STRLEN);
}
esp_err_t wifi_provision::clear_handler(httpd_req_t* request) {
auto* self = static_cast<wifi_provision*>(request->user_ctx);
const esp_err_t clear_result = self->config_clear();
if (clear_result != ESP_OK) {
return httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "clear failed");
}
self->wifi_.disconnect();
self->pending_.store(pending_action::restart_ap);
httpd_resp_set_type(request, HTTPD_TYPE_TEXT);
return httpd_resp_send(request, kClearPage, HTTPD_RESP_USE_STRLEN);
}
} // namespace frame::m1
@@ -0,0 +1,83 @@
#pragma once
#include <atomic>
#include <cstddef>
#include <cstdint>
#include "esp_err.h"
#include "esp_event.h"
#include "esp_http_server.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "hardware_status.hh"
#include "wifi_service.hh"
namespace frame::m1 {
struct provision_ap_info {
char ssid[33]{};
int8_t rssi{};
bool secure{};
};
class wifi_provision {
public:
wifi_provision(hardware_status& status, wifi_service& wifi) : status_(status), wifi_(wifi) {
mutex_ = xSemaphoreCreateMutex();
}
wifi_provision(const wifi_provision&) = delete;
wifi_provision& operator=(const wifi_provision&) = delete;
esp_err_t initialize();
esp_err_t config_load(char ssid[33], char password[64], bool& hidden);
esp_err_t config_save(const char* ssid, const char* password, bool hidden);
esp_err_t config_clear();
esp_err_t start_saved_or_pending();
esp_err_t start_provision();
esp_err_t stop_provision();
[[nodiscard]] bool ap_active() const { return ap_active_.load(); }
[[nodiscard]] bool config_present();
esp_err_t scan_networks(provision_ap_info* results, std::size_t capacity, std::size_t* count);
static esp_err_t parse_config(const char* text, char ssid[33], char password[64], bool& hidden);
private:
enum class pending_action : uint8_t { none, sta_connect, restart_ap, stop_ap };
static void monitor_trampoline(void* context);
static void event_trampoline(void* context, esp_event_base_t base, int32_t id, void* data);
static esp_err_t root_handler(httpd_req_t* request);
static esp_err_t scan_handler(httpd_req_t* request);
static esp_err_t connect_handler(httpd_req_t* request);
static esp_err_t clear_handler(httpd_req_t* request);
void monitor_loop();
void handle_event(esp_event_base_t base, int32_t id);
esp_err_t ensure_runtime();
esp_err_t start_httpd();
void build_ap_name(char (&name)[17]) const;
esp_err_t write_config_atomic(const char* text);
hardware_status& status_;
wifi_service& wifi_;
SemaphoreHandle_t mutex_{};
httpd_handle_t server_{};
TaskHandle_t monitor_{};
bool mounted_{};
bool ap_netif_created_{};
char pending_ssid_[33]{};
char pending_password_[64]{};
bool pending_hidden_{};
std::atomic<bool> runtime_ready_{};
std::atomic<bool> ap_active_{};
std::atomic<bool> has_ip_{};
std::atomic<pending_action> pending_{pending_action::none};
std::atomic<int> disconnect_count_{};
std::atomic<int> no_ip_ticks_{};
};
} // namespace frame::m1
+168
View File
@@ -0,0 +1,168 @@
#include "wifi_service.hh"
#include <cstdio>
#include <cstring>
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
namespace frame::m1 {
namespace {
constexpr char kTag[] = "frame-wifi";
} // namespace
esp_err_t wifi_service::initialize() {
esp_err_t result = esp_netif_init();
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
return result;
}
result = esp_event_loop_create_default();
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
return result;
}
if (esp_netif_create_default_wifi_sta() == nullptr) {
return ESP_ERR_NO_MEM;
}
wifi_init_config_t configuration = WIFI_INIT_CONFIG_DEFAULT();
result = esp_wifi_init(&configuration);
if (result != ESP_OK) {
return result;
}
result = esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_service::event_handler,
this);
if (result != ESP_OK) {
return result;
}
result = esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_service::event_handler,
this);
if (result != ESP_OK) {
return result;
}
result = esp_wifi_set_storage(WIFI_STORAGE_RAM);
if (result == ESP_OK) {
result = esp_wifi_set_mode(WIFI_MODE_STA);
}
if (result == ESP_OK) {
result = esp_wifi_start();
}
initialized_ = result == ESP_OK;
status_.update([&](status_snapshot& value) {
value.wifi = wifi_state::unconfigured;
value.wifi_error = result;
});
return result;
}
esp_err_t wifi_service::connect_ephemeral(const char* ssid, const char* password, bool hidden) {
return connect_sta(ssid, password, hidden);
}
esp_err_t wifi_service::connect_stored(const char* ssid, const char* password, bool hidden) {
return connect_sta(ssid, password, hidden);
}
esp_err_t wifi_service::connect_sta(const char* ssid, const char* password, bool hidden) {
if (!initialized_ || ssid == nullptr || password == nullptr) {
return ESP_ERR_INVALID_STATE;
}
const std::size_t ssid_length = std::strlen(ssid);
const std::size_t password_length = std::strlen(password);
if (ssid_length == 0 || ssid_length > 32 || password_length < 8 || password_length > 63) {
return ESP_ERR_INVALID_ARG;
}
wifi_config_t config{};
std::memcpy(config.sta.ssid, ssid, ssid_length);
std::memcpy(config.sta.password, password, password_length);
config.sta.scan_method = hidden ? WIFI_FAST_SCAN : WIFI_ALL_CHANNEL_SCAN;
config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
config.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
configured_.store(false);
esp_wifi_disconnect();
esp_err_t result = esp_wifi_set_config(WIFI_IF_STA, &config);
if (result == ESP_OK) {
status_.update([&](status_snapshot& value) {
value.ssid_configured = true;
value.ip_address[0] = '\0';
value.wifi = wifi_state::connecting;
value.wifi_error = ESP_OK;
});
configured_.store(true);
result = esp_wifi_connect();
} else {
status_.update([](status_snapshot& value) {
value.ssid_configured = false;
value.ip_address[0] = '\0';
value.wifi = wifi_state::unconfigured;
value.wifi_error = ESP_ERR_WIFI_STATE;
});
}
std::memset(&config, 0, sizeof(config));
return result;
}
esp_err_t wifi_service::disconnect() {
configured_.store(false);
esp_err_t result = esp_wifi_disconnect();
if (result == ESP_ERR_WIFI_NOT_CONNECT) {
result = ESP_OK;
}
wifi_config_t empty_config{};
const esp_err_t clear_result = esp_wifi_set_config(WIFI_IF_STA, &empty_config);
if (result == ESP_OK) {
result = clear_result;
}
status_.update([&](status_snapshot& value) {
std::memset(value.ip_address, 0, sizeof(value.ip_address));
value.ssid_configured = false;
value.wifi = wifi_state::unconfigured;
value.wifi_error = result;
});
return result;
}
esp_err_t wifi_service::reconnect() {
if (!initialized_ || !configured_.load()) {
return ESP_ERR_INVALID_STATE;
}
status_.update([](status_snapshot& value) { value.wifi = wifi_state::connecting; });
return esp_wifi_connect();
}
void wifi_service::event_handler(void* context, esp_event_base_t base, int32_t id, void* data) {
static_cast<wifi_service*>(context)->handle_event(base, id, data);
}
void wifi_service::handle_event(esp_event_base_t base, int32_t id, void* data) {
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
const bool configured = configured_.load();
status_.update([&](status_snapshot& value) {
value.ip_address[0] = '\0';
value.wifi = configured ? wifi_state::disconnected : wifi_state::unconfigured;
});
if (configured) {
const esp_err_t result = esp_wifi_connect();
if (result != ESP_OK) {
ESP_LOGW(kTag, "Reconnect failed: %s", esp_err_to_name(result));
}
}
return;
}
if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
const auto* event = static_cast<const ip_event_got_ip_t*>(data);
status_.update([&](status_snapshot& value) {
std::snprintf(value.ip_address, sizeof(value.ip_address), IPSTR,
IP2STR(&event->ip_info.ip));
value.wifi = wifi_state::connected;
value.wifi_error = ESP_OK;
});
}
}
} // namespace frame::m1
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <atomic>
#include <cstddef>
#include "esp_err.h"
#include "esp_event.h"
#include "hardware_status.hh"
namespace frame::m1 {
class wifi_service {
public:
explicit wifi_service(hardware_status& status) : status_(status) {}
wifi_service(const wifi_service&) = delete;
wifi_service& operator=(const wifi_service&) = delete;
esp_err_t initialize();
esp_err_t connect_ephemeral(const char* ssid, const char* password, bool hidden);
esp_err_t connect_stored(const char* ssid, const char* password, bool hidden);
esp_err_t disconnect();
esp_err_t reconnect();
[[nodiscard]] bool configured() const { return configured_.load(); }
private:
static void event_handler(void* context, esp_event_base_t base, int32_t id, void* data);
void handle_event(esp_event_base_t base, int32_t id, void* data);
esp_err_t connect_sta(const char* ssid, const char* password, bool hidden);
hardware_status& status_;
bool initialized_{};
std::atomic<bool> configured_{};
};
} // namespace frame::m1
+44
View File
@@ -0,0 +1,44 @@
CONFIG_IDF_TARGET="esp32s3"
CONFIG_ESPTOOLPY_FLASHMODE_QIO=y
CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_FREERTOS_HZ=1000
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=2
CONFIG_SPIRAM=y
CONFIG_SPIRAM_MODE_OCT=y
CONFIG_SPIRAM_TYPE_AUTO=y
CONFIG_SPIRAM_SPEED_80M=y
CONFIG_SPIRAM_USE_MALLOC=y
# CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM is not set
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="../../../partitions.csv"
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
CONFIG_ESP_CONSOLE_SECONDARY_NONE=y
CONFIG_ESP_TASK_WDT_EN=y
CONFIG_ESP_TASK_WDT_INIT=y
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=y
CONFIG_ESP_COREDUMP_CHECK_BOOT=y
CONFIG_ESP_COREDUMP_STACK_SIZE=2048
CONFIG_ESP_COREDUMP_LOGS=y
CONFIG_FATFS_LFN_HEAP=y
CONFIG_FATFS_MAX_LFN=128
CONFIG_COMPILER_OPTIMIZATION_DEBUG=y
CONFIG_COMPILER_CXX_EXCEPTIONS=n
CONFIG_COMPILER_CXX_RTTI=n
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
CONFIG_LV_USE_FLEX=y
CONFIG_LV_FONT_MONTSERRAT_16=y
CONFIG_LV_FONT_MONTSERRAT_24=y
CONFIG_LV_FONT_MONTSERRAT_40=y
+20
View File
@@ -0,0 +1,20 @@
cmake_minimum_required(VERSION 3.25)
set(FRAME_REQUIRED_IDF_TAG "v6.0.2" CACHE STRING
"Exact ESP-IDF release tag required by the architecture")
set(FRAME_REQUIRED_IDF_COMMIT "7101770dc6db2667b3c477cc31365dd1acd6db4e" CACHE STRING
"Exact ESP-IDF commit required by the architecture")
set(FRAME_REQUIRED_COMPILER_VERSION "15.2.0" CACHE STRING
"Exact Xtensa GCC version required by the architecture")
include("${CMAKE_CURRENT_LIST_DIR}/../../../cmake/FramePlatform.cmake")
frame_require_esp_idf("${FRAME_REQUIRED_IDF_TAG}")
set(EXTRA_COMPONENT_DIRS
"${CMAKE_CURRENT_LIST_DIR}/../../common/components")
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(frame_poc_a)
frame_verify_platform("${FRAME_REQUIRED_IDF_COMMIT}" "${FRAME_REQUIRED_COMPILER_VERSION}")
idf_build_set_property(CXX_COMPILE_OPTIONS "-std=c++26" APPEND)
+27
View File
@@ -0,0 +1,27 @@
{
"version": 3,
"cmakeMinimumRequired": {
"major": 3,
"minor": 25,
"patch": 0
},
"configurePresets": [
{
"name": "default",
"displayName": "PoC-A development",
"description": "ESP-IDF v6.0.2 PoC-A configuration",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/default",
"cacheVariables": {
"IDF_TARGET": "esp32s3",
"SDKCONFIG": "${sourceDir}/build/default/sdkconfig"
}
}
],
"buildPresets": [
{
"name": "default",
"configurePreset": "default"
}
]
}
+7
View File
@@ -0,0 +1,7 @@
# PoC-A ESP-IDF Test Application
This directory is a standard ESP-IDF project. Open `poc/poc-a.code-workspace`, select the `v6.0.2` setup and `esp32s3` target for the `poc-a` folder, then use the extension Build, Flash, Monitor, and Size commands.
The application consumes `frame_poc_runtime` through `EXTRA_COMPONENT_DIRS`; shared PoC runtime code must use `idf_component_register` and must not be added as an ordinary CMake target.
The separate `poc/host` project is only for ABI and pure state-model tests that do not produce ESP32 firmware.
+5
View File
@@ -0,0 +1,5 @@
idf_component_register(
SRCS "poc_a_main.cc"
PRIV_REQUIRES frame_poc_runtime unity)
target_compile_options(${COMPONENT_LIB} PRIVATE -std=c++26)
+42
View File
@@ -0,0 +1,42 @@
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include "frame_poc/frame_abi.h"
#include "unity.h"
TEST_CASE("C ABI header layout is stable", "[poc-a][abi]")
{
TEST_ASSERT_EQUAL_UINT32(0, offsetof(frame_abi_header_t, struct_size));
TEST_ASSERT_EQUAL_UINT32(16, sizeof(frame_abi_header_t));
TEST_ASSERT_EQUAL_UINT32(8, sizeof(plugin_instance_handle_t));
}
TEST_CASE("C ABI compatibility checks size version and features", "[poc-a][abi]")
{
constexpr uint64_t required_feature = UINT64_C(1) << 12;
const frame_abi_header_t offered{
.struct_size = sizeof(frame_abi_header_t),
.abi_major = FRAME_ABI_MAJOR,
.abi_minor = FRAME_ABI_MINOR,
.feature_bits = required_feature,
};
TEST_ASSERT_TRUE(frame_abi_supports(
&offered, FRAME_ABI_MAJOR, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t), required_feature));
TEST_ASSERT_FALSE(frame_abi_supports(
&offered, FRAME_ABI_MAJOR + 1, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t), required_feature));
TEST_ASSERT_FALSE(frame_abi_supports(
&offered, FRAME_ABI_MAJOR, FRAME_ABI_MINOR,
sizeof(frame_abi_header_t) + 1, required_feature));
}
static_assert(__cplusplus >= 202302L);
static_assert(std::is_standard_layout_v<frame_abi_header_t>);
extern "C" void app_main(void)
{
unity_run_menu();
}
@@ -0,0 +1 @@
idf_component_register(INCLUDE_DIRS "include")
@@ -0,0 +1,97 @@
#ifndef FRAME_POC_FRAME_ABI_H
#define FRAME_POC_FRAME_ABI_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef int32_t frame_err_t;
enum {
FRAME_OK = 0,
FRAME_ERR_INVALID_PTR = -1,
FRAME_ERR_TIMEOUT = -2,
FRAME_ERR_QUOTA_EXCEEDED = -3,
FRAME_ERR_LEASE_FULL = -4,
FRAME_ERR_PLUGIN_NOT_FOUND = -5,
FRAME_ERR_DEP_CYCLE = -6,
FRAME_ERR_ABI_MISMATCH = -7,
FRAME_ERR_BUSY = -8,
FRAME_ERR_INVALID_CONTEXT = -9,
FRAME_ERR_NET_AGAIN = -10,
FRAME_ERR_WDT_TRIGGERED = -11,
FRAME_ERR_ROLLBACK_FAILED = -12,
FRAME_ERR_QUEUE_FULL = -13,
FRAME_ERR_PLUGIN_STOPPING = -14,
FRAME_ERR_CANCELLED = -15,
FRAME_ERR_RESTART_REQUIRED = -16,
FRAME_ERR_SIGNATURE_INVALID = -17,
FRAME_ERR_PACKAGE_INVALID = -18,
FRAME_ERR_HASH_MISMATCH = -19,
FRAME_ERR_FS_NOT_FOUND = -20,
FRAME_ERR_FS_TIMEOUT = -21,
FRAME_ERR_FS_IO = -22,
FRAME_ERR_FS_NO_TF = -23,
FRAME_ERR_FS_RECOVERING = -24,
FRAME_ERR_DURABILITY_DEGRADED = -25,
FRAME_ERR_CAPACITY = -26,
FRAME_ERR_NOT_FOUND = -27,
FRAME_ERR_INVALID_ARGUMENT = -28,
FRAME_ERR_RATE_LIMITED = -29,
FRAME_ERR_MEM_FRAGMENTED = -30,
FRAME_ERR_SEMVER_MISMATCH = -31,
FRAME_ERR_IRAM_EXHAUSTED = -32,
FRAME_ERR_STATE_SCHEMA = -33,
FRAME_ERR_EPOCH_ROLLBACK = -34,
FRAME_ERR_TARGET_MISMATCH = -35,
};
enum {
FRAME_ABI_MAJOR = 1,
FRAME_ABI_MINOR = 0,
};
typedef uint64_t plugin_instance_handle_t;
typedef uint64_t frame_buffer_handle_t;
typedef uint64_t steady_timer_handle_t;
typedef uint64_t managed_task_handle_t;
typedef uint64_t resource_handle_t;
typedef uint64_t frame_request_handle_t;
typedef uint64_t frame_allocation_handle_t;
typedef struct {
uint32_t struct_size;
uint16_t abi_major;
uint16_t abi_minor;
uint64_t feature_bits;
} frame_abi_header_t;
typedef struct {
void (*invoke)(void* user);
void (*destroy)(void* user);
void* user;
} frame_post_operation_t;
typedef struct {
void (*complete)(void* user, frame_err_t err);
void (*destroy)(void* user);
void* user;
} frame_completion_operation_t;
static inline bool frame_abi_supports(const frame_abi_header_t* offered, uint16_t required_major,
uint16_t required_minor, uint32_t required_size,
uint64_t required_features) {
return offered != NULL && offered->abi_major == required_major &&
offered->abi_minor >= required_minor && offered->struct_size >= required_size &&
(offered->feature_bits & required_features) == required_features;
}
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,124 @@
#ifndef FRAME_POC_FRAME_HANDLE_HH
#define FRAME_POC_FRAME_HANDLE_HH
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include "frame_poc/frame_abi.h"
namespace frame::poc {
struct handle_owner {
plugin_instance_handle_t instance;
uint64_t generation;
};
enum class handle_type : uint16_t {
invalid = 0,
buffer = 1,
timer,
managed_task,
resource,
storage_request,
network_request,
};
template <typename Value, size_t Capacity> class handle_table {
static_assert(Capacity > 0);
static_assert(Capacity <= std::numeric_limits<uint32_t>::max());
public:
frame_err_t acquire(handle_owner owner, handle_type type, Value value, uint64_t* out_handle) {
if (out_handle == nullptr || owner.instance == 0 || owner.generation == 0) {
return FRAME_ERR_INVALID_ARGUMENT;
}
for (size_t slot = 0; slot < entries_.size(); ++slot) {
entry& candidate = entries_[slot];
if (candidate.live) {
continue;
}
if (candidate.retired) {
continue;
}
candidate.live = true;
candidate.owner = owner;
candidate.type = type;
candidate.value = value;
*out_handle = encode(slot, candidate.epoch);
return FRAME_OK;
}
return FRAME_ERR_CAPACITY;
}
frame_err_t get(uint64_t handle, handle_owner owner, handle_type type, Value** out_value) {
if (out_value == nullptr) {
return FRAME_ERR_INVALID_PTR;
}
entry* candidate = find(handle);
if (candidate == nullptr || candidate->owner.instance != owner.instance ||
candidate->owner.generation != owner.generation || candidate->type != type) {
return FRAME_ERR_INVALID_PTR;
}
*out_value = &candidate->value;
return FRAME_OK;
}
frame_err_t release(uint64_t handle, handle_owner owner, handle_type type) {
entry* candidate = find(handle);
if (candidate == nullptr || candidate->owner.instance != owner.instance ||
candidate->owner.generation != owner.generation || candidate->type != type) {
return FRAME_ERR_INVALID_PTR;
}
candidate->live = false;
candidate->owner = {};
if (candidate->epoch == std::numeric_limits<uint32_t>::max()) {
candidate->retired = true;
} else {
++candidate->epoch;
}
return FRAME_OK;
}
private:
struct entry {
handle_owner owner{};
handle_type type{handle_type::invalid};
Value value{};
uint32_t epoch{1};
bool live{false};
bool retired{false};
};
static uint64_t encode(size_t slot, uint32_t epoch) {
return (static_cast<uint64_t>(epoch) << 32) | (static_cast<uint64_t>(slot) + 1);
}
entry* find(uint64_t handle) {
const uint32_t encoded_slot = static_cast<uint32_t>(handle);
const uint32_t epoch = static_cast<uint32_t>(handle >> 32);
if (encoded_slot == 0 || epoch == 0) {
return nullptr;
}
const size_t slot = encoded_slot - 1;
if (slot >= entries_.size()) {
return nullptr;
}
entry& candidate = entries_[slot];
return candidate.live && candidate.epoch == epoch ? &candidate : nullptr;
}
std::array<entry, Capacity> entries_{};
};
} // namespace frame::poc
#endif
@@ -0,0 +1,118 @@
#ifndef FRAME_POC_LIFECYCLE_STATE_HH
#define FRAME_POC_LIFECYCLE_STATE_HH
#include <cstdint>
#include "frame_poc/frame_abi.h"
namespace frame::poc {
enum class plugin_state : uint8_t {
staged,
loading,
prepared,
active,
pausing,
paused,
quiescing,
unloading,
unloaded,
failed_restart_required,
};
enum class lifecycle_event : uint8_t {
begin_load,
prepare_succeeded,
activation_committed,
begin_pause,
pause_succeeded,
resume_succeeded,
begin_quiesce,
quiesce_succeeded,
unload_succeeded,
discard_candidate,
fail_restart_required,
};
struct transition_result {
frame_err_t error;
plugin_state next;
};
constexpr bool contains_plugin_code(plugin_state state) {
return state != plugin_state::staged && state != plugin_state::unloaded &&
state != plugin_state::failed_restart_required;
}
constexpr transition_result transition(plugin_state current, lifecycle_event event) {
if (event == lifecycle_event::fail_restart_required && contains_plugin_code(current)) {
return {FRAME_OK, plugin_state::failed_restart_required};
}
switch (current) {
case plugin_state::staged:
if (event == lifecycle_event::begin_load) {
return {FRAME_OK, plugin_state::loading};
}
if (event == lifecycle_event::discard_candidate) {
return {FRAME_OK, plugin_state::unloaded};
}
break;
case plugin_state::loading:
if (event == lifecycle_event::prepare_succeeded) {
return {FRAME_OK, plugin_state::prepared};
}
if (event == lifecycle_event::discard_candidate) {
return {FRAME_OK, plugin_state::unloaded};
}
break;
case plugin_state::prepared:
if (event == lifecycle_event::activation_committed) {
return {FRAME_OK, plugin_state::active};
}
if (event == lifecycle_event::discard_candidate) {
return {FRAME_OK, plugin_state::unloaded};
}
break;
case plugin_state::active:
if (event == lifecycle_event::begin_pause) {
return {FRAME_OK, plugin_state::pausing};
}
if (event == lifecycle_event::begin_quiesce) {
return {FRAME_OK, plugin_state::quiescing};
}
break;
case plugin_state::pausing:
if (event == lifecycle_event::pause_succeeded) {
return {FRAME_OK, plugin_state::paused};
}
break;
case plugin_state::paused:
if (event == lifecycle_event::resume_succeeded) {
return {FRAME_OK, plugin_state::active};
}
if (event == lifecycle_event::begin_quiesce) {
return {FRAME_OK, plugin_state::quiescing};
}
break;
case plugin_state::quiescing:
if (event == lifecycle_event::quiesce_succeeded) {
return {FRAME_OK, plugin_state::unloading};
}
break;
case plugin_state::unloading:
if (event == lifecycle_event::unload_succeeded) {
return {FRAME_OK, plugin_state::unloaded};
}
break;
case plugin_state::unloaded:
case plugin_state::failed_restart_required:
break;
}
return {FRAME_ERR_INVALID_ARGUMENT, current};
}
} // namespace frame::poc
#endif
+88
View File
@@ -0,0 +1,88 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://frame.local/schemas/poc-evidence-v1.json",
"title": "Frame architecture gate evidence manifest",
"type": "object",
"additionalProperties": false,
"required": [
"schema_version",
"gate",
"run_id",
"verdict",
"started_at",
"finished_at",
"source",
"platform",
"artifacts"
],
"properties": {
"schema_version": { "const": 1 },
"gate": { "enum": ["A", "B", "C", "D", "E", "M1"] },
"run_id": { "type": "string", "minLength": 1, "maxLength": 128 },
"verdict": { "enum": ["PASS", "FAIL", "BLOCKED"] },
"started_at": { "type": "string", "format": "date-time" },
"finished_at": { "type": "string", "format": "date-time" },
"source": {
"type": "object",
"additionalProperties": false,
"required": ["repository_commit", "dirty", "project_document_sha256"],
"properties": {
"repository_commit": { "type": "string", "pattern": "^[0-9a-f]{40}$" },
"dirty": { "type": "boolean" },
"project_document_sha256": { "$ref": "#/$defs/sha256" }
}
},
"platform": {
"type": "object",
"additionalProperties": false,
"required": ["idf_tag", "compiler", "target", "sdkconfig_sha256"],
"properties": {
"idf_tag": { "const": "v6.0.2" },
"idf_commit": { "type": "string", "pattern": "^[0-9a-f]{40}$" },
"compiler": { "type": "string", "minLength": 1 },
"target": { "const": "esp32s3" },
"sdkconfig_sha256": { "$ref": "#/$defs/sha256" },
"loader_commit": { "type": ["string", "null"], "pattern": "^[0-9a-f]{40}$" }
}
},
"hardware": {
"type": ["object", "null"],
"additionalProperties": false,
"required": ["board_id", "board_revision"],
"properties": {
"board_id": { "type": "string", "minLength": 1 },
"board_revision": { "type": "string", "minLength": 1 },
"display_id": { "type": ["string", "null"] },
"sd_card_id": { "type": ["string", "null"] },
"power_fixture_id": { "type": ["string", "null"] }
}
},
"metrics": {
"type": "object",
"additionalProperties": {
"type": ["number", "integer", "string", "boolean", "null"]
}
},
"artifacts": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": false,
"required": ["name", "uri", "sha256"],
"properties": {
"name": { "type": "string", "minLength": 1 },
"uri": { "type": "string", "minLength": 1 },
"sha256": { "$ref": "#/$defs/sha256" }
}
}
},
"notes": { "type": "string" }
},
"$defs": {
"sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
}
}
}