Files
led-controller/main/espnow_tx.c
T
jimmyandClaude Opus 5.5 bfeeb958df feat: main's import/export, zones, audio API and web UI
Profiles, presets and sequences export and import as main's bundles.
Zones carry group_ids, preset_group_ids, sequence_ids, content_kind and
brightness; profiles seed rainbow as colour_cycle, and deleting a
profile also deletes its sequences. Groups, zones and sequences written
by older versions are migrated at boot.

/api/audio (status, event stream, start/stop, reset, anchor-bar,
devices) maps main's audio detector onto the mic's beat detector. Audio
start/stop picks whether mic beats or the BPM clock time sequences; the
clock's beats also go to the drivers while the mic is off.
/ws now greets from a post-handshake callback (httpd does not call the
handler for the upgrade).

The web UI is main's, plus v2's outputs editor, list search and
hostname/static IP settings; the bridge, Wi-Fi AP and led-tool parts
are gone. API tests follow main's behaviour (119 pass on the board).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:34:22 +13:00

242 lines
7.7 KiB
C

#include "espnow_tx.h"
#include <string.h>
#include "esp_check.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_now.h"
#include "esp_rom_sys.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "bench.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#define BULK_MAX 250
#define BULK_RETRIES 3
#define BULK_QUEUE_LEN 32
static const char *TAG = "espnow_tx";
static const uint8_t BROADCAST[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
typedef struct {
uint8_t mac[6];
bool broadcast;
uint8_t len;
uint8_t data[BULK_MAX];
} bulk_t;
static QueueHandle_t s_bulk_q;
static SemaphoreHandle_t s_bulk_done;
static volatile esp_now_send_status_t s_bulk_status;
static volatile bool s_bulk_inflight;
static volatile int64_t s_last_beat_us;
static esp_timer_handle_t s_copy_timer;
static beat_frame_t s_pending;
static int s_copies_left;
static uint16_t s_beat_idx;
static uint8_t s_cur_peer[6];
static bool s_have_peer;
static espnow_stats_t s_stats;
static volatile int s_loss_pct;
static volatile bool s_loss_beats = true;
bool espnow_tx_drop(void)
{
return s_loss_pct > 0 && (int)(esp_random() % 100) < s_loss_pct;
}
void espnow_tx_set_loss(int percent, bool include_beats)
{
s_loss_pct = percent < 0 ? 0 : (percent > 100 ? 100 : percent);
s_loss_beats = include_beats;
}
int espnow_tx_loss(bool *include_beats)
{
if (include_beats) {
*include_beats = s_loss_beats;
}
return s_loss_pct;
}
static void IRAM_ATTR send_cb(const esp_now_send_info_t *info, esp_now_send_status_t status)
{
(void)info;
if (s_bulk_inflight) {
s_bulk_status = status;
BaseType_t woken = pdFALSE;
xSemaphoreGiveFromISR(s_bulk_done, &woken);
portYIELD_FROM_ISR(woken);
}
}
// Each copy carries a fire_in_ms reduced by the time already spent, so every
// copy points at the same instant.
static void send_beat_copy(void *arg)
{
(void)arg;
int sent = CONFIG_BEAT_TX_COPIES - s_copies_left;
int gap_ms = (sent * CONFIG_BEAT_TX_GAP_US) / 1000;
int fire = CONFIG_BEAT_LEAD_MS - gap_ms;
s_pending.fire_in_ms = fire < 0 ? 0 : (fire > 255 ? 255 : fire);
if (s_loss_beats && espnow_tx_drop()) {
s_stats.sim_dropped++; // lossy-link test: this copy never reaches the radio
} else if (esp_now_send(BROADCAST, (const uint8_t *)&s_pending, sizeof(s_pending)) != ESP_OK) {
s_stats.beat_send_fail++;
}
s_last_beat_us = esp_timer_get_time();
if (--s_copies_left > 0) {
esp_timer_start_once(s_copy_timer, CONFIG_BEAT_TX_GAP_US);
}
}
void espnow_tx_beat(float bpm, bool downbeat, int bar)
{
if (bpm < 30.0f) {
return;
}
esp_timer_stop(s_copy_timer); // a still-pending copy belongs to the previous beat
s_pending.magic = BEAT_FRAME_MAGIC;
s_pending.type = BEAT_FRAME_TYPE;
s_pending.flags = (downbeat ? BEAT_FLAG_DOWNBEAT : 0) | ((bar & 7) << BEAT_FLAG_BAR_SHIFT);
s_pending.beat_idx = ++s_beat_idx;
s_pending.period_ms = (uint16_t)(60000.0f / bpm);
s_copies_left = CONFIG_BEAT_TX_COPIES;
s_stats.beats_sent++;
bench_on_beat_tx(s_pending.beat_idx, esp_timer_get_time(), CONFIG_BEAT_LEAD_MS);
send_beat_copy(NULL);
}
static volatile bool s_mic_beats = true;
void espnow_tx_set_mic_beats(bool on)
{
s_mic_beats = on;
}
// Runs in the audio task straight from the detector: no queue, no allocation.
static void on_beat(const beat_info_t *info, float bpm, bool downbeat)
{
if (!s_mic_beats) {
return;
}
if (bench_running()) {
return; // the bench generator owns the beat stream while it runs
}
espnow_tx_beat(bpm, downbeat, info->bar_sure ? info->bar_beat : 0);
}
static esp_err_t select_peer(const uint8_t *mac)
{
if (s_have_peer && memcmp(s_cur_peer, mac, 6) == 0) {
return ESP_OK;
}
// ESP-NOW holds 20 peers and there can be more drivers, so keep one
// rotating unicast peer plus the broadcast peer.
if (s_have_peer) {
esp_now_del_peer(s_cur_peer);
s_have_peer = false;
}
esp_now_peer_info_t p = { .channel = 0, .ifidx = WIFI_IF_STA, .encrypt = false };
memcpy(p.peer_addr, mac, 6);
ESP_RETURN_ON_ERROR(esp_now_add_peer(&p), TAG, "add peer");
memcpy(s_cur_peer, mac, 6);
s_have_peer = true;
return ESP_OK;
}
static void bulk_task(void *arg)
{
bulk_t b;
for (;;) {
xQueueReceive(s_bulk_q, &b, portMAX_DELAY);
// Keep the channel clear around beats
int64_t wait_us = CONFIG_BULK_HOLDOFF_US - (esp_timer_get_time() - s_last_beat_us);
if (wait_us > 0) {
esp_rom_delay_us(wait_us);
}
const uint8_t *dst = b.broadcast ? BROADCAST : b.mac;
if (!b.broadcast && select_peer(b.mac) != ESP_OK) {
s_stats.bulk_failed++;
continue;
}
int tries = b.broadcast ? 1 : BULK_RETRIES;
bool ok = false;
for (int t = 0; t < tries && !ok; t++) {
if (t) {
s_stats.bulk_retries++;
vTaskDelay(pdMS_TO_TICKS(5 << t));
}
xSemaphoreTake(s_bulk_done, 0);
s_bulk_inflight = true;
if (espnow_tx_drop()) {
s_stats.sim_dropped++; // lossy-link test: pretend the radio sent it
ok = true;
} else if (esp_now_send(dst, b.data, b.len) == ESP_OK &&
xSemaphoreTake(s_bulk_done, pdMS_TO_TICKS(30)) == pdTRUE) {
ok = s_bulk_status == ESP_NOW_SEND_SUCCESS || b.broadcast;
}
s_bulk_inflight = false;
}
s_stats.bulk_sent += ok;
s_stats.bulk_failed += !ok;
vTaskDelay(pdMS_TO_TICKS(3)); // inter-frame gap
}
}
esp_err_t espnow_tx_send(const uint8_t *mac, const void *data, size_t len)
{
if (len == 0 || len > BULK_MAX) {
return ESP_ERR_INVALID_SIZE;
}
bulk_t b = { .broadcast = mac == NULL, .len = len };
if (mac) {
memcpy(b.mac, mac, 6);
}
memcpy(b.data, data, len);
return xQueueSend(s_bulk_q, &b, 0) == pdTRUE ? ESP_OK : ESP_ERR_NO_MEM;
}
void espnow_tx_stats(espnow_stats_t *out)
{
*out = s_stats;
}
esp_err_t espnow_tx_init(void)
{
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_RETURN_ON_ERROR(esp_wifi_init(&cfg), TAG, "wifi init");
ESP_RETURN_ON_ERROR(esp_wifi_set_storage(WIFI_STORAGE_RAM), TAG, "storage");
ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_STA), TAG, "mode");
ESP_RETURN_ON_ERROR(esp_wifi_start(), TAG, "start");
ESP_RETURN_ON_ERROR(esp_wifi_set_ps(WIFI_PS_NONE), TAG, "ps");
ESP_RETURN_ON_ERROR(esp_wifi_set_max_tx_power(80), TAG, "tx power"); // 20 dBm
ESP_RETURN_ON_ERROR(esp_wifi_set_channel(CONFIG_ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE), TAG, "channel");
ESP_RETURN_ON_ERROR(esp_now_init(), TAG, "espnow init");
ESP_RETURN_ON_ERROR(esp_now_register_send_cb(send_cb), TAG, "send cb");
esp_now_peer_info_t bc = { .channel = 0, .ifidx = WIFI_IF_STA, .encrypt = false };
memcpy(bc.peer_addr, BROADCAST, 6);
ESP_RETURN_ON_ERROR(esp_now_add_peer(&bc), TAG, "broadcast peer");
s_bulk_q = xQueueCreate(BULK_QUEUE_LEN, sizeof(bulk_t));
s_bulk_done = xSemaphoreCreateBinary();
ESP_RETURN_ON_FALSE(s_bulk_q && s_bulk_done, ESP_ERR_NO_MEM, TAG, "alloc");
const esp_timer_create_args_t ta = { .callback = send_beat_copy, .name = "beat_copy",
.dispatch_method = ESP_TIMER_TASK };
ESP_RETURN_ON_ERROR(esp_timer_create(&ta, &s_copy_timer), TAG, "timer");
xTaskCreate(bulk_task, "espnow_bulk", 4096, NULL, 5, NULL);
beat_set_callback(on_beat);
ESP_LOGI(TAG, "ESP-NOW up on channel %d, %d beat copies", CONFIG_ESPNOW_CHANNEL, CONFIG_BEAT_TX_COPIES);
return ESP_OK;
}