// Serial bridge boards: SLIP frames to the ESP-NOW bridge boards (bridge/), see bridge_proto.h. Linux only. // Each open board has its own port, queue, writer and link task. #include "bridge_serial.h" #include #include #include #include #include #include #include #include "esp_log.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "bridge_proto.h" static const char *TAG = "bridge_serial"; // Messages are encoded by the caller and queued; the writer task puts them on the port. A caller (the // engine's send path) never waits for USB: when the queue is full the message is dropped and counted. #define TX_QUEUE_LEN 64 #define MAX_BOARDS BRIDGE_MAX_LINKS typedef struct { uint16_t len; uint8_t data[BRIDGE_ENC_MAX]; } tx_frame_t; struct bridge_serial { char dev[80]; bool used; // a slot holds a board (closed boards keep their slot and tasks) bool active; // the link task keeps the port open while this is set bridge_rx_cb_t cb; SemaphoreHandle_t lock; // guards fd, the flags below and the writes QueueHandle_t txq; int fd; // -1 while the port is closed bool warned; // "waiting for the port" logged once bool have_info; // an INFO frame arrived on this open uint8_t mac[6]; uint8_t channel; uint8_t caps; // BRIDGE_CAP_* from INFO (0 for boards that predate it) uint8_t eth_ip[4]; // the board's Ethernet address from INFO (0.0.0.0 without one) bool mic_wanted; // the host is recording: SET_MIC 1 is re-sent after each reconnect uint32_t sent; // frames this host handed to the board uint32_t tx_queue_drops; uint32_t tx, tx_fail, rx, drop; // the board's counters, from INFO int16_t pcm[BRIDGE_AUDIO_SAMPLES]; }; static bridge_serial_t s_boards[MAX_BOARDS]; static bridge_audio_cb_t s_audio_cb; static uint32_t get_u32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); } static bool open_port(bridge_serial_t *b) { int fd = open(b->dev, O_RDWR | O_NOCTTY); if (fd < 0) { return false; } struct termios t; if (tcgetattr(fd, &t) == 0) { cfmakeraw(&t); cfsetispeed(&t, B921600); // the USB-Serial-JTAG port ignores the rate cfsetospeed(&t, B921600); t.c_cflag |= CLOCAL | CREAD; tcsetattr(fd, TCSANOW, &t); } tcflush(fd, TCIOFLUSH); // Non-blocking: a blocked read would hold the host's FreeRTOS task, and with it the web server fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); b->fd = fd; return true; } // Queue one message for the writer. Never blocks. static esp_err_t send_frame(bridge_serial_t *b, uint8_t type, const uint8_t *body, size_t n) { tx_frame_t f; f.len = (uint16_t)bridge_encode(f.data, sizeof(f.data), type, body, n); if (!f.len) { return ESP_ERR_INVALID_SIZE; } if (xQueueSend(b->txq, &f, 0) != pdTRUE) { b->tx_queue_drops++; return ESP_ERR_NO_MEM; } return ESP_OK; } // The only writer for a board. It waits briefly for the port to take each message, then moves on: a // message that cannot be written is lost, as on the air. static void writer_task(void *arg) { bridge_serial_t *b = arg; tx_frame_t f; for (;;) { if (xQueueReceive(b->txq, &f, pdMS_TO_TICKS(20)) != pdTRUE) { continue; } xSemaphoreTake(b->lock, portMAX_DELAY); if (b->fd >= 0) { size_t off = 0; int stalls = 0; while (off < f.len) { ssize_t w = write(b->fd, f.data + off, f.len - off); if (w > 0) { off += (size_t)w; stalls = 0; continue; } if (w < 0 && (errno == EINTR || errno == EAGAIN) && stalls++ < 200) { vTaskDelay(pdMS_TO_TICKS(1)); // the port is full: give the board a moment continue; } break; } } xSemaphoreGive(b->lock); } } static void handle_frame(bridge_serial_t *b, 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 > 6 && b->cb) { b->cb(body, body + 6, (int)(n - 6)); } break; case BRIDGE_MSG_INFO: // 24 bytes from older boards, 25 with the capabilities byte // 24 bytes from the oldest boards, 25 with capabilities, 29 with the Ethernet address if (n >= 24 && body[0] == BRIDGE_PROTO_VERSION) { memcpy(b->mac, body + 1, 6); b->channel = body[7]; b->tx = get_u32(body + 8); b->tx_fail = get_u32(body + 12); b->rx = get_u32(body + 16); b->drop = get_u32(body + 20); b->caps = n >= 25 ? body[24] : 0; memset(b->eth_ip, 0, sizeof(b->eth_ip)); if (n >= BRIDGE_INFO_LEN) { memcpy(b->eth_ip, body + 25, 4); } b->have_info = true; if (b->mic_wanted && (b->caps & BRIDGE_CAP_MIC)) { uint8_t on = 1; send_frame(b, BRIDGE_MSG_SET_MIC, &on, 1); } } break; case BRIDGE_MSG_AUDIO: if (s_audio_cb && n >= BRIDGE_AUDIO_BYTES) { for (size_t i = 0; i < BRIDGE_AUDIO_SAMPLES; i++) { b->pcm[i] = (int16_t)((uint16_t)body[2 * i] | ((uint16_t)body[2 * i + 1] << 8)); } s_audio_cb(b->pcm, BRIDGE_AUDIO_SAMPLES); } break; case BRIDGE_MSG_LOG: ESP_LOGI(TAG, "%s: %.*s", b->dev, (int)n, (const char *)body); break; default: break; } } static void link_task(void *arg) { bridge_serial_t *b = arg; bridge_decoder_t dec; uint8_t buf[256]; int64_t last_hello = 0; // ms, esp_timer clock memset(&dec, 0, sizeof(dec)); for (;;) { if (b->fd < 0) { xSemaphoreTake(b->lock, portMAX_DELAY); bool ok = b->active && open_port(b); if (ok) { b->warned = false; memset(&dec, 0, sizeof(dec)); ESP_LOGI(TAG, "bridge board on %s", b->dev); } else if (b->active && !b->warned) { ESP_LOGW(TAG, "waiting for the bridge board on %s", b->dev); b->warned = true; } xSemaphoreGive(b->lock); if (!ok) { vTaskDelay(pdMS_TO_TICKS(b->active ? 1000 : 200)); continue; } send_frame(b, BRIDGE_MSG_HELLO, NULL, 0); // the board answers with INFO last_hello = esp_timer_get_time() / 1000; } // A board that is still booting after a reset misses the first HELLO: ask again until INFO arrives if (!b->have_info && esp_timer_get_time() / 1000 - last_hello >= 1000) { send_frame(b, BRIDGE_MSG_HELLO, NULL, 0); last_hello = esp_timer_get_time() / 1000; } ssize_t n = read(b->fd, buf, sizeof(buf)); if (n < 0 && (errno == EINTR || errno == EAGAIN)) { vTaskDelay(pdMS_TO_TICKS(5)); // nothing yet: let the other tasks run continue; } if (n <= 0 || !b->active) { xSemaphoreTake(b->lock, portMAX_DELAY); if (b->fd >= 0) { close(b->fd); b->fd = -1; ESP_LOGW(TAG, "bridge board on %s went away", b->dev); } b->have_info = false; xSemaphoreGive(b->lock); vTaskDelay(pdMS_TO_TICKS(b->active ? 1000 : 200)); continue; } for (ssize_t i = 0; i < n; i++) { if (bridge_decode_feed(&dec, buf[i])) { handle_frame(b, dec.buf, dec.frame_len); } } } } bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb) { if (!dev || !dev[0] || strlen(dev) >= sizeof(((bridge_serial_t *)0)->dev)) { return NULL; } bridge_serial_t *b = NULL; for (int i = 0; i < MAX_BOARDS; i++) { if (s_boards[i].used && strcmp(s_boards[i].dev, dev) == 0) { b = &s_boards[i]; break; } } if (!b) { for (int i = 0; i < MAX_BOARDS && !b; i++) { if (!s_boards[i].used) { b = &s_boards[i]; } } if (!b) { return NULL; } memset(b, 0, sizeof(*b)); snprintf(b->dev, sizeof(b->dev), "%s", dev); b->fd = -1; b->lock = xSemaphoreCreateMutex(); b->txq = xQueueCreate(TX_QUEUE_LEN, sizeof(tx_frame_t)); if (!b->lock || !b->txq) { return NULL; } b->used = true; xTaskCreate(writer_task, "bridge_write", 6144, b, 6, NULL); xTaskCreate(link_task, "bridge_serial", 6144, b, 6, NULL); } xSemaphoreTake(b->lock, portMAX_DELAY); b->cb = cb; b->active = true; xSemaphoreGive(b->lock); ESP_LOGW(TAG, "ESP-NOW frames go to the bridge board on %s, not the radio", dev); return b; } void bridge_serial_close(bridge_serial_t *b) { if (!b) { return; } xSemaphoreTake(b->lock, portMAX_DELAY); b->active = false; b->mic_wanted = false; if (b->fd >= 0) { close(b->fd); // the link task sees fd < 0 and idles while the board is closed b->fd = -1; } b->have_info = false; xSemaphoreGive(b->lock); } esp_err_t bridge_serial_send(bridge_serial_t *b, const uint8_t *dst_mac, const void *data, size_t len) { if (!b || !b->active) { return ESP_ERR_INVALID_STATE; } if (len > BRIDGE_PKT_MAX) { return ESP_ERR_INVALID_SIZE; } uint8_t buf[BRIDGE_BODY_MAX]; memcpy(buf, dst_mac, 6); memcpy(buf + 6, data, len); esp_err_t err = send_frame(b, BRIDGE_MSG_PKT, buf, 6 + len); if (err == ESP_OK) { b->sent++; } return err; } esp_err_t bridge_serial_set_channel(bridge_serial_t *b, uint8_t channel) { if (!b) { return ESP_ERR_INVALID_STATE; } if (channel < 1 || channel > 13) { return ESP_ERR_INVALID_ARG; } if (!b->have_info) { return ESP_ERR_INVALID_STATE; // the board has not answered: there is no radio to set } return send_frame(b, BRIDGE_MSG_SET_CHANNEL, &channel, 1); } size_t bridge_serial_status(bridge_serial_t *b, char *out, size_t n) { bool linked = b->have_info; char ip_json[24] = "null"; if (b->have_info && (b->eth_ip[0] || b->eth_ip[1] || b->eth_ip[2] || b->eth_ip[3])) { snprintf(ip_json, sizeof(ip_json), "\"%u.%u.%u.%u\"", b->eth_ip[0], b->eth_ip[1], b->eth_ip[2], b->eth_ip[3]); } return (size_t)snprintf(out, n, "{\"port\":\"%s\",\"linked\":%s,\"mac\":\"%02x:%02x:%02x:%02x:%02x:%02x\",\"channel\":%u," "\"mic\":%s,\"ip\":%s,\"sent\":%lu,\"queue_drops\":%lu,\"tx\":%lu,\"tx_fail\":%lu,\"rx\":%lu,\"drop\":%lu}", b->dev, linked ? "true" : "false", b->mac[0], b->mac[1], b->mac[2], b->mac[3], b->mac[4], b->mac[5], (unsigned)b->channel, (b->have_info && (b->caps & BRIDGE_CAP_MIC)) ? "true" : "false", ip_json, (unsigned long)b->sent, (unsigned long)b->tx_queue_drops, (unsigned long)b->tx, (unsigned long)b->tx_fail, (unsigned long)b->rx, (unsigned long)b->drop); } void bridge_serial_set_audio_cb(bridge_audio_cb_t cb) { s_audio_cb = cb; } bool bridge_serial_has_mic(void) { for (int i = 0; i < MAX_BOARDS; i++) { bridge_serial_t *b = &s_boards[i]; if (b->used && b->active && b->have_info && (b->caps & BRIDGE_CAP_MIC)) { return true; } } return false; } // The recording board: the first open one with a mic. Any other board's mic stays off. esp_err_t bridge_serial_mic(bool on) { bridge_serial_t *mic = NULL; for (int i = 0; i < MAX_BOARDS && !mic; i++) { bridge_serial_t *b = &s_boards[i]; if (b->used && b->active && b->have_info && (b->caps & BRIDGE_CAP_MIC)) { mic = b; } } for (int i = 0; i < MAX_BOARDS; i++) { bridge_serial_t *b = &s_boards[i]; if (b->used && b != mic && b->mic_wanted) { b->mic_wanted = false; uint8_t off = 0; send_frame(b, BRIDGE_MSG_SET_MIC, &off, 1); } } if (!on) { if (mic) { mic->mic_wanted = false; uint8_t off = 0; return send_frame(mic, BRIDGE_MSG_SET_MIC, &off, 1); } return ESP_OK; } if (!mic) { return ESP_ERR_NOT_SUPPORTED; } mic->mic_wanted = true; uint8_t onb = 1; return send_frame(mic, BRIDGE_MSG_SET_MIC, &onb, 1); } size_t bridge_serial_ports_json(char *out, size_t n) { static const char *const pats[] = { "/dev/ttyACM*", "/dev/ttyUSB*", "/dev/led-bridge" }; glob_t g; memset(&g, 0, sizeof(g)); for (size_t i = 0; i < sizeof(pats) / sizeof(pats[0]); i++) { glob(pats[i], i ? GLOB_APPEND : 0, NULL, &g); } size_t used = (size_t)snprintf(out, n, "["); bool first = true; for (size_t i = 0; i < g.gl_pathc && used < n; i++) { const char *p = g.gl_pathv[i]; if (strchr(p, '"') || strchr(p, '\\')) { continue; } int w = snprintf(out + used, n - used, "%s\"%s\"", first ? "" : ",", p); if (w < 0 || (size_t)w >= n - used) { break; } used += (size_t)w; first = false; } if (used + 2 <= n) { out[used++] = ']'; out[used] = 0; } globfree(&g); return used; }