# Tactiverge Academy — companion code for "Designing a message protocol"
# Lesson: https://tactiverge.win/academy/embedded-systems/embedded-communication/designing-message-protocols/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import struct
import binascii

START = 0xAA
VERSION = 1
MSG_DISTANCE = 0x10

def checksum8(data):
    """Simple checksum: sum of all bytes, keeping only the low 8 bits."""
    return sum(data) & 0xFF

def crc16(data):
    """CRC-16/CCITT-FALSE from the standard library."""
    return binascii.crc_hqx(data, 0xFFFF)

def build_frame(msg_type, payload):
    body = bytes([VERSION, msg_type, len(payload)]) + payload
    return bytes([START]) + body + struct.pack("<H", crc16(body))

# Payload: distance in millimetres (uint16) and a timestamp in ms (uint32),
# both little-endian.
payload = struct.pack("<HI", 1234, 56789)
frame = build_frame(MSG_DISTANCE, payload)
print("frame:", frame.hex(" "))

# A swap of two payload bytes fools the simple sum, but not the CRC.
good = bytes([0x01, 0x02, 0x03])
swapped = bytes([0x02, 0x01, 0x03])
print("sum  :", hex(checksum8(good)), hex(checksum8(swapped)))
print("crc16:", hex(crc16(good)), hex(crc16(swapped)))
print("check value:", hex(crc16(b"123456789")))


# ── Example 2 ────────────────────────────────────────
MAX_PAYLOAD = 32

def parse_stream(stream):
    """Yield (msg_type, payload) for every valid frame found in a byte stream."""
    i = 0
    while i < len(stream):
        if stream[i] != START:
            i += 1                       # not a frame start: skip one byte
            continue
        if i + 4 > len(stream):
            break                        # header incomplete: wait for more bytes
        version, msg_type, length = stream[i + 1], stream[i + 2], stream[i + 3]
        end = i + 4 + length + 2
        if version != VERSION or length > MAX_PAYLOAD:
            i += 1                       # implausible header: resynchronise
            continue
        if end > len(stream):
            break
        body = stream[i + 1: i + 4 + length]
        (received,) = struct.unpack("<H", stream[end - 2: end])
        if crc16(body) == received:
            yield msg_type, body[3:]
            i = end
        else:
            print(f"bad CRC in frame at byte {i}, skipping")
            i += 1

a = build_frame(0x10, struct.pack("<HI", 1234, 56789))
b = bytearray(build_frame(0x10, struct.pack("<HI", 1240, 56889)))
b[5] ^= 0x04                             # flip one bit "in transit"
c = build_frame(0x10, struct.pack("<HI", 1251, 56989))
stream = bytes([0x37, 0xAA, 0x99]) + a + bytes(b) + c

for msg_type, payload in parse_stream(stream):
    mm, ms = struct.unpack("<HI", payload)
    print(f"type 0x{msg_type:02X}: {mm} mm at t = {ms} ms")
