namespace TuneBoss.Core.Protocol; /// /// Checksum helpers for the TuneBoss BLE packet protocol. /// /// genCheckSumDW: accumulates payload as little-endian uint32 DWords, /// sums them (wrapping uint32), then returns the bitwise inverse (~sum). /// Verified against debug log 17-Mar-2026. /// public static class ChecksumHelper { /// /// Computes the DWord checksum over a byte span. /// The span length must be a multiple of 4 (pad before calling if needed). /// public static uint GenChecksumDW(ReadOnlySpan data) { if (data.Length % 4 != 0) throw new ArgumentException("Data length must be a multiple of 4.", nameof(data)); uint cumResult = 0; for (int i = 0; i < data.Length; i += 4) { uint dword = data[i] | ((uint)data[i + 1] << 8) | ((uint)data[i + 2] << 16) | ((uint)data[i + 3] << 24); cumResult += dword; // wrapping uint32 addition } return ~cumResult; // bitwise inverse } /// /// Writes the 4-byte little-endian checksum into . /// public static void WriteChecksumDW(ReadOnlySpan data, Span dest) { uint cs = GenChecksumDW(data); dest[0] = (byte)(cs); dest[1] = (byte)(cs >> 8); dest[2] = (byte)(cs >> 16); dest[3] = (byte)(cs >> 24); } /// /// Computes the single-byte header inverse sum. /// sum = TL_type + seqNum + dwCount; result = 0xFF - sum (byte wrap). /// Verified: TL=02 seq=01 dw=02 → sum=05 → invSum=FA ✓ /// public static byte HeaderInverseSum(byte tlType, byte seqNum, byte dwCount) => unchecked((byte)(0xFF - (tlType + seqNum + dwCount))); /// /// Verifies an inbound packet's DWord checksum. /// The last 4 bytes of are the checksum; /// the preceding bytes are the data. /// public static bool VerifyChecksumDW(ReadOnlySpan payload) { if (payload.Length < 8 || payload.Length % 4 != 0) return false; int dataLen = payload.Length - 4; var data = payload.Slice(0, dataLen); var expected = payload.Slice(dataLen, 4); uint computed = GenChecksumDW(data); return expected[0] == (byte)(computed) && expected[1] == (byte)(computed >> 8) && expected[2] == (byte)(computed >> 16) && expected[3] == (byte)(computed >> 24); } }