#!/usr/bin/env python3
"""Local calculations only: no serial, MQTT, HTTP or device access."""
import base64


def crc16(data):
    crc = 0xffff
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = (crc >> 1) ^ (0xa001 if crc & 1 else 0)
    return crc


def check():
    frames = [
        '01 03 00 00 00 08 44 0C',
        '01 04 00 00 00 06 70 08',
        '01 10 00 00 00 08 10 39 30 61 62 63 64 65 66 31 32 33 34 35 36 37 38 7F 5D',
        '01 10 00 00 00 08 C1 CF',
        '01 01 00 03 01 02 03 1A F4',
    ]
    for frame in frames:
        raw = bytes.fromhex(frame)
        assert crc16(raw[:-2]) == int.from_bytes(raw[-2:], 'little'), frame
        print('CRC OK:', frame)
    assert base64.b64encode(bytes.fromhex('010203')).decode() == 'AQID'
    assert base64.b64decode('MTIz', validate=True) == bytes.fromhex('313233')
    eui = bytes.fromhex('1122334455667788')
    assert base64.b64encode(eui).decode() == 'ESIzRFVmd4g='
    for idx in range(6):
        assert 12 - idx in range(7, 13)
    assert round(505.3 * 1000000) == 505300000
    print('Base64 / EUI / MHz / SF mapping OK. No device was contacted.')


if __name__ == '__main__':
    check()
