Add poweroff function & status LED. Include 3D files for Seeed XIAO

This commit is contained in:
Matt
2025-12-13 17:38:18 +00:00
parent c762e0d632
commit 00c3c85c67
6 changed files with 4258 additions and 118 deletions

View File

@@ -1,3 +1,9 @@
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "cJSON.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
@@ -5,20 +11,16 @@
#include "esp_event.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_sleep.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// Tag for logging
static const char *TAG = "ESP-SCOPE";
static const char* TAG = "ESP-SCOPE";
// WiFi configuration from Kconfig
/* See untracked wifi-credentials.h */
@@ -65,7 +67,6 @@ static httpd_handle_t s_server = NULL;
static adc_continuous_handle_t adc_handle = NULL;
// Single client support for simplicity, or use a list for multiple
static int s_ws_client_fd = -1;
@@ -78,40 +79,38 @@ static uint16_t s_test_hz = 100;
// Forward declarations
static void wifi_init_sta(void);
static void continuous_adc_init(adc_channel_t *channel, uint8_t channel_num,
adc_continuous_handle_t *out_handle);
static esp_err_t ws_handler(httpd_req_t *req);
static void continuous_adc_init(adc_channel_t* channel, uint8_t channel_num,
adc_continuous_handle_t* out_handle);
static esp_err_t ws_handler(httpd_req_t* req);
// Forward declarations
static void wifi_init_sta(void);
static void continuous_adc_init(adc_channel_t *channel, uint8_t channel_num,
adc_continuous_handle_t *out_handle);
static esp_err_t ws_handler(httpd_req_t *req);
static void continuous_adc_init(adc_channel_t* channel, uint8_t channel_num,
adc_continuous_handle_t* out_handle);
static esp_err_t ws_handler(httpd_req_t* req);
// Helper to calculate optimal buffer size (approx 50ms latency, max 4096, aligned to 4)
static uint32_t get_optimal_buffer_size(uint32_t sample_rate) {
uint32_t bytes_per_sec = sample_rate * sizeof(adc_digi_output_data_t);
uint32_t target_size = bytes_per_sec / 50; // 20ms (50Hz)
uint32_t bytes_per_sec = sample_rate * sizeof(adc_digi_output_data_t);
uint32_t target_size = bytes_per_sec / 50; // 20ms (50Hz)
// Clamp to min/max
if (target_size < 128) target_size = 128;
if (target_size > ADC_READ_LEN) target_size = ADC_READ_LEN;
// Clamp to min/max
if (target_size < 128) target_size = 128;
if (target_size > ADC_READ_LEN) target_size = ADC_READ_LEN;
// Align to 4 bytes
return (target_size + 3) & ~3;
// Align to 4 bytes
return (target_size + 3) & ~3;
}
/*
* Task to read from ADC Continuous driver
*/
static void adc_read_task(void *arg) {
static void adc_read_task(void* arg) {
esp_err_t ret;
uint32_t ret_num = 0;
uint8_t result[ADC_READ_LEN] = {0};
memset(result, 0xcc, ADC_READ_LEN);
// ADC Init (Moved from app_main)
// TODO: Make this configurable or find a good default pin.
// For ESP32C6 ADC1 Channel 0 is usually GPIO 0. Let's use Channel 0 for now.
@@ -157,7 +156,6 @@ static void adc_read_task(void *arg) {
if (ret == ESP_OK) {
// ESP_LOGI(TAG, "ret is %x, ret_num is %"PRIu32" bytes", ret, ret_num);
// OPTIMIZED BATCH SENDING
// We have `ret_num` bytes of data in `result`.
// It contains `adc_digi_output_data_t` structs (4 bytes each).
@@ -166,39 +164,37 @@ static void adc_read_task(void *arg) {
// So we have 1/2 the size.
if (s_ws_client_fd != -1) {
// Allocate a small temp buffer on stack or static to avoid malloc in loop
// ret_num is up to ADC_READ_LEN (1024). 1024 / 4 = 256 samples.
// 256 * 2 bytes = 512 bytes output. Stack safe.
uint16_t out_buf[ADC_READ_LEN / sizeof(adc_digi_output_data_t)];
int out_idx = 0;
// Allocate a small temp buffer on stack or static to avoid malloc in loop
// ret_num is up to ADC_READ_LEN (1024). 1024 / 4 = 256 samples.
// 256 * 2 bytes = 512 bytes output. Stack safe.
uint16_t out_buf[ADC_READ_LEN / sizeof(adc_digi_output_data_t)];
int out_idx = 0;
for (int i = 0; i < ret_num; i += sizeof(adc_digi_output_data_t)) {
adc_digi_output_data_t* p = (adc_digi_output_data_t*)&result[i];
uint32_t val = ADC_GET_DATA(p);
out_buf[out_idx++] = (uint16_t)val;
}
for (int i = 0; i < ret_num; i += sizeof(adc_digi_output_data_t)) {
adc_digi_output_data_t *p = (adc_digi_output_data_t *)&result[i];
uint32_t val = ADC_GET_DATA(p);
out_buf[out_idx++] = (uint16_t)val;
}
if (out_idx > 0) {
httpd_ws_frame_t ws_frame = {
.final = true,
.fragmented = false,
.type = HTTPD_WS_TYPE_BINARY,
.payload = (uint8_t *)out_buf,
.len = out_idx * sizeof(uint16_t)
};
// Non-blocking send (best effort)
esp_err_t ret_ws = httpd_ws_send_frame_async(s_server, s_ws_client_fd, &ws_frame);
if (ret_ws != ESP_OK) {
ESP_LOGW(TAG, "dropped: %s", esp_err_to_name(ret_ws));
// Invalidate FD if it's no longer valid (client disconnected)
if (ret_ws == ESP_ERR_INVALID_ARG || ret_ws == ESP_FAIL) {
s_ws_client_fd = -1;
}
}
if (out_idx > 0) {
httpd_ws_frame_t ws_frame = {
.final = true,
.fragmented = false,
.type = HTTPD_WS_TYPE_BINARY,
.payload = (uint8_t*)out_buf,
.len = out_idx * sizeof(uint16_t)};
// Non-blocking send (best effort)
esp_err_t ret_ws = httpd_ws_send_frame_async(s_server, s_ws_client_fd, &ws_frame);
if (ret_ws != ESP_OK) {
ESP_LOGW(TAG, "dropped: %s", esp_err_to_name(ret_ws));
// Invalidate FD if it's no longer valid (client disconnected)
if (ret_ws == ESP_ERR_INVALID_ARG || ret_ws == ESP_FAIL) {
s_ws_client_fd = -1;
}
}
}
}
/**
@@ -213,11 +209,8 @@ static void adc_read_task(void *arg) {
}
}
static void continuous_adc_init(adc_channel_t *channel, uint8_t channel_num,
adc_continuous_handle_t *out_handle) {
static void continuous_adc_init(adc_channel_t* channel, uint8_t channel_num,
adc_continuous_handle_t* out_handle) {
uint32_t frame_size = get_optimal_buffer_size(s_sample_rate);
ESP_LOGI(TAG, "Dynamic Buffer Size: %lu bytes", frame_size);
@@ -271,30 +264,39 @@ static void start_test_signal(uint32_t hz) {
}
ESP_LOGI(TAG, "Starting test signal at %u Hz", hz);
ledc_timer_config_t ledc_timer = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_14_BIT,
.timer_num = LEDC_TIMER_0,
.freq_hz = hz,
.clk_cfg = LEDC_AUTO_CLK
};
.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_14_BIT,
.timer_num = LEDC_TIMER_0,
.freq_hz = hz,
.clk_cfg = LEDC_AUTO_CLK};
ledc_channel_config_t ledc_channel = {
.gpio_num = 1, // GPIO data pin 1
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_0,
.timer_sel = LEDC_TIMER_0,
.duty = 1 << (ledc_timer.duty_resolution - 1), // 512, // 50% duty cycle (1024 / 2 for 10-bit resolution)
.hpoint = 0
};
.gpio_num = 1, // GPIO data pin 1
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_0,
.timer_sel = LEDC_TIMER_0,
.duty = 1 << (ledc_timer.duty_resolution - 1), // 512, // 50% duty cycle (1024 / 2 for 10-bit resolution)
.hpoint = 0};
// Initialize the PWM
ledc_timer_config(&ledc_timer);
ledc_channel_config(&ledc_channel);
// Start the PWM signal
ledc_set_duty(ledc_channel.speed_mode, ledc_channel.channel, ledc_channel.duty); // 50% duty cycle
ledc_set_duty(ledc_channel.speed_mode, ledc_channel.channel, ledc_channel.duty); // 50% duty cycle
ledc_update_duty(ledc_channel.speed_mode, ledc_channel.channel);
ledc_inited = true;
}
static void show_status_led() {
#ifdef CONFIG_LED_BUILTIN
while (true) {
vTaskDelay(pdMS_TO_TICKS(100));
gpio_set_level(CONFIG_LED_BUILTIN, 1);
vTaskDelay(pdMS_TO_TICKS(s_ws_client_fd == -1 ? 900 : 200));
gpio_set_level(CONFIG_LED_BUILTIN, 0);
}
#endif
}
void app_main(void) {
// Initialize NVS
esp_err_t ret = nvs_flash_init();
@@ -305,28 +307,35 @@ void app_main(void) {
}
ESP_ERROR_CHECK(ret);
#ifdef CONFIG_LED_BUILTIN
gpio_config_t led_io_conf = {
.pin_bit_mask = (1ULL << CONFIG_LED_BUILTIN),
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE};
gpio_config(&led_io_conf);
gpio_set_level(CONFIG_LED_BUILTIN, 0);
#endif
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
/* Board-specific WiFi init (if any) */
// Seeed XIAO ESP32C6: Configure GPIO 3 and GPIO 14 as outputs
gpio_config_t io_conf = {
.pin_bit_mask = (1ULL << 3) | (1ULL << 14),
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE
};
gpio_config(&io_conf);
// Seeed XIAO ESP32C6: Configure GPIO 3 and GPIO 14 as outputs
gpio_config_t board_io_conf = {
.pin_bit_mask = (1ULL << 3) | (1ULL << 14),
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE};
gpio_config(&board_io_conf);
// Set GPIO 3 and GPIO 14 to low
gpio_set_level(3, 0);
gpio_set_level(14, 0);
// Set GPIO 3 and GPIO 14 to low
gpio_set_level(3, 0);
gpio_set_level(14, 0);
/* end board-specific WiFi init (if any) */
wifi_init_sta();
start_test_signal(100);
xTaskCreate(adc_read_task, "adc_read_task", 8192 + ADC_READ_LEN, NULL, 5, NULL);
// Wait for WiFi connection
@@ -337,6 +346,7 @@ void app_main(void) {
if (bits & WIFI_CONNECTED_BIT) {
ESP_LOGI(TAG, "connected to ap SSID:%s", ESP_WIFI_SSID);
start_webserver();
show_status_led();
} else if (bits & WIFI_FAIL_BIT) {
ESP_LOGI(TAG, "Failed to connect to SSID:%s", ESP_WIFI_SSID);
} else {
@@ -344,8 +354,8 @@ void app_main(void) {
}
}
static void event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data) {
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data) {
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT &&
@@ -359,7 +369,7 @@ static void event_handler(void *arg, esp_event_base_t event_base,
}
ESP_LOGI(TAG, "connect to the AP fail");
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
ip_event_got_ip_t* event = (ip_event_got_ip_t*)event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
@@ -401,19 +411,17 @@ static void wifi_init_sta(void) {
ESP_LOGI(TAG, "wifi_init_sta finished.");
}
/*
* WebSocket Handler
*/
static esp_err_t ws_handler(httpd_req_t *req) {
static esp_err_t ws_handler(httpd_req_t* req) {
if (req->method == HTTP_GET) {
// Handshake
return ESP_OK;
}
httpd_ws_frame_t ws_pkt;
uint8_t *buf = NULL;
uint8_t* buf = NULL;
memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t));
ws_pkt.type = HTTPD_WS_TYPE_TEXT;
@@ -435,7 +443,7 @@ static esp_err_t ws_handler(httpd_req_t *req) {
// Check for "hello"
if (ws_pkt.type == HTTPD_WS_TYPE_TEXT &&
strcmp((char *)ws_pkt.payload, "hello") == 0) {
strcmp((char*)ws_pkt.payload, "hello") == 0) {
ESP_LOGI(TAG, "New WS client connected, fd=%d", httpd_req_to_sockfd(req));
s_ws_client_fd = httpd_req_to_sockfd(req);
}
@@ -447,7 +455,7 @@ static esp_err_t ws_handler(httpd_req_t *req) {
/*
* Control Params Handler (POST /params)
*/
static esp_err_t params_handler(httpd_req_t *req) {
static esp_err_t params_handler(httpd_req_t* req) {
char buf[256];
int ret, remaining = req->content_len;
if (remaining >= sizeof(buf)) {
@@ -460,24 +468,24 @@ static esp_err_t params_handler(httpd_req_t *req) {
return ESP_FAIL;
buf[ret] = '\0';
cJSON *root = cJSON_Parse(buf);
cJSON* root = cJSON_Parse(buf);
if (root) {
cJSON *sample_rate = cJSON_GetObjectItem(root, "sample_rate");
cJSON* sample_rate = cJSON_GetObjectItem(root, "sample_rate");
if (sample_rate && s_sample_rate != sample_rate->valueint) {
s_reconfig_needed = true;
s_sample_rate = sample_rate->valueint;
}
cJSON *atten = cJSON_GetObjectItem(root, "atten");
cJSON* atten = cJSON_GetObjectItem(root, "atten");
if (atten && s_atten != (adc_atten_t)atten->valueint) {
s_reconfig_needed = true;
s_atten = (adc_atten_t)atten->valueint;
}
cJSON *bit_width = cJSON_GetObjectItem(root, "bit_width");
cJSON* bit_width = cJSON_GetObjectItem(root, "bit_width");
if (bit_width && s_bit_width != (adc_bitwidth_t)bit_width->valueint) {
s_reconfig_needed = true;
s_bit_width = (adc_bitwidth_t)bit_width->valueint;
}
cJSON *test_hz = cJSON_GetObjectItem(root, "test_hz");
cJSON* test_hz = cJSON_GetObjectItem(root, "test_hz");
if (test_hz) {
if (s_test_hz != (adc_bitwidth_t)test_hz->valueint) {
s_test_hz = (adc_bitwidth_t)test_hz->valueint;
@@ -487,7 +495,7 @@ static esp_err_t params_handler(httpd_req_t *req) {
ESP_LOGI(TAG, "Config Request: Rate=%lu, Atten=%d, Width=%d, TestHz=%u, s_reconfig_needed=%d", s_sample_rate,
s_atten, s_bit_width, s_test_hz,
s_reconfig_needed);
s_reconfig_needed);
cJSON_Delete(root);
}
@@ -507,16 +515,14 @@ static const httpd_uri_t uri_params = {.uri = "/params",
.handler = params_handler,
.user_ctx = NULL};
/* Handler for serving index.html */
static esp_err_t index_handler(httpd_req_t *req) {
static esp_err_t index_handler(httpd_req_t* req) {
httpd_resp_set_type(req, "text/html");
httpd_resp_set_hdr(req, "Content-Type", "text/html; charset=utf-8");
uint32_t len = index_html_end - index_html_start;
// Workaround for some build systems adding null byte
while (len && index_js_start[len-1] == 0) len--;
httpd_resp_send(req, (const char *)index_html_start, len);
while (len && index_js_start[len - 1] == 0) len--;
httpd_resp_send(req, (const char*)index_html_start, len);
return ESP_OK;
}
@@ -524,19 +530,32 @@ static const httpd_uri_t uri_index = {
.uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL};
/* Handler for serving index.js */
static esp_err_t index_js_handler(httpd_req_t *req) {
static esp_err_t index_js_handler(httpd_req_t* req) {
httpd_resp_set_type(req, "text/javascript");
httpd_resp_set_hdr(req, "Content-Type", "text/javascript; charset=utf-8");
uint32_t len = index_js_end - index_js_start;
// Workaround for some build systems adding null byte
while (len && index_js_start[len-1] == 0) len--;
httpd_resp_send(req, (const char *)index_js_start, len);
while (len && index_js_start[len - 1] == 0) len--;
httpd_resp_send(req, (const char*)index_js_start, len);
return ESP_OK;
}
static const httpd_uri_t uri_index_js = {
.uri = "/index.js", .method = HTTP_GET, .handler = index_js_handler, .user_ctx = NULL};
static esp_err_t power_handler(httpd_req_t* req) {
#ifdef CONFIG_LED_BUILTIN
gpio_set_level(CONFIG_LED_BUILTIN, 0);
#endif
esp_sleep_enable_timer_wakeup(30L * 24L * 60L * 60L * 1000000ULL); // One month
esp_deep_sleep_start();
return ESP_OK;
}
static const httpd_uri_t uri_power = {
.uri = "/poweroff", .method = HTTP_POST, .handler = power_handler, .user_ctx = NULL};
static void start_webserver(void) {
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.lru_purge_enable = true;
@@ -548,9 +567,7 @@ static void start_webserver(void) {
httpd_register_uri_handler(s_server, &uri_index_js);
httpd_register_uri_handler(s_server, &uri_ws);
httpd_register_uri_handler(s_server, &uri_params);
httpd_register_uri_handler(s_server, &uri_power);
} else {
ESP_LOGI(TAG, "Error starting server!");
}