"""Part 12, step 1: answer ACK to POLL. Needs osdp.py. Run controller.py on the Mac."""

from machine import Pin, UART
import time
import osdp

ADDRESS = 1

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):
    if command.code == osdp.POLL:
        return osdp.ACK, b""
    return osdp.NAK, bytes([3])

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)
