Skip to content

Commit 9048f68

Browse files
Improve UDP MAVLink reliability through unicasting (#152)
Unicast MAVLink data rather than always broadcasting; improves packet loss on some setups for unknown reasons.
1 parent 179e8a8 commit 9048f68

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

lib/WIFI/devWIFI.cpp

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ constexpr size_t MAVLINK_BUF_THRESHOLD = MAVLINK_BUF_SIZE / 2;
113113
constexpr size_t MAVLINK_BUF_TIMEOUT = 500;
114114

115115
WiFiUDP mavlinkUDP;
116+
IPAddress gcsIP;
117+
bool gcsIPSet = false;
116118

117119
typedef struct {
118120
uint32_t packets_downlink; // packets from the aircraft
@@ -489,6 +491,12 @@ static void WebMAVLinkHandler(AsyncWebServerRequest *request)
489491
json["counters"]["overflows_down"] = mavlink_stats.overflows_downlink;
490492
json["ports"]["listen"] = MAVLINK_PORT_LISTEN;
491493
json["ports"]["send"] = MAVLINK_PORT_SEND;
494+
if (gcsIPSet) {
495+
json["ip"]["gcs"] = gcsIP.toString();
496+
} else {
497+
json["ip"]["gcs"] = "IP UNSET";
498+
}
499+
json["protocol"] = "UDP";
492500

493501
AsyncResponseStream *response = request->beginResponseStream("application/json");
494502
serializeJson(json, *response);
@@ -810,8 +818,26 @@ static void HandleWebUpdate()
810818
(mavlink_to_gcs_buf_count > 0 && (millis() - last_mavlink_to_gcs_dump) > MAVLINK_BUF_TIMEOUT) // buffer hasn't been flushed in a while
811819
)
812820
{
813-
IPAddress broadcast = WiFi.getMode() == WIFI_STA ? WiFi.broadcastIP() : apBroadcast;
814-
mavlinkUDP.beginPacket(broadcast, MAVLINK_PORT_SEND);
821+
// If we've set the remote IP, use that. Otherwise, we need to broadcast to find our GCS so it can send us heartbeats and we can know its IP
822+
IPAddress remote;
823+
824+
// If we have a GCS IP, use that
825+
if (gcsIPSet)
826+
{
827+
remote = gcsIP;
828+
}
829+
// otherwise if we're in AP mode, broadcast to the AP subnet
830+
else if (WiFi.getMode() == WIFI_AP || WiFi.getMode() == WIFI_AP_STA)
831+
{
832+
remote = apBroadcast;
833+
}
834+
// otherwise broadcast to the station subnet
835+
else
836+
{
837+
remote = WiFi.broadcastIP();
838+
}
839+
mavlinkUDP.beginPacket(remote, MAVLINK_PORT_SEND);
840+
815841
for (uint8_t i = 0; i < mavlink_to_gcs_buf_count; i++)
816842
{
817843
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
@@ -833,6 +859,8 @@ static void HandleWebUpdate()
833859
if (wifiService == WIFI_SERVICE_MAVLINK_TX) {
834860
int packetSize = mavlinkUDP.parsePacket();
835861
if (packetSize) {
862+
gcsIP = mavlinkUDP.remoteIP(); // store the IP of the GCS so we can send to it directly
863+
gcsIPSet = true;
836864
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
837865
mavlinkUDP.read(buf, packetSize);
838866
Serial.write(buf, packetSize);

0 commit comments

Comments
 (0)