| 1234567891011121314151617181920212223242526 |
- """Independent CRC-16/CCITT-FALSE reference (nibble table, not bit-serial)."""
- from __future__ import annotations
- from typing import Iterable
- # High-nibble table for poly 0x1021, init 0xFFFF, no reflect, xorout 0.
- _NIBBLE = (
- 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
- 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
- )
- def crc16_ccitt_false_table(data: bytes | bytearray | Iterable[int]) -> int:
- crc = 0xFFFF
- for raw in data:
- value = int(raw) & 0xFF
- crc = ((crc << 4) & 0xFFFF) ^ _NIBBLE[((crc >> 12) ^ (value >> 4)) & 0x0F]
- crc = ((crc << 4) & 0xFFFF) ^ _NIBBLE[((crc >> 12) ^ value) & 0x0F]
- return crc
- def frame_bytes(frame_type: int, payload: bytes) -> bytes:
- body = bytes((frame_type & 0xFF, len(payload) & 0xFF)) + payload
- crc = crc16_ccitt_false_table(body)
- return b"\xA5\x5A" + body + crc.to_bytes(2, "little")
|