Module 3/5 · Weeks 7–9 · 27 h

MAVLink and packet analysis

UAT 207 Communication and Data Network Systems

About 100 minDraft, awaiting reviewLast updated 30 September 2026

Lesson

By the end of this module you will be able to

  1. Compute packet loss from MAVLink sequence numbers that wrap after 255
  2. Split MAVLink 2 frames from a byte stream and verify the CRC with CRC_EXTRA
  3. Set up SITL, MAVProxy, a GCS and Wireshark data paths to analyse messages
  4. Distinguish network packet rate from data freshness in the application
  5. Plan IP addresses and subnets for a field station and read a routing table by longest match

Prerequisites: UAT 207 Module 2 · UAT 104 Module 4 (reading telemetry with pymavlink)

Why this matters

When telemetry stutters, the first question is whether packets are really lost or just late, and where along the path. MAVLink puts the data to answer this in every frame: a sequence number and a CRC. This module shows how to use them to analyse a link, following on from reading messages with pymavlink in UAT 104.

Wrapping sequence numbers

The MAVLink guide specifies the sequence number as a uint8 from 0 to 255; the sender increments it for every message, and it is used to detect packet loss. After 255 the next message is 0, so correct counting needs modulo-256 arithmetic. Subtracting directly turns 255 → 0 into a loss of 255 packets.

Boxes of sequence numbers left to right: 252, 253, 254, 255, 0, 1, 3, 4, joined by arrows. Box 3 is pink with 'Lost: 2' above it. Below: 255 to 0 is a wrap, not a loss
Figure 1 MAVLink uint8 sequence numbers

Example 1 Packet loss from sequence numbers

Sequence numbers the station received from one sender (system 1, component 1) over a period.

seqs = [250, 251, 252, 253, 254, 255, 0, 1, 3, 4, 5, 9, 10, 11, 12, 13]

lost = 0
for prev, cur in zip(seqs, seqs[1:]):
    gap = (cur - prev - 1) % 256
    if gap:
        print(f"after {prev:>3} came {cur:>3}: {gap} packet(s) lost")
    lost += gap
naive = sum(max(cur - prev - 1, 0) + (255 if cur < prev else 0) for prev, cur in zip(seqs, seqs[1:]))
print(f"received {len(seqs)}, lost {lost}, loss rate {lost / (lost + len(seqs)):.1%}")
print(f"(a naive count that ignores the wrap would report {naive} lost)")
after   1 came   3: 1 packet(s) lost
after   5 came   9: 3 packet(s) lost
received 16, lost 4, loss rate 20.0%
(a naive count that ignores the wrap would report 259 lost)

Count separately for each sender (system ID and component ID), since each has its own sequence. If a tool such as MAVProxy merges several senders, the computed rate will be wrong.

Splitting frames from a byte stream

A serial radio sends bytes back to back without frame boundaries. The receiver must find the MAVLink 2 start byte 0xFD, read the length, then check the CRC, computed over the header (excluding the start byte), the payload and the message type’s CRC_EXTRA. This value comes from the message definition, for example HEARTBEAT = 50 and ATTITUDE = 39. If sender and receiver use different versions of a message definition, the CRC fails, so it also catches incompatibility.

Example 2 Splitting frames and catching a bad one

A stream is built from four frames with junk bytes between them, and one byte of the third frame is corrupted. The instructor checked that pymavlink 2.4.50 reads these hand-built frames correctly.

import struct

def crc_x25(data, crc=0xFFFF):
    for b in data:
        tmp = b ^ (crc & 0xFF)
        tmp = (tmp ^ (tmp << 4)) & 0xFF
        crc = ((crc >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4)) & 0xFFFF
    return crc

CRC_EXTRA = {0: 50, 30: 39}                    # HEARTBEAT, ATTITUDE
NAMES = {0: "HEARTBEAT", 30: "ATTITUDE"}

def frame(seq, msgid, payload):
    hdr = bytes([0xFD, len(payload), 0, 0, seq, 1, 1]) + msgid.to_bytes(3, "little")
    crc = crc_x25(hdr[1:] + payload + bytes([CRC_EXTRA[msgid]]))
    return hdr + payload + struct.pack("<H", crc)

hb = struct.pack("<IBBBBB", 0, 2, 3, 0x81, 4, 3)
att = struct.pack("<Iffffff", 12000, 0.05, -0.02, 1.57, 0.01, 0.0, 0.02)
stream = bytearray(b"\x00\x13" + frame(10, 0, hb) + frame(11, 30, att) + b"\x55" + frame(12, 30, att) + frame(13, 0, hb))
bad_at = stream.index(bytes([0xFD, 28, 0, 0, 12])) + 15
stream[bad_at] ^= 0xFF                          # corrupt the payload of frame seq 12

