/* * USB ESP-NOW bridge. A computer talks to it over the USB-Serial-JTAG port in SLIP frames * (bridge_proto.h); it sends each PKT's dst_mac + packet on ESP-NOW and returns every received frame * as src_mac + packet. ESP-NOW runs on one Wi-Fi channel with no access point and no router. */ #include #include #include #include "driver/gpio.h" #include "driver/i2s_std.h" #include "driver/usb_serial_jtag.h" #include "esp_log.h" #include "esp_mac.h" #include "esp_netif.h" #include "esp_event.h" #include "esp_now.h" #include "esp_wifi.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/semphr.h" #include "esp_timer.h" #include "freertos/task.h" #include "lwip/sockets.h" #include "nvs.h" #include "nvs_flash.h" #include "bridge_proto.h" #include "sdkconfig.h" #if CONFIG_BRIDGE_ETH #include "bridge_eth.h" #endif static const char *TAG = "bridge"; #define DEFAULT_CHANNEL 6 // the controller's CONFIG_ESPNOW_CHANNEL #define PEERS_MAX 19 // ESP-NOW allows 20 peers: 19 unicast and the broadcast one #define TX_QUEUE_LEN 32 #define RX_QUEUE_LEN 32 #define SEND_WAIT_MS 100 typedef struct { uint8_t mac[6]; uint8_t len; uint8_t data[BRIDGE_PKT_MAX]; } pkt_t; static const uint8_t BROADCAST[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; static QueueHandle_t s_txq; static QueueHandle_t s_rxq; static SemaphoreHandle_t s_sent; // given by the ESP-NOW send callback static SemaphoreHandle_t s_usb_lock; static volatile esp_now_send_status_t s_last_status; static volatile bool s_usb_ready; static uint8_t s_mac[6]; static uint8_t s_channel = DEFAULT_CHANNEL; static uint8_t s_peers[PEERS_MAX][6]; // most recently used first static int s_npeers; static uint32_t s_tx, s_tx_fail, s_rx, s_drop; static volatile bool s_mic_on; // the host asked for microphone audio (SET_MIC) #if CONFIG_BRIDGE_ETH // The UDP bridge: the host that sent the last datagram gets every frame the radio hears static int s_udp = -1; static SemaphoreHandle_t s_udp_lock; static struct sockaddr_in s_udp_peer; static bool s_udp_have_peer; // The control port (BRIDGE_ETH_AUDIO_PORT): HELLO gets INFO back; SET_MIC 1 from a host makes this board send it // microphone audio (AUDIO datagrams) until SET_MIC 1 stops arriving for MIC_UDP_TIMEOUT_MS #define MIC_UDP_TIMEOUT_MS 2000 static int s_ctl = -1; static struct sockaddr_in s_ctl_peer; static bool s_ctl_mic; static int64_t s_ctl_mic_ms; #endif /* ---- USB link ---------------------------------------------------------------------------------- */ // One whole frame per call, under the lock so frames from different tasks never interleave #define USB_WRITE_PIECE 64 static void usb_send_frame(uint8_t type, const uint8_t *body, size_t n) { static uint8_t out[BRIDGE_ENC_MAX]; if (!s_usb_ready) { return; } size_t len = bridge_encode(out, sizeof(out), type, body, n); if (!len) { return; } xSemaphoreTake(s_usb_lock, portMAX_DELAY); size_t off = 0; while (off < len) { // The driver's TX ring takes a write only as a whole, so a frame longer than its ring is written in pieces size_t piece = len - off < USB_WRITE_PIECE ? len - off : USB_WRITE_PIECE; int w = usb_serial_jtag_write_bytes(out + off, piece, pdMS_TO_TICKS(200)); if (w <= 0) { break; // host not reading: drop the rest rather than stall the radio } off += (size_t)w; } xSemaphoreGive(s_usb_lock); } // Log lines travel as LOG frames, so nothing but frames ever reaches the USB port static int log_hook(const char *fmt, va_list args) { char line[200]; int n = vsnprintf(line, sizeof(line), fmt, args); if (n > 0) { size_t len = (size_t)n < sizeof(line) ? (size_t)n : sizeof(line) - 1; usb_send_frame(BRIDGE_MSG_LOG, (const uint8_t *)line, len); } return n; } #if CONFIG_BRIDGE_MIC #define BRIDGE_CAP_MIC_BOARD BRIDGE_CAP_MIC #else #define BRIDGE_CAP_MIC_BOARD 0 #endif static void put_u32(uint8_t *p, uint32_t v) { p[0] = v & 0xFF; p[1] = (v >> 8) & 0xFF; p[2] = (v >> 16) & 0xFF; p[3] = (v >> 24) & 0xFF; } // The INFO body (see bridge_proto.h), the same over USB and over the UDP control port static void build_info(uint8_t *b) { b[0] = BRIDGE_PROTO_VERSION; memcpy(b + 1, s_mac, 6); b[7] = s_channel; put_u32(b + 8, s_tx); put_u32(b + 12, s_tx_fail); put_u32(b + 16, s_rx); put_u32(b + 20, s_drop); uint8_t ip[4] = { 0, 0, 0, 0 }; uint8_t eth_cap = 0; #if CONFIG_BRIDGE_ETH if (bridge_eth_ip(ip)) { eth_cap = BRIDGE_CAP_ETH; } #endif b[24] = BRIDGE_CAP_MIC_BOARD | eth_cap; memcpy(b + 25, ip, 4); } static void send_info(void) { uint8_t b[BRIDGE_INFO_LEN]; build_info(b); usb_send_frame(BRIDGE_MSG_INFO, b, sizeof(b)); } /* ---- ESP-NOW ----------------------------------------------------------------------------------- */ static void on_sent(const esp_now_send_info_t *info, esp_now_send_status_t status) { (void)info; s_last_status = status; xSemaphoreGive(s_sent); } static void on_recv(const esp_now_recv_info_t *info, const uint8_t *data, int len) { if (len <= 0 || len > BRIDGE_PKT_MAX) { return; } pkt_t p; memcpy(p.mac, info->src_addr, 6); p.len = (uint8_t)len; memcpy(p.data, data, len); if (xQueueSend(s_rxq, &p, 0) == pdTRUE) { s_rx++; } else { s_drop++; } } // Keep the peer table within the ESP-NOW limit, least recently used dropped first static void ensure_peer(const uint8_t *mac) { if (memcmp(mac, BROADCAST, 6) == 0) { if (!esp_now_is_peer_exist(BROADCAST)) { esp_now_peer_info_t p = { .channel = s_channel, .ifidx = WIFI_IF_STA, .encrypt = false }; memcpy(p.peer_addr, BROADCAST, 6); esp_now_add_peer(&p); } return; } for (int i = 0; i < s_npeers; i++) { if (memcmp(s_peers[i], mac, 6) == 0) { uint8_t hit[6]; memcpy(hit, mac, 6); memmove(s_peers[1], s_peers[0], i * 6); memcpy(s_peers[0], hit, 6); return; } } if (s_npeers == PEERS_MAX) { esp_now_del_peer(s_peers[PEERS_MAX - 1]); s_npeers--; } esp_now_peer_info_t p = { .channel = s_channel, .ifidx = WIFI_IF_STA, .encrypt = false }; memcpy(p.peer_addr, mac, 6); if (esp_now_add_peer(&p) != ESP_OK) { return; } memmove(s_peers[1], s_peers[0], s_npeers * 6); memcpy(s_peers[0], mac, 6); s_npeers++; } static void drop_unicast_peers(void) { for (int i = 0; i < s_npeers; i++) { esp_now_del_peer(s_peers[i]); } s_npeers = 0; } static void set_channel(uint8_t ch) { drop_unicast_peers(); // peers were added on the old channel s_channel = ch; esp_wifi_set_channel(ch, WIFI_SECOND_CHAN_NONE); nvs_handle_t h; if (nvs_open("bridge", NVS_READWRITE, &h) == ESP_OK) { nvs_set_u8(h, "channel", ch); nvs_commit(h); nvs_close(h); } ESP_LOGI(TAG, "ESP-NOW channel %u", ch); } // One frame at a time, waiting for each send callback, so the radio is never overrun static void tx_task(void *arg) { (void)arg; pkt_t p; for (;;) { if (xQueueReceive(s_txq, &p, portMAX_DELAY) != pdTRUE) { continue; } ensure_peer(p.mac); if (esp_now_send(p.mac, p.data, p.len) != ESP_OK) { s_tx_fail++; continue; } if (xSemaphoreTake(s_sent, pdMS_TO_TICKS(SEND_WAIT_MS)) == pdTRUE && s_last_status == ESP_NOW_SEND_SUCCESS) { s_tx++; } else { s_tx_fail++; } } } #if CONFIG_BRIDGE_ETH static void udp_send_up(const uint8_t *body, size_t n); #endif // Received frames go to the host as src_mac + packet static void rx_task(void *arg) { (void)arg; pkt_t p; uint8_t body[6 + BRIDGE_PKT_MAX]; for (;;) { if (xQueueReceive(s_rxq, &p, portMAX_DELAY) != pdTRUE) { continue; } memcpy(body, p.mac, 6); memcpy(body + 6, p.data, p.len); usb_send_frame(BRIDGE_MSG_PKT, body, 6 + p.len); #if CONFIG_BRIDGE_ETH udp_send_up(body, 6 + p.len); #endif } } #if CONFIG_BRIDGE_ETH // Frames heard on ESP-NOW go to the last UDP sender as src_mac + packet static void udp_send_up(const uint8_t *body, size_t n) { xSemaphoreTake(s_udp_lock, portMAX_DELAY); if (s_udp_have_peer && s_udp >= 0) { sendto(s_udp, body, n, 0, (const struct sockaddr *)&s_udp_peer, sizeof(s_udp_peer)); } xSemaphoreGive(s_udp_lock); } // Datagrams from a host are dst_mac + packet, queued like a USB PKT frame. The sender becomes the peer. static void udp_task(void *arg) { (void)arg; uint8_t buf[6 + BRIDGE_PKT_MAX]; for (;;) { struct sockaddr_in from; socklen_t fl = sizeof(from); int n = recvfrom(s_udp, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fl); if (n <= 6) { continue; } xSemaphoreTake(s_udp_lock, portMAX_DELAY); s_udp_peer = from; s_udp_have_peer = true; xSemaphoreGive(s_udp_lock); pkt_t p; memcpy(p.mac, buf, 6); p.len = (uint8_t)(n - 6); memcpy(p.data, buf + 6, p.len); if (xQueueSend(s_txq, &p, 0) != pdTRUE) { s_drop++; } } } #if CONFIG_BRIDGE_ETH static void ctl_task(void *arg) { (void)arg; uint8_t buf[32]; for (;;) { struct sockaddr_in from; socklen_t fl = sizeof(from); int n = recvfrom(s_ctl, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fl); if (n < 1) { vTaskDelay(pdMS_TO_TICKS(10)); continue; } if (buf[0] == BRIDGE_MSG_HELLO) { uint8_t out[1 + BRIDGE_INFO_LEN]; out[0] = BRIDGE_MSG_INFO; build_info(out + 1); sendto(s_ctl, out, sizeof(out), 0, (struct sockaddr *)&from, fl); } else if (buf[0] == BRIDGE_MSG_SET_MIC && n >= 2) { xSemaphoreTake(s_udp_lock, portMAX_DELAY); s_ctl_peer = from; s_ctl_mic = buf[1] != 0; s_ctl_mic_ms = esp_timer_get_time() / 1000; xSemaphoreGive(s_udp_lock); } } } static void ctl_open(void) { s_ctl = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(CONFIG_BRIDGE_ETH_AUDIO_PORT), .sin_addr.s_addr = htonl(INADDR_ANY) }; if (s_ctl < 0 || bind(s_ctl, (struct sockaddr *)&a, sizeof(a)) != 0) { ESP_LOGE(TAG, "UDP control port %d not open", CONFIG_BRIDGE_ETH_AUDIO_PORT); return; } xTaskCreate(ctl_task, "udp_ctl", 4096, NULL, 5, NULL); ESP_LOGI(TAG, "UDP control on port %d", CONFIG_BRIDGE_ETH_AUDIO_PORT); } #endif static void udp_open(void) { ESP_LOGI(TAG, "udp: opening"); s_udp = socket(AF_INET, SOCK_DGRAM, 0); ESP_LOGI(TAG, "udp: socket %d", s_udp); struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(CONFIG_BRIDGE_ETH_PORT), .sin_addr.s_addr = htonl(INADDR_ANY) }; if (s_udp < 0 || bind(s_udp, (struct sockaddr *)&a, sizeof(a)) != 0) { ESP_LOGE(TAG, "UDP port %d not open", CONFIG_BRIDGE_ETH_PORT); return; } xTaskCreate(udp_task, "udp_rx", 4096, NULL, 5, NULL); ESP_LOGI(TAG, "UDP bridge on port %d", CONFIG_BRIDGE_ETH_PORT); ctl_open(); } #endif /* ---- host commands ----------------------------------------------------------------------------- */ static void handle_frame(const uint8_t *msg, size_t len) { if (len < 1) { return; } const uint8_t *body = msg + 1; size_t n = len - 1; switch (msg[0]) { case BRIDGE_MSG_PKT: { if (n < 7 || n > 6 + BRIDGE_PKT_MAX) { return; } pkt_t p; memcpy(p.mac, body, 6); p.len = (uint8_t)(n - 6); memcpy(p.data, body + 6, p.len); if (xQueueSend(s_txq, &p, 0) != pdTRUE) { s_drop++; } break; } case BRIDGE_MSG_HELLO: send_info(); break; case BRIDGE_MSG_SET_CHANNEL: if (n >= 1 && body[0] >= 1 && body[0] <= 13) { set_channel(body[0]); } send_info(); break; case BRIDGE_MSG_SET_MIC: if (n >= 1) { s_mic_on = body[0] != 0; ESP_LOGI(TAG, "microphone %s", s_mic_on ? "on" : "off"); } break; default: break; } } static void host_rx_task(void *arg) { (void)arg; uint8_t buf[64]; bridge_decoder_t dec = { 0 }; for (;;) { int n = usb_serial_jtag_read_bytes(buf, sizeof(buf), pdMS_TO_TICKS(50)); for (int i = 0; i < n; i++) { if (bridge_decode_feed(&dec, buf[i])) { handle_frame(dec.buf, dec.frame_len); } } } } /* ---- microphone (boards with BRIDGE_MIC) ------------------------------------------------------- */ #if CONFIG_BRIDGE_MIC #define MIC_RATE 16000 static i2s_chan_handle_t s_mic_chan; // Reads the I2S mic all the time (so the bus never stalls) and sends 10 ms of 16-bit mono while the host wants it. // The mic drives one of the two slots and the other reads 0: the busier slot is the one kept. static void mic_task(void *arg) { (void)arg; static int32_t raw[BRIDGE_AUDIO_SAMPLES * 2]; uint8_t out[BRIDGE_AUDIO_BYTES]; uint8_t dg[1 + BRIDGE_AUDIO_BYTES]; // a UDP audio datagram: AUDIO, then the samples for (;;) { size_t got = 0; esp_err_t err = i2s_channel_read(s_mic_chan, raw, sizeof(raw), &got, portMAX_DELAY); if (err != ESP_OK || got == 0) { continue; } size_t frames = got / (2 * sizeof(int32_t)); size_t nonzero[2] = { 0, 0 }; for (size_t i = 0; i < frames; i++) { nonzero[0] += raw[2 * i] != 0; nonzero[1] += raw[2 * i + 1] != 0; } int ch = nonzero[1] > nonzero[0] ? 1 : 0; bool want_usb = s_mic_on; bool want_udp = false; struct sockaddr_in peer; #if CONFIG_BRIDGE_ETH xSemaphoreTake(s_udp_lock, portMAX_DELAY); want_udp = s_ctl_mic && esp_timer_get_time() / 1000 - s_ctl_mic_ms < MIC_UDP_TIMEOUT_MS; peer = s_ctl_peer; xSemaphoreGive(s_udp_lock); #endif if (!want_usb && !want_udp) { continue; } for (size_t i = 0; i < frames; i++) { int16_t s = (int16_t)(raw[2 * i + ch] >> 16); // 24-bit sample in the top of the 32-bit slot out[2 * i] = (uint8_t)(s & 0xFF); out[2 * i + 1] = (uint8_t)((uint16_t)s >> 8); } if (want_usb) { usb_send_frame(BRIDGE_MSG_AUDIO, out, 2 * frames); } #if CONFIG_BRIDGE_ETH if (want_udp) { dg[0] = BRIDGE_MSG_AUDIO; memcpy(dg + 1, out, 2 * frames); sendto(s_ctl, dg, 1 + 2 * frames, 0, (struct sockaddr *)&peer, sizeof(peer)); } #endif } } static void mic_start(void) { i2s_chan_config_t chan = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); if (i2s_new_channel(&chan, NULL, &s_mic_chan) != ESP_OK) { ESP_LOGE(TAG, "I2S channel create failed: no microphone"); return; } i2s_std_config_t std = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(MIC_RATE), .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = CONFIG_BRIDGE_MIC_SCK_GPIO, .ws = CONFIG_BRIDGE_MIC_WS_GPIO, .dout = I2S_GPIO_UNUSED, .din = CONFIG_BRIDGE_MIC_SD_GPIO, }, }; if (i2s_channel_init_std_mode(s_mic_chan, &std) != ESP_OK || i2s_channel_enable(s_mic_chan) != ESP_OK) { ESP_LOGE(TAG, "I2S mic init failed: no microphone"); return; } gpio_pulldown_en(CONFIG_BRIDGE_MIC_SD_GPIO); // SD tri-states outside the mic's slot xTaskCreate(mic_task, "mic", 4096, NULL, 5, NULL); ESP_LOGI(TAG, "I2S mic on SCK %d WS %d SD %d at %d Hz", CONFIG_BRIDGE_MIC_SCK_GPIO, CONFIG_BRIDGE_MIC_WS_GPIO, CONFIG_BRIDGE_MIC_SD_GPIO, MIC_RATE); } #else static void mic_start(void) { } #endif /* ---- start-up ---------------------------------------------------------------------------------- */ static void load_channel(void) { nvs_handle_t h; if (nvs_open("bridge", NVS_READONLY, &h) == ESP_OK) { uint8_t ch = 0; if (nvs_get_u8(h, "channel", &ch) == ESP_OK && ch >= 1 && ch <= 13) { s_channel = ch; } nvs_close(h); } } void app_main(void) { esp_err_t err = nvs_flash_init(); if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { nvs_flash_erase(); err = nvs_flash_init(); } ESP_ERROR_CHECK(err); load_channel(); s_txq = xQueueCreate(TX_QUEUE_LEN, sizeof(pkt_t)); s_rxq = xQueueCreate(RX_QUEUE_LEN, sizeof(pkt_t)); s_sent = xSemaphoreCreateBinary(); s_usb_lock = xSemaphoreCreateMutex(); #if CONFIG_BRIDGE_ETH s_udp_lock = xSemaphoreCreateMutex(); // the microphone task uses it from the start #endif ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); wifi_init_config_t wcfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&wcfg)); ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_start()); ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE)); ESP_ERROR_CHECK(esp_wifi_set_channel(s_channel, WIFI_SECOND_CHAN_NONE)); ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_STA, s_mac)); ESP_ERROR_CHECK(esp_now_init()); ESP_ERROR_CHECK(esp_now_register_send_cb(on_sent)); ESP_ERROR_CHECK(esp_now_register_recv_cb(on_recv)); ensure_peer(BROADCAST); usb_serial_jtag_driver_config_t ucfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT(); ESP_ERROR_CHECK(usb_serial_jtag_driver_install(&ucfg)); s_usb_ready = true; esp_log_set_vprintf(log_hook); xTaskCreate(tx_task, "espnow_tx", 4096, NULL, 6, NULL); xTaskCreate(rx_task, "espnow_rx", 4096, NULL, 6, NULL); xTaskCreate(host_rx_task, "usb_rx", 4096, NULL, 5, NULL); mic_start(); #if CONFIG_BRIDGE_ETH ESP_LOGI(TAG, "eth: starting"); esp_err_t eth_err = bridge_eth_start(); ESP_LOGI(TAG, "eth: %s", esp_err_to_name(eth_err)); if (eth_err == ESP_OK) { udp_open(); } #endif ESP_LOGI(TAG, "bridge %02x:%02x:%02x:%02x:%02x:%02x on ESP-NOW channel %u", s_mac[0], s_mac[1], s_mac[2], s_mac[3], s_mac[4], s_mac[5], s_channel); }