fix: prevent LED flicker from dropped knob messages at read-buffer boundary

parse_messages() previously advanced past a 0xFE start byte whenever no
complete frame could be matched, silently consuming partial frames at the
end of each ser.read(64) call as garbage.  When the device sends 20-50
rapid knob messages during a fast turn and one message straddles the
64-byte read boundary, the split message was discarded: the daemon skipped
a knob-position update, the LED color lagged, and when the next complete
message arrived the color jumped — producing a visible flicker.

Fix: break out of the parse loop when a 0xFE is followed by a known type
byte (0x02/0x03/0x06/0x07) but the buffer does not yet hold a complete
frame.  The partial bytes are returned in the remainder and prepended to
the next ser.read() chunk, so no message is ever lost.

Also sync last_led_colors after the initial send_leds() on connect so the
dedup guard is accurate from the first knob event instead of from the
first heartbeat.

Adds 5 tests covering partial heartbeat, button, and knob frames, the
split-read round-trip, and unknown frame type skipping (61 pass total).
This commit is contained in:
Sean Doran committed 2026-02-28 14:45:46 -05:00
1 parent 4c1d9e53d1
commit 390e290b57
2 files changed
+64 -3

No files matched your search

+19 -1
View File
@@ -81,6 +81,22 @@ def parse_messages(buf: bytearray) -> tuple[list[dict], bytearray]:
i += 6
else:
# buf[i] == 0xFE but no complete frame matched. If the following
# byte identifies a known frame type, this is a partial (split)
# frame at the end of the read buffer — break and return it in the
# remainder so the next serial read can complete it. Only skip
# past this 0xFE when we can rule out a valid frame start (unknown
# type byte with enough bytes already present to decide).
if remaining < 2:
break # Lone 0xFE — could be the start of any frame type.
type_byte = buf[i + 1]
if type_byte == 0x02 and remaining < 3:
break # Partial heartbeat: waiting for terminator 0xFF.
if type_byte in (0x06, 0x07) and remaining < 4:
break # Partial button: waiting for id + 0xFF.
if type_byte == 0x03 and remaining < 6:
break # Partial knob: waiting for id, hi, lo, 0xFF.
# Unknown / corrupted frame — skip this 0xFE byte.
i += 1
return messages, bytearray(buf[i:])
@@ -378,7 +394,9 @@ def main() -> None:
with serial.Serial(port, baud, timeout=0.1) as ser:
log.info("Connected to %s", port)
buf.clear()
send_leds(ser, all_led_colors(config, knob_norms))
initial_colors = all_led_colors(config, knob_norms)
send_leds(ser, initial_colors)
last_led_colors[:] = initial_colors
while True:
data = ser.read(64)