i, good, bad = 0, {}, 0
while i < len(stream):
    if stream[i] != 0xFD or i + 12 > len(stream):
        i += 1
        continue
    n = stream[i + 1]
    fr = stream[i:i + 12 + n]
    msgid = int.from_bytes(fr[7:10], "little")
    crc = struct.unpack("<H", fr[10 + n:12 + n])[0]
    if msgid in CRC_EXTRA and crc_x25(fr[1:10 + n] + bytes([CRC_EXTRA[msgid]])) == crc:
        good[NAMES[msgid]] = good.get(NAMES[msgid], 0) + 1
        print(f"seq {fr[4]:>3}: {NAMES[msgid]:<9} ok")
        i += 12 + n
    else:
        bad += 1
        print(f"seq {fr[4]:>3}: CRC failed, resync")
        i += 1
print("good frames:", good, "| bad frames:", bad)
seq  10: HEARTBEAT ok
seq  11: ATTITUDE  ok
seq  12: CRC failed, resync
seq  13: HEARTBEAT ok
good frames: {'HEARTBEAT': 2, 'ATTITUDE': 1} | bad frames: 1

When the CRC fails, the receiver advances one byte at a time to find a new start byte, so junk bytes do not spoil the next frame, and the bad frame is discarded instead of passing wrong values to the application.

Analysis in simulation

Lab L09 in the drone knowledge base connects SITL to MAVProxy and forwards to a GCS and a Python script while Wireshark captures loopback packets, to compare the network packet rate with the rate the application reads. The unit stresses that packet rate is not data freshness: messages may arrive often while the values inside are stale.

A SITL autopilot box on the left, a UDP arrow to MAVProxy in the centre, which branches to QGroundControl at top right and a Python pymavlink script at bottom right. A Wireshark loopback box at the top has a dashed line pointing down at the UDP arrow
Figure 2 MAVLink data paths in a SITL experiment

IP addresses, subnets and routing

When MAVLink leaves the serial radio and travels over Wi-Fi, a cable or 4G, it rides on IP (Internet Protocol), which RFC 791 defines as the way to deliver a packet from one address to another across several networks. Every device on the network, such as the GCS laptop, the video receiver or the companion computer on the drone, needs an IP address: 32 bits written as four numbers, for example 192.168.10.10. UDP then adds a port number so the packet reaches the right program on that machine. The MAVProxy guide notes that MAVLink over IP usually uses port 14550, as in --out=udp:192.168.1.1:14550.

  • Subnet: addresses that share the same leading bits and can talk directly, without a router, like houses on the same street. CIDR notation (RFC 4632) writes the number of shared bits after a slash: 192.168.10.0/24 means the first 24 bits are the network, leaving 8 bits (256 addresses) for devices. Splitting it into /26 gives four blocks of 64.
  • Private addresses: RFC 1918 reserves 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16 for internal networks. These are not routed on the internet, so a field network uses them freely, and outside devices cannot reach them directly unless someone deliberately opens a path.
  • Routing: a device with a packet for another subnet sends it to a router listed in its routing table. RFC 4632 states that forwarding uses the longest match: if several routes cover a destination, the one with the longest prefix (the most specific) wins. The 0.0.0.0/0 route, the default route, matches everything and is used only when nothing more specific does.

Kurose and Ross (2025) explain addressing, subnets and routing in more depth, including how DHCP hands out addresses automatically.

Example 3 A field station network plan

The team has the block 192.168.10.0/24 (assumed) and wants separate subnets for the station, the drone link, field sensors and a spare. The GCS laptop 192.168.10.10/26 has three routes: its own subnet directly, the drone subnet through a radio bridge (a device that joins the two IP networks over a radio link), and everything else through the internet router.

import ipaddress as ip

site = ip.ip_network("192.168.10.0/24")
names = ["ground station", "drone link", "field sensors", "spare"]
for name, net in zip(names, site.subnets(new_prefix=26)):
    hosts = list(net.hosts())
    print(f"{name:<14}: {str(net):<17} hosts {hosts[0]} - {hosts[-1]} ({len(hosts)})")

ROUTES = [                                     # routing table of the GCS laptop 192.168.10.10/26
    ("192.168.10.0/26", "direct (station switch)"),
    ("192.168.10.64/26", "192.168.10.2 (radio bridge)"),
    ("0.0.0.0/0", "192.168.10.1 (internet router)"),
]

def next_hop(dst):
    addr = ip.ip_address(dst)
    match = [(ip.ip_network(net), hop) for net, hop in ROUTES if addr in ip.ip_network(net)]
    net, hop = max(match, key=lambda m: m[0].prefixlen)       # longest prefix wins
    return len(match), net, hop

