Section 12.36

pyserial

Full name: pySerial: a coined name from py (for Python §12.23) and serial; it is not an abbreviation. The package is installed under the name pyserial and imported as the module serial.

Definition

pySerial is a Python library for serial ports: connections that carry a stream of bytes one bit after another, such as a UART §6.23 (universal asynchronous receiver-transmitter) line or a USB adapter that presents itself as one. A program opens a port with serial.Serial, sets the line speed and other settings, and then writes and reads bytes. A read returns the bytes that have arrived, up to the number requested, within the configured timeout §9.34; it knows nothing about the messages that the application builds from those bytes. Chris Liechti wrote pySerial.

The idea

A development board §6.5 sends 6-byte status records over a serial port. A script calls port.read(6) with a timeout of 0.1 seconds and receives 3 bytes; the other 3 arrive 0.2 seconds later, because the firmware was busy between writing the two halves. Nothing is broken. A serial port carries a stream of bytes with no message boundaries. Where one read’s result ends depends on when the bytes arrived, how a USB adapter grouped them into packets and when the operating system ran the script, not on where the sender’s records end.

A serial port is like a conveyor belt that carries letters without envelopes. The receiver picks up whatever letters have reached the end of the belt; the belt says nothing about where one word stops and the next begins. Framing puts the envelopes back: the sender marks each record, for example by sending its length first, and the receiver collects bytes until a record is complete. The picture stops at one point: a real serial line can lose or corrupt bytes, so the framing also needs a way to detect damage, such as a checksum §4.32, and a way to find the start of the next record after an error.

How it works

Opening a port: port = serial.Serial("/dev/ttyUSB0", baudrate=115200, timeout=0.1). The device name is, for example, /dev/ttyUSB0 on Linux or COM3 on Windows. baudrate is the signaling speed of the line, which for a UART is in bits per second; the default is 9600. bytesize, parity and stopbits default to 8 data bits, no parity bit (an optional extra bit for detecting errors) and 1 stop bit, written 8N1. rtscts=True turns on hardware flow control, in which the receiver pauses the sender over two extra signal wires, RTS (request to send) and CTS (clear to send). timeout limits how long a read may wait, in seconds.

What port.read(n) returns depends on the timeout:

The result is a Python bytes object. An empty result means only that no byte arrived in time. A serial port has no end of file: the other side cannot signal through a read that it has finished or gone away. port.in_waiting gives the number of bytes received and not yet read. port.read_until(expected=b"\n") reads until the given byte sequence has arrived, a size limit is reached or the timeout expires, so it too can return part of a line.

port.write(data) returns the number of bytes written, where written means handed to the operating system’s driver, not received by the other side. port.flush() waits until the driver has sent everything in its output buffer. Only a reply from the other side shows that the data arrived and was processed.

A receive loop turns the stream back into records:

  1. Keep one receive buffer per port, such as a bytearray, that lives across reads, and append the bytes of each read to it.

  2. While the buffer begins with a complete record, remove that record from the front and process it. With a length prefix §4.30, a field at the start of each record that states its length, the first bytes tell how many bytes the record needs.

  3. Reject a length larger than the protocol allows, and discard the buffered bytes if the buffer outgrows the largest possible record. A reserved byte value that marks the start of each record lets the receiver find the next record after such an error.

  4. Verify a checksum or CRC (cyclic redundancy check) over each record to detect corrupted bytes.

  5. Wait for a whole record against one deadline, computed for example from time.monotonic(), because the port’s timeout limits each read separately.

Worked example

Records are length-prefixed: one length byte, then that many payload bytes. The board sends one record that carries the 5 ASCII characters hello:

05 68 65 6c 6c 6f

That is 1+5=61 + 5 = 6 bytes. The line runs at 115200 baud with 8N1 settings, so each byte occupies 10 bits on the line: 1 start bit, 8 data bits and 1 stop bit. One byte therefore takes 10/11520010 / 115200 seconds, about 0.0868 milliseconds, and the whole record about 6×0.0868≈0.5216 \times 0.0868 \approx 0.521 milliseconds.

The script polls the port with timeout=0, calling port.read(64) from time to time. Assume the driver passes on each byte as soon as its stop bit has arrived, count time from the start of the record’s first bit, and write ⌊x⌋\lfloor x \rfloor for xx rounded down to a whole number.

Treating each read as a record would have produced three broken records, of 2, 1 and 3 bytes.

Suppose the board sends a second record, 03 61 62 63, right behind the first, and the third read returns the end of one record together with the start of the next: 6c 6c 6f 03 61. The buffer then holds 3+5=83 + 5 = 8 bytes. The first record takes 6 of them, which leaves 8−6=28 - 6 = 2 bytes, 03 61. Their length byte says the next record needs 1+3=41 + 3 = 4 bytes, so the 2 bytes stay in the buffer until the other 2 arrive.

Stated precisely

Let TT be the port’s timeout, let nn be the size requested from read(n), and let rr be the number of bytes returned. The pySerial documentation gives this contract:

In every case the returned bytes are the next rr bytes of the received stream, in order. Joined end to end, the results of all reads equal the received stream; where one result ends carries no information about where a record ends.

Two assumptions sit underneath, and pySerial checks neither.

  1. The stream is complete. Bytes that the hardware or the operating system dropped, for example because a receive buffer overflowed while the script was slow to read, are missing from the stream, and read reports no error.

  2. There is one reader. On Linux, two programs can open the same port at once by default, and each byte goes to whichever program reads it first. Passing exclusive=True when opening makes a second exclusive open of the port fail.

Limits and common mistakes

One read is not one record, in any timeout mode. Even read(6) with timeout=None, which returns exactly 6 bytes, can return bytes that start inside one record and end inside the next, if the script began reading in the middle of the stream or a byte was lost.

The timeout limits each call, not the whole exchange. A loop that calls read ten times with a 1-second timeout can wait up to 10×1=1010 \times 1 = 10 seconds for one record. A deadline for the whole record bounds the total.

An empty read is not end of file and not a closed connection; it means only that nothing arrived in time. On Linux, reading from a USB serial adapter that has been unplugged raises serial.SerialException.

A completed write is not delivery. The bytes may still sit in a buffer of the operating system or the adapter, and the other side may not be reading at all.

Opening the port can reset the board. On some development boards, Arduino boards among them, the DTR (data terminal ready) signal of the USB serial chip is wired to the reset input of the microcontroller §6.1, and opening the port changes DTR. The first bytes after opening can then be the board’s startup output, or nothing until the board has restarted.

Questions answered

Does read return an entire application record or only currently available bytes?

A pySerial read(n) returns only bytes of the received stream, at most nn of them, and never knows where an application record begins or ends. With a timeout t>0t > 0 it returns as soon as nn bytes have arrived, or after tt seconds with whatever arrived by then, possibly nothing. With timeout=0 it returns at once with the bytes already received. With no timeout it waits for exactly nn bytes, and even those form a record only if the reader happens to be in step with the record boundaries.

The application must therefore frame the stream itself. It keeps a receive buffer across reads, appends each result, and removes a record only when the buffer holds all of it, as a length prefix or a delimiter (a reserved byte value that ends each record) defines it. It bounds the record length and the buffer size, verifies a checksum or CRC (cyclic redundancy check) for each record, and applies a deadline to the whole record. An empty result means only that nothing arrived before the timeout.

Related entries: termios and tty (§12.42), select and polling (§12.43), Length-prefix framing (§4.30), Asynchronous completion (§9.28), UART (§6.23), Checksum versus CRC (§4.32), Deadline versus timeout (§9.34). Further reading: [126].