Initial Commit

This commit is contained in:
2026-09-28 16:55:31 +08:00
commit 14f8706198
128 changed files with 19860 additions and 0 deletions
+163
View File
@@ -0,0 +1,163 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// Builds and parses TuneBoss BLE packets over Nordic UART Service (NUS).
///
/// Outbound frame layout (verified against debug log 17-Mar-2026):
/// [0..3] FF 00 FF 00 Preamble
/// [4] TL_type Transport layer type (TL_POSTED / TL_NONPOSTED / TL_STREAMING)
/// [5] SeqNum Sequence number (0 for streaming)
/// [6] DwCount Payload size in DWords (4-byte units)
/// [7] InvSum 0xFF - (TL_type + SeqNum + DwCount)
/// [8..] Data Command payload (DwCount × 4 bytes)
/// [last4] DataChecksum ~sum of data DWords, little-endian uint32
///
/// Total frame size = 8 (header) + DwCount×4 (data) + 4 (checksum)
/// </summary>
public static class PacketBuilder
{
private static readonly byte[] Preamble = { 0xFF, 0x00, 0xFF, 0x00 };
// ── Outbound ─────────────────────────────────────────────────────────────
/// <summary>
/// Builds a complete outbound packet.
/// </summary>
/// <param name="tlType">Transport layer type (TL_NONPOSTED, TL_STREAMING etc.)</param>
/// <param name="seqNum">Sequence number. Use 0 for streaming commands.</param>
/// <param name="data">Command payload. Will be zero-padded to DWord boundary.</param>
public static byte[] Build(byte tlType, byte seqNum, ReadOnlySpan<byte> data)
{
// Pad data to DWord boundary
int paddedLen = (data.Length + 3) & ~3;
byte[] paddedData = new byte[paddedLen];
data.CopyTo(paddedData);
byte dwCount = (byte)(paddedLen / 4);
byte invSum = ChecksumHelper.HeaderInverseSum(tlType, seqNum, dwCount);
// Total: 4 preamble + 4 header + paddedData + 4 checksum
byte[] frame = new byte[8 + paddedLen + 4];
// Preamble
frame[0] = 0xFF; frame[1] = 0x00; frame[2] = 0xFF; frame[3] = 0x00;
// Header
frame[4] = tlType;
frame[5] = seqNum;
frame[6] = dwCount;
frame[7] = invSum;
// Data
paddedData.CopyTo(frame, 8);
// Checksum
ChecksumHelper.WriteChecksumDW(paddedData, frame.AsSpan(8 + paddedLen));
return frame;
}
/// <summary>
/// Convenience: builds a TL_NONPOSTED packet with a single command byte
/// and optional parameters, auto-padded.
/// </summary>
public static byte[] BuildNonPosted(byte seqNum, byte command, ReadOnlySpan<byte> parameters = default)
{
byte[] payload = new byte[1 + parameters.Length];
payload[0] = command;
parameters.CopyTo(payload.AsSpan(1));
return Build(Commands.TL_NONPOSTED, seqNum, payload);
}
/// <summary>
/// Convenience: builds a TL_STREAMING packet (always seq=0).
/// </summary>
public static byte[] BuildStreaming(byte command)
{
return Build(Commands.TL_STREAMING, seqNum: 0, data: new[] { command });
}
/// <summary>
/// Builds an APP_MON_START (0x71) streaming packet.
/// </summary>
public static byte[] BuildMonStart() => BuildStreaming(Commands.APP_MON_START);
/// <summary>
/// Builds an APP_MON_STOP (0x72) streaming packet.
/// </summary>
public static byte[] BuildMonStop() => BuildStreaming(Commands.APP_MON_STOP);
/// <summary>
/// Builds an APP_READ_INFO (0x37) request.
/// Data = [0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] — 2 DWords.
/// Verified: log line 5–7.
/// </summary>
public static byte[] BuildReadInfo(byte seqNum)
=> BuildNonPosted(seqNum, Commands.APP_READ_INFO, new byte[7]);
// ── Inbound ──────────────────────────────────────────────────────────────
/// <summary>
/// Result of parsing an inbound packet.
/// </summary>
public sealed class InboundPacket
{
public byte TlType { get; init; }
public byte SeqNum { get; init; }
public byte DwCount { get; init; }
public byte ResponseCode { get; init; } // First byte of payload (e.g. 0x51 = success)
public byte OriginalCmd { get; init; } // Second byte of payload (echoed command)
public byte[] Payload { get; init; } = Array.Empty<byte>(); // Full payload excl. checksum
public bool ChecksumValid { get; init; }
}
/// <summary>
/// Parses a raw inbound frame received over BLE.
/// Returns null if the preamble is missing or the frame is too short.
/// </summary>
public static InboundPacket? Parse(ReadOnlySpan<byte> frame)
{
// Minimum: 4 preamble + 4 header + 4 data + 4 checksum = 16 bytes
if (frame.Length < 16) return null;
// Validate preamble
if (frame[0] != 0xFF || frame[1] != 0x00 || frame[2] != 0xFF || frame[3] != 0x00)
return null;
byte tlType = frame[4];
byte seqNum = frame[5];
byte dwCount = frame[6];
// frame[7] = invSum (not validated here; add if needed)
int payloadLen = dwCount * 4;
int expectedLen = 8 + payloadLen + 4;
if (frame.Length < expectedLen) return null;
var payloadWithChecksum = frame.Slice(8, payloadLen + 4);
var payload = frame.Slice(8, payloadLen).ToArray();
bool csValid = ChecksumHelper.VerifyChecksumDW(payloadWithChecksum);
return new InboundPacket
{
TlType = tlType,
SeqNum = seqNum,
DwCount = dwCount,
ResponseCode = payload.Length > 0 ? payload[0] : (byte)0,
OriginalCmd = payload.Length > 1 ? payload[1] : (byte)0,
Payload = payload,
ChecksumValid = csValid,
};
}
// ── Diagnostics helpers ──────────────────────────────────────────────────
/// <summary>
/// Returns true if a raw frame is a diagnostics streaming packet (0x70).
/// Fast check without full parse — used in the hot receive path.
/// </summary>
public static bool IsDiagnosticsFrame(ReadOnlySpan<byte> frame)
=> frame.Length >= 9
&& frame[4] == Commands.TL_STREAMING
&& frame[8] == Commands.APP_MONITORING;
}