for dst in ("192.168.10.20", "192.168.10.70", "8.8.8.8"):
    n, net, hop = next_hop(dst)
    kind = "private" if ip.ip_address(dst).is_private else "public"
    print(f"{dst:<13} ({kind}): matching routes {n}, use {net} -> {hop}")
ground station: 192.168.10.0/26   hosts 192.168.10.1 - 192.168.10.62 (62)
drone link    : 192.168.10.64/26  hosts 192.168.10.65 - 192.168.10.126 (62)
field sensors : 192.168.10.128/26 hosts 192.168.10.129 - 192.168.10.190 (62)
spare         : 192.168.10.192/26 hosts 192.168.10.193 - 192.168.10.254 (62)
192.168.10.20 (private): matching routes 2, use 192.168.10.0/26 -> direct (station switch)
192.168.10.70 (private): matching routes 2, use 192.168.10.64/26 -> 192.168.10.2 (radio bridge)
8.8.8.8       (public): matching routes 1, use 0.0.0.0/0 -> 192.168.10.1 (internet router)

Each /26 block holds 64 addresses but only 62 devices, because the first is the network address and the last is the broadcast address. The companion computer at .70 looks as if it is on the same network as the laptop, but it sits in another subnet, so its packets must go through the radio bridge; if the laptop lacks that route, they go to the internet router and vanish, and the GCS sees “no heartbeat” although the radio works. Check the address, subnet mask and routes of every device before blaming the radio.

Module lab

Lab: capturing and analysing MAVLink (L09)

  1. Start SITL and MAVProxy and record the endpoints, ports and system IDs used.
  2. Write a pymavlink script that reads ATTITUDE and stores sequence numbers and times to CSV.
  3. Use the code from Example 1 to compute packet loss per sender.
  4. Capture loopback packets with Wireshark and compare the packet rate with the rate the script reads.
  5. Record raw bytes from the radio’s serial port (if available) and use Example 2 to count bad frames.

Common mistakes

Watch out

  • Subtracting sequence numbers directly without handling the wrap.
  • Merging several senders into one sequence.
  • Using different message definition versions so the CRC fails.
  • Treating packet rate as data freshness.
  • Exposing control ports to the internet during experiments.
  • Putting devices in different subnets without a route between them, then blaming the radio.

Summary

  • MAVLink sequence numbers are uint8; count losses modulo 256 per sender.
  • The MAVLink CRC includes a per-message CRC_EXTRA, catching both corrupted data and mismatched definitions.
  • The receiver resynchronises on a new start byte when a frame is bad.
  • Compare Wireshark data with the application, and separate packet rate from data freshness.
  • On IP networks, check each device’s address, subnet and routes; routers choose the longest matching prefix, and RFC 1918 private addresses are not routed on the internet.

Check your understanding

  1. Sequence 254 is followed by 2. How many packets were lost?
  2. With a /26 subnet mask, are 192.168.10.20 and 192.168.10.70 in the same subnet?
  3. What is CRC_EXTRA for?
  4. Why count sequences separately per sender?
  5. Messages arrive at 10 Hz but the position value never changes. What does that suggest?
Answers
  1. packets (255, 0, 1).
  2. No. /26 blocks run .0 to .63 and .64 to .127, so they are in different subnets and need a router between them.
  3. It adds a per-message-type value into the CRC to check that sender and receiver use the same message definition.
  4. Each sender has its own sequence; merging them looks like false losses or duplicates.
  5. The data may be stale, for example a sensor or estimator stopped updating, even though the link works.

Key formulas

Packets lost between two sequence numbers
Packet loss rate

Key references

  1. MAVLink Development Team. Packet serialization. MAVLink developer guide. link
  2. MAVLink Development Team. MAVLink developer guide. link
  3. ArduPilot and MAVLink contributors. (2026). pymavlink (Version 2.4.50) [Computer software]. PyPI. link
  4. Kurose, J. F., & Ross, K. W. (2025). Computer networking: A top-down approach (9th ed.). Pearson. link
  5. Postel, J. (1981). Internet Protocol (RFC 791). RFC Editor. link
  6. Rekhter, Y., Moskowitz, B., Karrenberg, D., de Groot, G. J., & Lear, E. (1996). Address allocation for private internets (RFC 1918). RFC Editor. link
  7. Fuller, V., & Li, T. (2006). Classless inter-domain routing (CIDR): The Internet address assignment and aggregation plan (RFC 4632). RFC Editor. link
  8. ArduPilot Dev Team. Starting MAVProxy. MAVProxy documentation. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Communications, networks and IoT · Programming and digital technology