# STUDENT BUZZER  (put this same program on every student micro:bit)
#
# Number : the first time it shows 0. Press A to add 1 or B to add 10,
#          then wait 3 seconds. Pressing A once makes it buzzer 1.
#          To change it later, hold A and B together while buzzers are closed.
# Buzz   : press A, or an arcade button wired between pin 1 and GND.
#
# Display
#   small dot    waiting for the next question (press A to see your number)
#   big square   buzzers open: buzz now!
#   diamond      sending your buzz
#   tick         you buzzed first
#   X            someone else was first
#   sad face     answered wrong, out until the next question
#   ?            can't hear the receiver micro:bit

from microbit import *
import radio
import random

GROUP = 42          # must match receiver.py
MOST = 30           # highest buzzer number
SAVE = "number.txt"

radio.config(group=GROUP, power=6, length=120, queue=6)
radio.on()
try:
    pin1.set_pull(pin1.PULL_UP)     # for the optional arcade button
except AttributeError:
    pass                            # older micro:bits: use button A

PICTURES = {
    "waiting": Image("00000:00000:00500:00000:00000"),
    "open": Image.SQUARE,
    "sending": Image.DIAMOND_SMALL,
    "won": Image.YES,
    "lost": Image.NO,
    "out": Image.SAD,
    "alone": "?",
}


def load_number():
    try:
        with open(SAVE) as f:
            n = int(f.read())
        return n if 1 <= n <= MOST else None
    except (OSError, ValueError):
        return None


def show_number(n):
    if n < 10:
        display.show(str(n))
    else:
        display.scroll(str(n), delay=90, wait=False, loop=True)


def choose_number(n, first_time):
    while button_a.is_pressed() or button_b.is_pressed():
        sleep(20)
    button_a.was_pressed()      # forget the presses that got us here
    button_b.was_pressed()
    show_number(n)
    touched = None if first_time else running_time()
    while touched is None or running_time() - touched < 3000:
        step = 0
        if button_a.was_pressed():
            step = 1
        if button_b.was_pressed():
            step = 10
        if step:
            n = (n - 1 + step) % MOST + 1
            show_number(n)
            touched = running_time()
        sleep(20)
    with open(SAVE, "w") as f:
        f.write(str(n))
    display.show(Image.YES)
    sleep(600)
    return n


number = load_number()
if number is None:
    number = choose_number(0, True)
else:
    show_number(number)
    sleep(1500)

state = "alone"
shown = None
last_heard = -10000
give_up = 0
last_send = 0
next_hello = 0
number_until = 0
pin_was = 1


def handle(message):
    global state, last_heard
    if message == "W":
        state = "waiting"
    elif message.startswith("O:"):          # open; lists who is out
        if str(number) in message[2:].split(","):
            state = "out"
        elif state != "sending":
            state = "open"
    elif message.startswith("L:"):          # locked; says who won
        state = "won" if message[2:] == str(number) else "lost"
    else:
        return                              # another buzzer talking
    last_heard = running_time()


while True:
    while True:
        try:
            message = radio.receive()
        except ValueError:
            message = None
        if not message:
            break
        handle(message)

    now = running_time()

    if button_a.is_pressed() and button_b.is_pressed() and state in ("waiting", "alone"):
        number = choose_number(number, False)
        shown = None
        continue

    pin_now = pin1.read_digital()
    pressed = button_a.was_pressed() or (pin_was == 1 and pin_now == 0)
    pin_was = pin_now

    if pressed and state == "open":
        state = "sending"
        give_up = now + 1000
        last_send = -1000
    elif pressed and state == "waiting":
        number_until = now + 1500

    # radio messages can be lost, so repeat until the receiver answers
    if state == "sending":
        if now > give_up:
            state = "open"
        elif now - last_send >= 30 + random.randint(0, 15):
            radio.send("B%d" % number)
            last_send = now

    # tell the receiver this buzzer is switched on
    if now >= next_hello and state != "sending":
        radio.send("H%d" % number)
        next_hello = now + 2500 + random.randint(0, 1000)

    if now - last_heard > 2000 and state != "sending":
        state = "alone"

    wanted = "number" if state == "waiting" and now < number_until else state
    if wanted != shown:
        shown = wanted
        if wanted == "number":
            show_number(number)
        else:
            display.show(PICTURES[wanted])

    sleep(5)
