#include "espnow_tx.h" #include #include #include "esp_check.h" #include "esp_event.h" #include "esp_log.h" #include "esp_rom_sys.h" #include "esp_random.h" #include "esp_timer.h" #include "bench.h" #include "bridge.h" #if !CONFIG_IDF_TARGET_LINUX #include "esp_netif.h" #include "esp_now.h" #include "esp_wifi.h" #include "esp_mac.h" #include "esp_wifi_ap_get_sta_list.h" #endif #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 bool s_bulk_ok; 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; static espnow_rx_cb_t s_rx_cb; static char s_bridges[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX]; // the bridges to open at init static size_t s_nbridges; void espnow_tx_set_bridges(const char addrs[][BRIDGE_ADDR_MAX], size_t n) { if (n > BRIDGE_MAX_LINKS) { n = BRIDGE_MAX_LINKS; } memcpy(s_bridges, addrs, n * sizeof(s_bridges[0])); s_nbridges = n; } // One frame onto the air, or to the UDP bridge while one is set static esp_err_t radio_send(const uint8_t *dst, const void *data, size_t len) { if (bridge_active()) { return bridge_send(dst, data, len); } #if CONFIG_IDF_TARGET_LINUX return ESP_ERR_NOT_SUPPORTED; #else return esp_now_send(dst, data, len); #endif } 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; } #if !CONFIG_IDF_TARGET_LINUX 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_ok = status == ESP_NOW_SEND_SUCCESS; BaseType_t woken = pdFALSE; xSemaphoreGiveFromISR(s_bulk_done, &woken); portYIELD_FROM_ISR(woken); } } static void recv_cb(const esp_now_recv_info_t *info, const uint8_t *data, int len) { if (s_rx_cb) { s_rx_cb(info->src_addr, data, len); } } #endif static void bridge_rx(const uint8_t *src, const uint8_t *data, int len) { if (s_rx_cb) { s_rx_cb(src, data, len); } } esp_err_t espnow_tx_set_rx_cb(espnow_rx_cb_t cb) { s_rx_cb = cb; return ESP_OK; } // 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 (radio_send(BROADCAST, &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 (bridge_active()) { return ESP_OK; // no peer table behind the bridge } #if CONFIG_IDF_TARGET_LINUX return ESP_ERR_NOT_SUPPORTED; #else 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; #endif } 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 (bridge_active()) { ok = bridge_send(dst, b.data, b.len) == ESP_OK; // no MAC-layer ack: rel.c's acks retry } else if (radio_send(dst, b.data, b.len) == ESP_OK && xSemaphoreTake(s_bulk_done, pdMS_TO_TICKS(30)) == pdTRUE) { ok = s_bulk_ok || 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; } #if !CONFIG_IDF_TARGET_LINUX // A link-local IPv6 address on the AP lets the mDNS responder answer the AAAA half of a browser's // lookup; without it the browser waits about a second for an answer that never comes. static esp_netif_t *s_ap_netif; static void ap_event(void *arg, esp_event_base_t base, int32_t id, void *data) { if (s_ap_netif) { esp_netif_create_ip6_linklocal(s_ap_netif); } } int espnow_tx_ap_clients(char *out, size_t n) { int len = snprintf(out, n, "["); wifi_sta_list_t sl; wifi_sta_mac_ip_list_t ml; if (s_ap_netif && esp_wifi_ap_get_sta_list(&sl) == ESP_OK && esp_wifi_ap_get_sta_list_with_ip(&sl, &ml) == ESP_OK) { for (int i = 0; i < ml.num && len < (int)n - 64; i++) { len += snprintf(out + len, n - len, "%s{\"mac\":\"" MACSTR "\",\"ip\":\"" IPSTR "\"}", i ? "," : "", MAC2STR(ml.sta[i].mac), IP2STR(&ml.sta[i].ip)); } } len += snprintf(out + len, n - len, "]"); return len; } static esp_err_t radio_init(const char *ap_ssid, const char *ap_password) { 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"); if (ap_ssid) { // Not the Ethernet fallback subnet (192.168.4.x) esp_netif_t *ap = esp_netif_create_default_wifi_ap(); ESP_RETURN_ON_FALSE(ap, ESP_FAIL, TAG, "ap netif"); s_ap_netif = ap; ESP_RETURN_ON_ERROR(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_AP_START, ap_event, NULL), TAG, "ap event"); esp_netif_ip_info_t ip = { 0 }; ip.ip.addr = ESP_IP4TOADDR(192, 168, 5, 1); ip.gw.addr = ip.ip.addr; ip.netmask.addr = ESP_IP4TOADDR(255, 255, 255, 0); esp_netif_dhcps_stop(ap); ESP_RETURN_ON_ERROR(esp_netif_set_ip_info(ap, &ip), TAG, "ap ip"); esp_netif_dhcps_start(ap); wifi_config_t ac = { 0 }; strlcpy((char *)ac.ap.ssid, ap_ssid, sizeof(ac.ap.ssid)); ac.ap.ssid_len = strlen((char *)ac.ap.ssid); ac.ap.channel = CONFIG_ESPNOW_CHANNEL; if (ap_password && strlen(ap_password) >= 8) { strlcpy((char *)ac.ap.password, ap_password, sizeof(ac.ap.password)); ac.ap.authmode = WIFI_AUTH_WPA2_PSK; } else { ac.ap.authmode = WIFI_AUTH_OPEN; } ac.ap.max_connection = 4; ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_APSTA), TAG, "mode"); ESP_RETURN_ON_ERROR(esp_wifi_set_config(WIFI_IF_AP, &ac), TAG, "ap config"); } else { 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"); ESP_RETURN_ON_ERROR(esp_now_register_recv_cb(recv_cb), TAG, "recv cb"); ESP_LOGI(TAG, "ESP-NOW up on channel %d, %d beat copies", CONFIG_ESPNOW_CHANNEL, CONFIG_BEAT_TX_COPIES); return ESP_OK; } #endif #if CONFIG_IDF_TARGET_LINUX int espnow_tx_ap_clients(char *out, size_t n) { return snprintf(out, n, "[]"); } #endif esp_err_t espnow_tx_change_bridges(const char addrs[][BRIDGE_ADDR_MAX], size_t n) { espnow_tx_set_bridges(addrs, n); return bridge_set_all(addrs, n, bridge_rx); } esp_err_t espnow_tx_init(const char *ap_ssid, const char *ap_password) { #if CONFIG_IDF_TARGET_LINUX (void)ap_ssid; (void)ap_password; ESP_RETURN_ON_FALSE(s_nbridges, ESP_ERR_INVALID_STATE, TAG, "the host build needs a bridge address"); #else // The radio still comes up behind a bridge: the access point serves the web UI ESP_RETURN_ON_ERROR(radio_init(ap_ssid, ap_password), TAG, "radio"); #endif if (s_nbridges) { ESP_RETURN_ON_ERROR(bridge_set_all(s_bridges, s_nbridges, bridge_rx), TAG, "bridge"); } 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); return ESP_OK; }