crc16_ccitt_nibble_ref.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/env python3
  2. """Independent CRC-16/CCITT-FALSE using a frozen nibble table.
  3. This table is not generated from tools/generate_project.py or
  4. prod2u_simple_protocol.py. Used to cross-check golden vectors.
  5. """
  6. from __future__ import annotations
  7. # High-nibble table for poly 0x1021, init applied by the caller loop.
  8. _NIBBLE = (
  9. 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
  10. 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
  11. )
  12. def crc16_ccitt_false_nibble(data: bytes | bytearray) -> int:
  13. crc = 0xFFFF
  14. for value in data:
  15. crc ^= (value & 0xFF) << 8
  16. crc = ((crc << 4) & 0xFFFF) ^ _NIBBLE[(crc >> 12) & 0x0F]
  17. crc = ((crc << 4) & 0xFFFF) ^ _NIBBLE[(crc >> 12) & 0x0F]
  18. return crc
  19. def frame_hex(frame_type: int, payload: bytes) -> str:
  20. body = bytes((frame_type, len(payload))) + payload
  21. crc = crc16_ccitt_false_nibble(body)
  22. return (b"\xA5\x5A" + body + crc.to_bytes(2, "little")).hex().upper()
  23. SET_ALL_6400_ALL_ZERO = "A55A0120" + ("00" * 32) + "0D8C"
  24. GET_TEMPERATURE = "A55A02006D7B"