Rework sequences (engine, seqplay, envelope, API, web UI), add bridge support, add the host sim-controller and rig simulation tests, and update docs, presets and project tooling config. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
100 lines
2.5 KiB
C
100 lines
2.5 KiB
C
#include "bridge.h"
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include "esp_log.h"
|
|
#include "freertos/FreeRTOS.h"
|
|
#include "freertos/task.h"
|
|
#include "lwip/netdb.h"
|
|
#include "lwip/sockets.h"
|
|
|
|
static const char *TAG = "bridge";
|
|
|
|
static int s_sock = -1;
|
|
static struct sockaddr_in s_peer;
|
|
static bridge_rx_cb_t s_cb;
|
|
static char s_addr[80];
|
|
|
|
static void rx_task(void *arg)
|
|
{
|
|
(void)arg;
|
|
uint8_t buf[6 + 256];
|
|
for (;;) {
|
|
int n = recv(s_sock, buf, sizeof(buf), 0);
|
|
if (n < 0) {
|
|
vTaskDelay(pdMS_TO_TICKS(100));
|
|
continue;
|
|
}
|
|
if (n > 6 && s_cb) {
|
|
s_cb(buf, buf + 6, n - 6);
|
|
}
|
|
}
|
|
}
|
|
|
|
esp_err_t bridge_start(const char *addr, bridge_rx_cb_t cb)
|
|
{
|
|
if (s_sock >= 0 || !addr || !addr[0]) {
|
|
return ESP_ERR_INVALID_STATE;
|
|
}
|
|
char host[64];
|
|
int port = BRIDGE_DEFAULT_PORT;
|
|
snprintf(host, sizeof(host), "%s", addr);
|
|
char *colon = strrchr(host, ':');
|
|
if (colon) {
|
|
*colon = 0;
|
|
port = atoi(colon + 1);
|
|
}
|
|
if (port <= 0 || port > 65535 || !host[0]) {
|
|
ESP_LOGE(TAG, "bad bridge address %s", addr);
|
|
return ESP_ERR_INVALID_ARG;
|
|
}
|
|
struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_DGRAM }, *res = NULL;
|
|
if (getaddrinfo(host, NULL, &hints, &res) != 0 || !res) {
|
|
ESP_LOGE(TAG, "cannot resolve %s", host);
|
|
return ESP_FAIL;
|
|
}
|
|
memcpy(&s_peer, res->ai_addr, sizeof(s_peer));
|
|
freeaddrinfo(res);
|
|
s_peer.sin_port = htons(port);
|
|
|
|
int s = socket(AF_INET, SOCK_DGRAM, 0);
|
|
if (s < 0) {
|
|
return ESP_FAIL;
|
|
}
|
|
// connect() fixes the peer, so only its datagrams are received
|
|
if (connect(s, (struct sockaddr *)&s_peer, sizeof(s_peer)) != 0) {
|
|
close(s);
|
|
return ESP_FAIL;
|
|
}
|
|
s_sock = s;
|
|
s_cb = cb;
|
|
snprintf(s_addr, sizeof(s_addr), "%s:%d", host, port);
|
|
xTaskCreate(rx_task, "bridge_rx", 4096, NULL, 6, NULL);
|
|
ESP_LOGW(TAG, "ESP-NOW frames go to the UDP bridge %s, not the radio", s_addr);
|
|
return ESP_OK;
|
|
}
|
|
|
|
bool bridge_active(void)
|
|
{
|
|
return s_sock >= 0;
|
|
}
|
|
|
|
const char *bridge_addr(void)
|
|
{
|
|
return s_sock >= 0 ? s_addr : NULL;
|
|
}
|
|
|
|
esp_err_t bridge_send(const uint8_t *dst_mac, const void *data, size_t len)
|
|
{
|
|
if (s_sock < 0 || len > 250) {
|
|
return ESP_ERR_INVALID_STATE;
|
|
}
|
|
uint8_t buf[6 + 250];
|
|
memcpy(buf, dst_mac, 6);
|
|
memcpy(buf + 6, data, len);
|
|
// A refused datagram (the simulator is not running yet) is a lost frame, as on air
|
|
send(s_sock, buf, 6 + len, 0);
|
|
return ESP_OK;
|
|
}
|