"""Opens and locks the door (address 2) over OSDP, in turn, without the reader.

The door is held open for CYCLE_S seconds, then locked for CYCLE_S seconds,
and so on. In between, the door is polled and everything it reports is printed.

python3 door_cycle.py [port]

Needs osdp.py and controller.py from the reader, like door_controller.py.
"""

import itertools
import time

from door_controller import DOOR, LABELS, at_door, on_door_report
import osdp
from controller import POLL_INTERVAL_S, PORT, open_port, sequence_numbers, talk

CYCLE_S = 5
ORDERS = [(osdp.OUTPUT_ON, "cycle: open"), (osdp.OUTPUT_OFF, "cycle: locked")]


def main():
    port = open_port(PORT)
    sequences = sequence_numbers()

    def ask(code, data=b""):
        return talk(port, next(sequences), code, data, DOOR, LABELS[DOOR])

    ask(osdp.ID, b"\x00")
    for control, message in itertools.cycle(ORDERS):
        for _, code, data in at_door(control, message):
            ask(code, data)
        next_order_at = time.monotonic() + CYCLE_S
        while time.monotonic() < next_order_at:
            answer = ask(osdp.POLL)
            if answer is not None:
                on_door_report(answer)
            time.sleep(POLL_INTERVAL_S)


if __name__ == "__main__":
    main()
