DEV Community

Cover image for RS485 locker controller frames truncating under burst unlocks on Linux
Habeeb
Habeeb

Posted on

RS485 locker controller frames truncating under burst unlocks on Linux

Hi everyone,

We are running an edge controller on Debian 12 (Raspberry Pi CM4, kernel 6.6.x) using Python 3.11 (pyserial) over a USB-to-RS485 FTDI adapter (/dev/ttyUSB0 @ 9600 baud) to drive modular 12V solenoid lock controller boards for an on-prem smart locker system.

Expected Behavior

When an employee scans an RFID badge or QR code at the kiosk, the Python daemon sends a 10-byte RS485 command frame to the target slave board, waits ~80ms for the door-sensor status ACK (0xAA 0x55 ...), and updates the local SQLite compartment state.

Actual Behavior

During shift changes—when multiple users trigger unlocks back-to-back or when our background door-state polling loop overlaps an unlock request—serial.read() returns partial 4–6 byte frames or times out, causing the daemon to log a false "door failed to open" state even though the solenoid physically clicked open.

Relevant snippet from our serial worker:

python
with serial_lock:
ser.reset_input_buffer()
ser.write(build_unlock_frame(board_id, slot_id))
ser.flush()
time.sleep(0.05)
resp = ser.read(10)

Error logged via journalctl -u locker-daemon:

text
Nov 25 08:51:14 edge-node-02 locker-daemon[812]: WARNING: board=0x03 slot=14 short read (got 5/10 bytes): b'\xaa\x55\x03\x0e\x01'
Nov 25 08:51:14 edge-node-02 locker-daemon[812]: ERROR: CRC mismatch on compartment status poll, retrying frame

What We've Tried

  1. Added a threading.Lock() around all RS485 bus reads/writes so polling and unlock commands don't collide in Python.
  2. Lowered /sys/bus/usb-serial/devices/ttyUSB0/latency_timer from 16 to 1.
  3. Increased timeout=0.3 on pyserial.Serial, which reduces timeouts slightly but still drops tail bytes when 3+ boards reply sequentially.

Is calling ser.reset_input_buffer() right before write() discarding delayed turnaround bytes from the RS485 transceiver, or should we switch from fixed-length ser.read(10) to a frame-header/CRC state machine reading byte-by-byte until the footer?

Top comments (1)

Collapse
 
osamamalik profile image
Osama Malik •

I think your second guess is right, and there's also a timing bug that explains the "5/10 bytes then CRC mismatch" pair in your log.

What is likely happening: you sleep 50 ms and then call ser.read(10). With a ~80 ms ACK, the read can return after timeout with only the bytes that have arrived so far (your 5-byte aa 55 03 0e 01). The other 5 bytes arrive a moment later and stay in the buffer. The next transaction calls reset_input_buffer(), which may run before those late bytes arrive, so the tail shows up in the next response. That gives you a bad CRC on the next poll even though the lock opened fine. The threading.Lock protects the bus, but it can't fix a read that gives up early.

I would change it to a small framed read with a deadline:

import time

HEADER = b"\xaa\x55"
FRAME_LEN = 10

def read_frame(ser, deadline_s=0.4):
    end = time.monotonic() + deadline_s
    buf = bytearray()
    while time.monotonic() < end:
        buf += ser.read(max(1, ser.in_waiting))   # with a short timeout, e.g. 0.02
        i = buf.find(HEADER)
        if i > 0:
            del buf[:i]                           # drop garbage before the header
        if len(buf) >= FRAME_LEN and buf.startswith(HEADER):
            frame = bytes(buf[:FRAME_LEN])
            if crc_ok(frame):
                return frame
            del buf[:2]                           # bad CRC: resync on the next header
    return None

with serial_lock:
    ser.reset_input_buffer()
    ser.write(build_unlock_frame(board_id, slot_id))
    ser.flush()
    resp = read_frame(ser)
Enter fullscreen mode Exit fullscreen mode

A few more things that help on RS485:

  • Don't use a fixed sleep plus read(10). Wait for the header and the full length until a deadline, as above.
  • Keep one thread as the only owner of the port, and send both unlocks and polls through a queue. Then a poll can never start while an unlock reply is still on the wire.
  • Add a short guard time (about 5-10 ms) after each reply before the next write, so the transceiver has finished turning around.
  • Only mark "door failed" after a valid frame says so, or after N retries with no valid frame. A timeout alone shouldn't change the state, since the solenoid may have fired.
  • If your FTDI adapter is auto-direction, check that it has no extra delay on the direction switch. Some cheap ones do.

Resetting the input buffer before the write is fine, as long as the previous transaction was read to the end of its frame.