Softivation

JSON coming over TCP from a Raspberry Pi throws an error

If JSON arriving from a Raspberry Pi over TCP throws an Extra data error at the ground station, the packets are sticking together. Frame them with a newline and decode line by line from a buffer.

Furkan IŞIKAY 6 min read

The code on the Raspberry Pi reads the position from the Pixhawk, turns each measurement into JSON and sends it to the ground station over TCP. While the two programs run on the same computer, the data flows fine. When you add map drawing to the ground station or connect the Pi over Wi-Fi, the receiver throws an error after a few packets and quits.

Before blaming the cable and the Wi-Fi, look at what TCP does: it delivers bytes in order, but it doesn't know which byte belongs to which packet. Marking where a packet ends is the job of the sender and receiver.

Why it works on the bench but breaks in the field

On every recv call, the ground station takes all the bytes that have accumulated up to that moment. If the receiver doesn't wait at all between two reads, each recv usually brings back one packet. That's why you don't see the problem on the bench.

If the Pi sends 50 packets per second and the receiver spends 0.1 seconds drawing the map after every read, a single recv will usually get five packets. When the wait goes up to 0.5 seconds, that number goes up to twenty-five.

In the figure, see the packets the Pi sends one at a time in the top strip, and the ground station's reads in the middle strip: the second recv takes five packets, #1 through #5, as a single chunk.

The Pi sends each packet separately; the ground station accumulates five of them between two recv calls

The Pi sends each packet separately; the ground station accumulates five of them between two recv calls
Look at the five packets gathered by the red bracket and the Extra data label under it.

Think of a typical setup in TEKNOFEST Fighting UAV. The Pi sends the coordinates of the target it found on the camera and the drone's altitude, and the ground station plots both on the map. Each time the map refreshes, the receiver doesn't call recv for a while. Packets pile up in the meantime and the program crashes on the first combined read.

What the error text tells you

json.loads decodes the first JSON object in the text, then checks whether the text has ended. If bytes remain behind it, it raises an Extra data error. So the first packet arrived complete. The problem is at the boundary between the two packets.

The char number in parentheses shows where the second packet starts. If you see char 66, the first packet, newline included, is 66 characters long.

recv can also cut a packet in the middle: if the packet is larger than the number of bytes recv returns at once, or if the bytes arrive from the network in pieces. Then the error text changes. If the cut falls inside a text value you'll see Unterminated string, and if it falls right after a comma you'll see Expecting property name enclosed in double quotes.

Adding a newline alone isn't enough

The first fix that comes to mind is adding a newline (\n) to the end of every packet on the Pi. If the receiver still treats every recv as a single packet, the error still comes, only its location changes: Extra data: line 2 column 1 (char 66). The newline works when the receiver looks for it and splits the bytes there.

The fix: end each packet with a newline, split line by line at the receiver

On the Pi side, change two lines: add \n to the end of the packet, and call sendall instead of send. send may send only part of the bytes and return; sendall keeps trying until all of them have gone.

PythonPi side, the two changed lines
satir = json.dumps(paket) + "\n"          # message boundary: newline
yki.sendall(satir.encode("utf-8"))        # sendall, not send: make sure everything goes out

At the ground station, append incoming bytes to a buffer, cut from the buffer wherever you find a newline, and decode that line. A half-received line waits in the buffer, and the next recv completes it.

Pythonyki_al.py
# GCS side: split the TCP stream line by line, decode each line as separate JSON
import json, socket

sunucu = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sunucu.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sunucu.bind(("0.0.0.0", 5005))
sunucu.listen(1)
baglanti, adres = sunucu.accept()
print("Pi connected:", adres)

tampon = b""
while True:
    parca = baglanti.recv(4096)
    if not parca:                      # 0 bytes: the Pi closed the connection
        print("connection closed"); break
    tampon += parca
    while b"\n" in tampon:             # process every complete line in the buffer
        satir, tampon = tampon.split(b"\n", 1)
        if not satir.strip():
            continue
        paket = json.loads(satir)
        print(paket["no"], paket["alt"], paket["mod"])
    # a partial line waits in the buffer; the next recv completes it

What you'll see

If you run yki_al.py at the ground station first and then the code on the Pi, each packet arrives on its own line:

Output
Pi connected: ('127.0.0.1', 34394)
0 -0.01 STABILIZE
1 -0.01 STABILIZE
2 -0.01 STABILIZE
3 -0.01 STABILIZE

Even if the receiver does 2 seconds of other work before each read, the numbers don't skip. In that case recv fills 4096 bytes and cuts a line in the middle. The buffer joins the cut line with the next read, and the sequence runs from 0 to 635 without a break.

Error messages

json.decoder.JSONDecodeError: Extra data: line 1 column 82 (char 81)

Two or more packets arrived in a single recv, and the text didn't end after the first packet. End packets with a newline, and decode line by line from the buffer at the receiver.

json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 63 (char 62)

recv cut the packet in the middle of a text value. The buffer method joins the cut piece with the next read.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Empty data went to json.loads. If recv returned 0 bytes, the other side closed the connection. Break out of the loop without trying to decode.

ConnectionResetError: [Errno 104] Connection reset by peer

This error appears on the Pi side: the program at the ground station has closed, most often with one of the JSON errors above. Fix the error at the ground station first, then restart the code on the Pi.

More in the course

We cover data transfer from a Raspberry Pi to the ground station, and serial port and TCP/UDP communication, step by step in the Drone Communication Technologies course. In the newly added lesson, we show byte by byte how a cut line is joined in the buffer. The receiver code that counts lost and corrupt packets and the Pixhawk's TELEM2 settings are there too.

Was this article helpful?

Free resourceTEKNOFEST UAV software readiness checklistCheck off your team's software readiness stage by stage on a printable list.

Learn this topic from start to finish

Season plan: all six courses for 9 months, ₺790 a month. ₺390 a month for high school and university students, ₺351 the first month with your member code. You can stop in any month you like. Start the Season plan · I'm a student