feat: add FIT CRC calculation

This commit is contained in:
Bastian Wagner
2026-08-15 10:21:09 +02:00
parent 49aba8efb4
commit 4599b2b71c
4 changed files with 29 additions and 0 deletions

0
app/fit/__init__.py Normal file
View File

18
app/fit/crc.py Normal file
View File

@@ -0,0 +1,18 @@
CRC_TABLE = (
0x0000, 0xCC01, 0xD801, 0x1400,
0xF001, 0x3C00, 0x2800, 0xE401,
0xA001, 0x6C00, 0x7800, 0xB401,
0x5000, 0x9C01, 0x8801, 0x4400,
)
def fit_crc(data: bytes | bytearray | memoryview) -> int:
crc = 0
for byte in data:
tmp = CRC_TABLE[crc & 0xF]
crc = (crc >> 4) & 0x0FFF
crc ^= tmp ^ CRC_TABLE[byte & 0xF]
tmp = CRC_TABLE[crc & 0xF]
crc = (crc >> 4) & 0x0FFF
crc ^= tmp ^ CRC_TABLE[(byte >> 4) & 0xF]
return crc & 0xFFFF

0
tests/fit/__init__.py Normal file
View File

11
tests/fit/test_crc.py Normal file
View File

@@ -0,0 +1,11 @@
from app.fit.crc import fit_crc
def test_empty_crc_is_zero() -> None:
assert fit_crc(b"") == 0
def test_crc_is_incremental_equivalent() -> None:
payload = b".FIT-device-metadata"
assert fit_crc(payload) == fit_crc(memoryview(payload))
assert 0 <= fit_crc(payload) <= 0xFFFF