Files
led-controller/main/bridge_serial.c
T
jimmyandClaude Haiku 5.5 edf35e9c71 Channel 11 defaults, ESP-NOW driver config and rig/desktop updates
Moves the controller, bridge and led-driver default ESP-NOW channel to 11 and
updates the led-driver and led-tool submodule pointers. Includes the rest of the
working tree: web UI, desktop and sim-controller changes, API and bridge code,
graphify output, and the .gitea and fixture-driver folders.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-21 01:19:02 +13:00

571 lines
19 KiB
C

// 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 <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#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]; // the port; empty while a board known by MAC has not been found yet
bool by_mac; // follow the board by its MAC: when its port goes away, find it on another
uint8_t want_mac[6];
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 | O_CLOEXEC); // processes the controller starts must not keep the board open
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;
}
}
// Is a board on this port in use by a board slot other than skip?
static bool port_taken(const char *path, const bridge_serial_t *skip)
{
for (int i = 0; i < MAX_BOARDS; i++) {
const bridge_serial_t *o = &s_boards[i];
if (o != skip && o->used && o->fd >= 0 && strcmp(o->dev, path) == 0) {
return true;
}
}
return false;
}
// Open path for a moment and ask the board for its INFO. True with its MAC if one answers.
static bool probe_mac(const char *path, uint8_t mac[6])
{
int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
if (fd < 0) {
return false;
}
struct termios t;
if (tcgetattr(fd, &t) == 0) {
cfmakeraw(&t);
cfsetispeed(&t, B921600);
cfsetospeed(&t, B921600);
t.c_cflag |= CLOCAL | CREAD;
tcsetattr(fd, TCSANOW, &t);
}
tcflush(fd, TCIOFLUSH);
uint8_t hello[BRIDGE_ENC_MAX];
size_t hn = bridge_encode(hello, sizeof(hello), BRIDGE_MSG_HELLO, NULL, 0);
bridge_decoder_t dec;
memset(&dec, 0, sizeof(dec));
bool found = false;
for (int tick = 0; tick < 75 && !found; tick++) { // 1.5 s, HELLO every 0.5 s
if (tick % 25 == 0 && hn) {
ssize_t w = write(fd, hello, hn);
(void)w;
}
uint8_t buf[128];
ssize_t n = read(fd, buf, sizeof(buf));
for (ssize_t i = 0; i < n && !found; i++) {
if (bridge_decode_feed(&dec, buf[i]) && dec.frame_len >= 8 && dec.buf[0] == BRIDGE_MSG_INFO &&
dec.buf[1] == BRIDGE_PROTO_VERSION) {
memcpy(mac, dec.buf + 2, 6);
found = true;
}
}
if (!found) {
vTaskDelay(pdMS_TO_TICKS(20));
}
}
close(fd);
return found;
}
// A board followed by MAC lost its port: look for it on the other serial ports. Sets b->dev when found.
static bool find_board(bridge_serial_t *b)
{
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);
}
bool found = false;
for (size_t i = 0; i < g.gl_pathc && !found; i++) {
const char *path = g.gl_pathv[i];
uint8_t mac[6];
if (strlen(path) >= sizeof(b->dev) || port_taken(path, b)) {
continue;
}
if (probe_mac(path, mac) && memcmp(mac, b->want_mac, 6) == 0) {
if (strcmp(b->dev, path) != 0) {
ESP_LOGW(TAG, "bridge board %02x:%02x:%02x:%02x:%02x:%02x is now on %s", mac[0], mac[1], mac[2], mac[3],
mac[4], mac[5], path);
}
xSemaphoreTake(b->lock, portMAX_DELAY);
snprintf(b->dev, sizeof(b->dev), "%s", path);
xSemaphoreGive(b->lock);
found = true;
}
}
globfree(&g);
return found;
}
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) {
if (b->by_mac && b->active && !find_board(b)) {
if (!b->warned) {
ESP_LOGW(TAG, "waiting for the bridge board %02x:%02x:%02x:%02x:%02x:%02x", b->want_mac[0],
b->want_mac[1], b->want_mac[2], b->want_mac[3], b->want_mac[4], b->want_mac[5]);
b->warned = true;
}
vTaskDelay(pdMS_TO_TICKS(2000));
continue;
}
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);
}
}
}
}
// "usb:aabbccddeeff" (colons allowed): a board known by its MAC
static bool parse_usb_mac(const char *s, uint8_t mac[6])
{
if (strncmp(s, "usb:", 4) != 0) {
return false;
}
int n = 0;
for (const char *c = s + 4; *c && n < 12; c++) {
if (*c == ':') {
continue;
}
int v = (*c >= '0' && *c <= '9') ? *c - '0' : (*c >= 'a' && *c <= 'f') ? *c - 'a' + 10
: (*c >= 'A' && *c <= 'F') ? *c - 'A' + 10 : -1;
if (v < 0) {
return false;
}
mac[n / 2] = (uint8_t)((n % 2 ? mac[n / 2] << 4 : 0) | v);
n++;
}
return n == 12;
}
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;
}
uint8_t want[6];
bool by_mac = parse_usb_mac(dev, want);
if (strncmp(dev, "usb:", 4) == 0 && !by_mac) {
return NULL;
}
bridge_serial_t *b = NULL;
for (int i = 0; i < MAX_BOARDS; i++) {
if (!s_boards[i].used) {
continue;
}
if (by_mac ? (s_boards[i].by_mac && memcmp(s_boards[i].want_mac, want, 6) == 0)
: 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));
if (by_mac) {
b->by_mac = true;
memcpy(b->want_mac, want, 6);
} else {
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 %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);
}
bool bridge_serial_mac(bridge_serial_t *b, uint8_t mac[6])
{
if (!b || !b->have_info) {
return false;
}
memcpy(mac, b->mac, 6);
return true;
}
void bridge_serial_follow_mac(bridge_serial_t *b)
{
if (b && b->have_info) {
memcpy(b->want_mac, b->mac, 6);
b->by_mac = true;
}
}
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;
}