fix(#711): drain serial on each callback; never drop bytes silently

Two app-side halves of the #702 fix.

The native USB service read one 8 KB chunk per flserial callback, which
left the rest of a burst waiting in the native ring. It now drains
until the ring is empty, bounded at 32 reads (the ring's 256 KB) so a
stuck read cannot spin.

The frame decoder skipped bytes it could not frame (noise, an oversized
length) without a word, so when bytes were lost upstream, whole frames
vanished with no trace. It now counts them and keeps the first 16; the
native USB, web USB and TCP services log each batch as an error with
the count and a hex sample (SAFELANE 6). The web service shares the
decoder, so it gets the same logging, matching the plan's "all
transports" intent.

Tests cover no report on clean input, noise before a frame, an
oversized header, take-once, the capped sample and reset; with the
count disabled, 4 fail.

Epic #702.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/743/head
Strycher 2 months ago committed by diffwireauto
parent a430a47561
commit 845b0f1e55

@ -167,6 +167,10 @@ class TcpTransportService {
}
_addFrame(packet.payload);
}
final skipped = _frameDecoder.takeSkipReport();
if (skipped != null) {
_debugLogService?.error('TCP ${skipped.describe()}', tag: 'TCP');
}
}
void _handleSocketError(Object error, [StackTrace? stackTrace]) {

@ -37,13 +37,58 @@ class UsbSerialDecodedPacket {
bool get isRxFrame => frameStart == usbSerialRxFrameStart;
}
/// Bytes the decoder could not frame and discarded (#711). Lost bytes mean
/// lost frames, so callers log this as an error rather than drop it quietly.
class UsbSerialSkipReport {
const UsbSerialSkipReport({required this.count, required this.sample});
final int count;
/// The first discarded bytes, for the log.
final List<int> sample;
String describe() {
final hex = sample
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join(' ');
return 'discarded $count byte(s) that could not be framed '
'(first: $hex${count > sample.length ? ' ...' : ''})';
}
}
class UsbSerialFrameDecoder {
static const int _skipSampleLength = 16;
final List<int> _rxBuffer = <int>[];
int _startIndex = 0;
int _skipped = 0;
final List<int> _skipSample = <int>[];
void reset() {
_rxBuffer.clear();
_startIndex = 0;
_skipped = 0;
_skipSample.clear();
}
/// Returns what was discarded since the last call, or null if nothing was.
UsbSerialSkipReport? takeSkipReport() {
if (_skipped == 0) return null;
final report = UsbSerialSkipReport(
count: _skipped,
sample: List<int>.unmodifiable(_skipSample),
);
_skipped = 0;
_skipSample.clear();
return report;
}
void _skipByte() {
_skipped++;
if (_skipSample.length < _skipSampleLength) {
_skipSample.add(_rxBuffer[_startIndex]);
}
_startIndex++;
}
List<UsbSerialDecodedPacket> ingest(Uint8List bytes) {
@ -63,7 +108,7 @@ class UsbSerialFrameDecoder {
if (_rxBuffer[_startIndex] != usbSerialRxFrameStart &&
_rxBuffer[_startIndex] != usbSerialTxFrameStart) {
_startIndex++;
_skipByte();
_compactBufferIfNeeded();
continue;
}
@ -77,7 +122,7 @@ class UsbSerialFrameDecoder {
final payloadLength =
_rxBuffer[_startIndex + 1] | (_rxBuffer[_startIndex + 2] << 8);
if (payloadLength > usbSerialMaxPayloadLength) {
_startIndex++;
_skipByte();
_compactBufferIfNeeded();
continue;
}

@ -421,10 +421,16 @@ class UsbSerialService {
unawaited(disconnect().whenComplete(_closeFrameController));
}
// One readList() returns at most 8 KB, so a single read per callback left
// the rest of a burst waiting in the native ring (#702, #711). Drain it,
// bounded to the ring's 256 KB so a stuck read can never spin forever.
static const int _maxReadsPerCallback = 32;
void _handleSerialData(FlSerialEventArgs event) {
try {
final bytes = event.serial.readList();
if (bytes.isNotEmpty) {
for (var i = 0; i < _maxReadsPerCallback; i++) {
final bytes = event.serial.readList();
if (bytes.isEmpty) break;
_ingestRawBytes(Uint8List.fromList(bytes));
}
} catch (error, stack) {
@ -465,6 +471,12 @@ class UsbSerialService {
}
_addFrame(packet.payload);
}
final skipped = _frameDecoder.takeSkipReport();
if (skipped != null) {
final message = 'USB serial ${skipped.describe()}';
debugPrint(message);
_debugLogService?.error(message, tag: 'USB Serial');
}
}
void _addFrame(Uint8List payload) {

@ -546,6 +546,12 @@ class UsbSerialService {
}
_addFrame(packet.payload);
}
final skipped = _frameDecoder.takeSkipReport();
if (skipped != null) {
final message = 'USB serial ${skipped.describe()}';
debugPrint(message);
_debugLogService?.error(message, tag: 'USB Serial');
}
}
void _addFrame(Uint8List payload) {

@ -164,4 +164,81 @@ void main() {
expect(packets.single.isRxFrame, isTrue);
expect(packets.single.payload, orderedEquals(<int>[0x88]));
});
group('skip report (#711): discarded bytes are never silent', () {
test('clean input reports nothing', () {
final decoder = UsbSerialFrameDecoder();
decoder.ingest(
Uint8List.fromList(<int>[usbSerialRxFrameStart, 0x01, 0x00, 0x55]),
);
expect(decoder.takeSkipReport(), isNull);
});
test('counts and samples noise before a frame', () {
final decoder = UsbSerialFrameDecoder();
final packets = decoder.ingest(
Uint8List.fromList(<int>[
0xAA,
0xBB,
usbSerialRxFrameStart,
0x01,
0x00,
0x55,
]),
);
expect(packets.single.payload, orderedEquals(<int>[0x55]));
final report = decoder.takeSkipReport()!;
expect(report.count, 2);
expect(report.sample, orderedEquals(<int>[0xAA, 0xBB]));
expect(report.describe(), contains('discarded 2 byte(s)'));
expect(report.describe(), contains('aa bb'));
});
test('counts an oversized header and still decodes the next frame', () {
final decoder = UsbSerialFrameDecoder();
final oversized = usbSerialMaxPayloadLength + 1;
final packets = decoder.ingest(
Uint8List.fromList(<int>[
usbSerialRxFrameStart,
oversized & 0xff,
(oversized >> 8) & 0xff,
usbSerialRxFrameStart,
0x01,
0x00,
0x44,
]),
);
expect(packets.single.payload, orderedEquals(<int>[0x44]));
expect(decoder.takeSkipReport()!.count, 3);
});
test('a report is taken once, then cleared', () {
final decoder = UsbSerialFrameDecoder();
decoder.ingest(Uint8List.fromList(<int>[0x01, 0x02]));
expect(decoder.takeSkipReport()!.count, 2);
expect(decoder.takeSkipReport(), isNull);
});
test('the sample is capped, the count is not', () {
final decoder = UsbSerialFrameDecoder();
decoder.ingest(Uint8List.fromList(List<int>.filled(40, 0x00)));
final report = decoder.takeSkipReport()!;
expect(report.count, 40);
expect(report.sample, hasLength(16));
expect(report.describe(), endsWith('...)'));
});
test('reset clears a pending report', () {
final decoder = UsbSerialFrameDecoder();
decoder.ingest(Uint8List.fromList(<int>[0x01]));
decoder.reset();
expect(decoder.takeSkipReport(), isNull);
});
});
}

Loading…
Cancel
Save

Powered by TurnKey Linux.