From fee9c23a1599a48797a2934521fa4d517a76aa0b Mon Sep 17 00:00:00 2001 From: nicoboy Date: Sun, 21 Jun 2026 16:18:05 +0200 Subject: [PATCH] =?UTF-8?q?Buffer=20UART=20bytes=20before=20UDP=20send=20?= =?UTF-8?q?=E2=80=94=20fix=20MAVLink=20frame=20fragmentation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/main.cpp | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 961ed3a..dae6a46 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -40,6 +40,13 @@ uint32_t bytesUartToUdp = 0; uint32_t bytesUdpToUart = 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 ───────────────────────────────────── void updateLED() { unsigned long elapsed = millis() - ledStateStart; @@ -135,21 +142,23 @@ void loop() { if (!wifiConnected) return; - // UART → UDP (H743 → Jetson) - if (MavSerial.available()) { - uint8_t buf[512]; - int len = 0; - while (MavSerial.available() && len < (int)sizeof(buf)) { - buf[len++] = MavSerial.read(); - } - if (len > 0) { - udp.beginPacket(TARGET_IP, UDP_PORT); - udp.write(buf, len); - udp.endPacket(); - bytesUartToUdp += len; - setLedState(LED_ACTIVITY); - Serial.printf("[UART->UDP] %d bytes\n", len); - } + // UART → UDP (H743 → Jetson) — accumulation puis flush + while (MavSerial.available() && uartBufLen < UART_BUF_SIZE) { + uartBuf[uartBufLen++] = MavSerial.read(); + uartLastByteTime = millis(); + } + + bool flushNow = uartBufLen > 0 && + (uartBufLen >= UART_BUF_SIZE || millis() - uartLastByteTime >= UART_FLUSH_MS); + + if (flushNow) { + udp.beginPacket(TARGET_IP, UDP_PORT); + udp.write(uartBuf, uartBufLen); + udp.endPacket(); + bytesUartToUdp += uartBufLen; + setLedState(LED_ACTIVITY); + Serial.printf("[UART->UDP] %d bytes\n", uartBufLen); + uartBufLen = 0; } // UDP → UART (Jetson → H743)