Files
TuneBossPC/TuneBoss.Core/Protocol/ChecksumHelper.cs
T
2026-09-28 16:55:31 +08:00

74 lines
2.6 KiB
C#

namespace TuneBoss.Core.Protocol;
/// <summary>
/// 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.
/// </summary>
public static class ChecksumHelper
{
/// <summary>
/// Computes the DWord checksum over a byte span.
/// The span length must be a multiple of 4 (pad before calling if needed).
/// </summary>
public static uint GenChecksumDW(ReadOnlySpan<byte> 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
}
/// <summary>
/// Writes the 4-byte little-endian checksum into <paramref name="dest"/>.
/// </summary>
public static void WriteChecksumDW(ReadOnlySpan<byte> data, Span<byte> dest)
{
uint cs = GenChecksumDW(data);
dest[0] = (byte)(cs);
dest[1] = (byte)(cs >> 8);
dest[2] = (byte)(cs >> 16);
dest[3] = (byte)(cs >> 24);
}
/// <summary>
/// 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 ✓
/// </summary>
public static byte HeaderInverseSum(byte tlType, byte seqNum, byte dwCount)
=> unchecked((byte)(0xFF - (tlType + seqNum + dwCount)));
/// <summary>
/// Verifies an inbound packet's DWord checksum.
/// The last 4 bytes of <paramref name="payload"/> are the checksum;
/// the preceding bytes are the data.
/// </summary>
public static bool VerifyChecksumDW(ReadOnlySpan<byte> 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);
}
}