namespace TuneBoss.Core.Protocol; /// /// 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) /// public static class PacketBuilder { private static readonly byte[] Preamble = { 0xFF, 0x00, 0xFF, 0x00 }; // ── Outbound ───────────────────────────────────────────────────────────── /// /// Builds a complete outbound packet. /// /// Transport layer type (TL_NONPOSTED, TL_STREAMING etc.) /// Sequence number. Use 0 for streaming commands. /// Command payload. Will be zero-padded to DWord boundary. public static byte[] Build(byte tlType, byte seqNum, ReadOnlySpan 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; } /// /// Convenience: builds a TL_NONPOSTED packet with a single command byte /// and optional parameters, auto-padded. /// public static byte[] BuildNonPosted(byte seqNum, byte command, ReadOnlySpan parameters = default) { byte[] payload = new byte[1 + parameters.Length]; payload[0] = command; parameters.CopyTo(payload.AsSpan(1)); return Build(Commands.TL_NONPOSTED, seqNum, payload); } /// /// Convenience: builds a TL_STREAMING packet (always seq=0). /// public static byte[] BuildStreaming(byte command) { return Build(Commands.TL_STREAMING, seqNum: 0, data: new[] { command }); } /// /// Builds an APP_MON_START (0x71) streaming packet. /// public static byte[] BuildMonStart() => BuildStreaming(Commands.APP_MON_START); /// /// Builds an APP_MON_STOP (0x72) streaming packet. /// public static byte[] BuildMonStop() => BuildStreaming(Commands.APP_MON_STOP); /// /// Builds an APP_READ_INFO (0x37) request. /// Data = [0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] — 2 DWords. /// Verified: log line 5–7. /// public static byte[] BuildReadInfo(byte seqNum) => BuildNonPosted(seqNum, Commands.APP_READ_INFO, new byte[7]); // ── Inbound ────────────────────────────────────────────────────────────── /// /// Result of parsing an inbound packet. /// 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(); // Full payload excl. checksum public bool ChecksumValid { get; init; } } /// /// Parses a raw inbound frame received over BLE. /// Returns null if the preamble is missing or the frame is too short. /// public static InboundPacket? Parse(ReadOnlySpan 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 ────────────────────────────────────────────────── /// /// Returns true if a raw frame is a diagnostics streaming packet (0x70). /// Fast check without full parse — used in the hot receive path. /// public static bool IsDiagnosticsFrame(ReadOnlySpan frame) => frame.Length >= 9 && frame[4] == Commands.TL_STREAMING && frame[8] == Commands.APP_MONITORING; }