Buffer UART bytes before UDP send — fix MAVLink frame fragmentation

Accumulate UART bytes and flush to UDP only when buffer is full (512B)
or after 3ms of UART inactivity (end-of-frame gap). Fixes mavp2p
"packet too short" / "invalid magic byte" errors caused by sending
partial MAVLink frames in separate UDP packets.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-21 16:18:05 +02:00
parent e090ef14bc
commit fee9c23a15

View File

@ -40,6 +40,13 @@ uint32_t bytesUartToUdp = 0;
uint32_t bytesUdpToUart = 0; uint32_t bytesUdpToUart = 0;
unsigned long lastStatsTime = 0; unsigned long lastStatsTime = 0;
// ── Buffer UART → UDP ────────────────────────────────────
#define UART_BUF_SIZE 512
#define UART_FLUSH_MS 3
uint8_t uartBuf[UART_BUF_SIZE];
int uartBufLen = 0;
unsigned long uartLastByteTime = 0;
// ── LED non bloquante ───────────────────────────────────── // ── LED non bloquante ─────────────────────────────────────
void updateLED() { void updateLED() {
unsigned long elapsed = millis() - ledStateStart; unsigned long elapsed = millis() - ledStateStart;
@ -135,21 +142,23 @@ void loop() {
if (!wifiConnected) return; if (!wifiConnected) return;
// UART → UDP (H743 → Jetson) // UART → UDP (H743 → Jetson) — accumulation puis flush
if (MavSerial.available()) { while (MavSerial.available() && uartBufLen < UART_BUF_SIZE) {
uint8_t buf[512]; uartBuf[uartBufLen++] = MavSerial.read();
int len = 0; uartLastByteTime = millis();
while (MavSerial.available() && len < (int)sizeof(buf)) { }
buf[len++] = MavSerial.read();
} bool flushNow = uartBufLen > 0 &&
if (len > 0) { (uartBufLen >= UART_BUF_SIZE || millis() - uartLastByteTime >= UART_FLUSH_MS);
udp.beginPacket(TARGET_IP, UDP_PORT);
udp.write(buf, len); if (flushNow) {
udp.endPacket(); udp.beginPacket(TARGET_IP, UDP_PORT);
bytesUartToUdp += len; udp.write(uartBuf, uartBufLen);
setLedState(LED_ACTIVITY); udp.endPacket();
Serial.printf("[UART->UDP] %d bytes\n", len); bytesUartToUdp += uartBufLen;
} setLedState(LED_ACTIVITY);
Serial.printf("[UART->UDP] %d bytes\n", uartBufLen);
uartBufLen = 0;
} }
// UDP → UART (Jetson → H743) // UDP → UART (Jetson → H743)