Files
riojoy/src/RioJoy.Core/Protocol/PacketParser.cs
T
CydandClaude Fable 5 3b2af7b79a Phase 8A (1/2): de-Span the serial layer, swap JSON to Newtonsoft
Prepares RioJoy.Core for the net40 (Windows XP) target, which has no
System.Memory, ValueTask, or System.Text.Json:
- IRioTransport and the whole protocol/framing layer now use byte[] +
  Task (RioPacket.Payload, PacketParser/Builder, RioChecksum, replies,
  AnalogReport, RioHidReport). At 9600 baud Span bought nothing; the
  SerialPortTransport bridge copies disappear entirely.
- ConfigStore/OverlayTemplateStore switch to Newtonsoft 13 with the
  same conventions (indented, PascalCase, string enums, null-skipping);
  verified against the real STJ-written config.json and regions.json
  (load + round-trip). System.Memory and System.Text.Json packages
  dropped.

275 tests green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 20:36:19 -05:00

127 lines
4.5 KiB
C#

namespace RioJoy.Core.Protocol;
/// <summary>
/// Streaming receive-side framing state machine, fed raw bytes from the serial
/// port. Faithful port of the framing loop in <c>ReadCommBlock</c>
/// (riovjoy2.cpp#L860); see docs/PROTOCOL.md §2.
///
/// <para>Rules:</para>
/// <list type="bullet">
/// <item>Outside a packet, a byte in the command range starts a packet whose
/// total length is <c>1 + payloadLen + 1</c> (command + payload + checksum).</item>
/// <item>Outside a packet, any other byte is reported as a
/// <see cref="RioRxEventKind.ControlByte"/> (ACK/NAK/RESTART/IDLE or garbage).</item>
/// <item>Mid-packet, a byte with the high bit set aborts the packet and
/// resynchronizes (<see cref="RioRxEventKind.FramingError"/>); that byte is
/// discarded, matching the legacy <c>continue</c>.</item>
/// <item>When the final (checksum) byte arrives, a
/// <see cref="RioRxEventKind.Packet"/> is emitted with
/// <see cref="RioRxEvent.ChecksumValid"/> set from a real checksum compare.</item>
/// </list>
///
/// Each input byte produces at most one event, so the per-byte
/// <see cref="Feed(byte, out RioRxEvent)"/> returns a single optional event.
/// This type is not thread-safe; drive it from one reader.
/// </summary>
public sealed class PacketParser
{
// Max framed packet = command(1) + AnalogReply payload(10) + checksum(1) = 12.
private const int MaxPacketBytes = 16;
private readonly byte[] _buffer = new byte[MaxPacketBytes];
// Bytes still expected to complete the current packet (0 = not in a packet).
private int _remaining;
// Count of bytes stored in _buffer for the current packet (incl. command).
private int _count;
/// <summary>True while a packet is partially received.</summary>
public bool InPacket => _remaining != 0;
/// <summary>Discard any in-progress packet and reset to the idle state.</summary>
public void Reset()
{
_remaining = 0;
_count = 0;
}
/// <summary>
/// Feed one received byte. Returns <see langword="true"/> and sets
/// <paramref name="ev"/> when this byte produced an event; otherwise returns
/// <see langword="false"/> (the byte was consumed into an in-progress packet).
/// </summary>
public bool Feed(byte ch, out RioRxEvent ev)
{
if (_remaining != 0)
{
// Mid-packet. A high-bit byte is a framing error → abort and resync.
if ((ch & 0x80) != 0)
{
Reset();
ev = RioRxEvent.ForFramingError(ch);
return true;
}
_buffer[_count++] = ch;
_remaining--;
if (_remaining == 0)
{
ev = CompletePacket();
return true;
}
ev = default;
return false;
}
// Not in a packet.
if (RioCommandTable.IsCommand(ch))
{
_count = 0;
_buffer[_count++] = ch;
_remaining = RioCommandTable.PayloadLength(ch) + 1; // + checksum byte
ev = default;
return false;
}
// A byte outside framing: control character (ACK/NAK/RESTART/IDLE) or garbage.
ev = RioRxEvent.ForControl(ch);
return true;
}
/// <summary>
/// Feed the first <paramref name="count"/> received bytes of
/// <paramref name="data"/>, invoking <paramref name="onEvent"/> for each
/// event produced, in order.
/// </summary>
public void Feed(byte[] data, int count, Action<RioRxEvent> onEvent)
{
if (data is null) throw new ArgumentNullException(nameof(data));
if (onEvent is null) throw new ArgumentNullException(nameof(onEvent));
for (int i = 0; i < count; i++)
{
if (Feed(data[i], out RioRxEvent ev))
onEvent(ev);
}
}
private RioRxEvent CompletePacket()
{
// _buffer = [command][payload…][checksum]; _count includes all of them.
int bodyLen = _count - 1; // command + payload (exclude checksum)
byte receivedChecksum = _buffer[bodyLen];
byte computed = RioChecksum.Compute(_buffer, 0, bodyLen);
bool checksumValid = computed == receivedChecksum;
var command = (RioCommand)_buffer[0];
var payload = new byte[bodyLen - 1]; // copy out; buffer is reused
Array.Copy(_buffer, 1, payload, 0, payload.Length);
var packet = new RioPacket(command, payload);
Reset();
return RioRxEvent.ForPacket(packet, checksumValid);
}
}