"""Part 12, step 2: answer ID and CAP too. Needs osdp.py."""

from machine import Pin, UART, unique_id
import time
import osdp

ADDRESS = 1
IDENTITY = bytes([0x00, 0x00, 0x00, 1, 1]) + unique_id()[-4:] + bytes([0, 1, 0])
CAPABILITIES = bytes([
    3, 1, 0,
    4, 4, 1,
    5, 2, 1,
    6, 1, 1,
    8, 1, 0,
    10, 128, 0,
])
UNKNOWN_COMMAND = bytes([3])

REPLIES = {
    osdp.POLL: (osdp.ACK, b""),
    osdp.ID: (osdp.PDID, IDENTITY),
    osdp.CAP: (osdp.PDCAP, CAPABILITIES),
}

uart = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))
transmit_enable = Pin(2, Pin.OUT, value=0)

def send(frame):
    transmit_enable.value(1)
    uart.write(frame)
    uart.flush()
    transmit_enable.value(0)

def answer(command):
    return REPLIES.get(command.code, (osdp.NAK, UNKNOWN_COMMAND))

buffer = b""
while True:
    if uart.any():
        buffer += uart.read()
    command, buffer = osdp.parse(buffer)
    if command is not None and command.address == ADDRESS:
        code, data = answer(command)
        send(osdp.reply(ADDRESS, command.sequence, code, data))
        print("command", hex(command.code), "-> reply", hex(code))
    time.sleep_ms(2)
