# upload with `mpremote ben_cuelight.py :main.py` when connected with serial

import espnow
from machine import Pin, Timer
import network
import time
import ubinascii

# io0 = Pin(0, Pin.IN)
led = Pin(23, Pin.OUT)
led.value(1)
# turn off after 5s
Timer(0).init(mode=Timer.ONE_SHOT, period=5000, callback=lambda _: led.value(0))

print("Ben Cuelight Starting...")

# ESPNow https://docs.micropython.org/en/latest/library/espnow.html
sta = network.WLAN(network.WLAN.IF_STA)
sta.active(True)

def nice_mac(bys): return ubinascii.hexlify(bys, ":").decode()

my_mac = sta.config("mac")

MOS_X4_MAC = b"\x00\x70\x07\x7C\xDB\xC8"
ETH_01_MAC = b"\x14\x08\x08\x9E\xA1\x94"

print("MAC Address", nice_mac(my_mac))

e = espnow.ESPNow()
e.active(True)
print("ESPNow active")


def wait_change(pin):
    # wait for pin to change value
    # it needs to be stable for a continuous 20ms
    cur_value = pin.value()
    active = 0
    while active < 20:
        if pin.value() != cur_value:
            active += 1
        else:
            active = 0
        time.sleep(0.001)


def mos_x4():
    print("I am: MOS_X4")
    
    mos1 = Pin(16, Pin.OUT) # flash
    mos2 = Pin(17, Pin.OUT)
    mos3 = Pin(26, Pin.OUT)
    mos4 = Pin(27, Pin.OUT) # mute-state
    
    flash = mos1
    mute = mos4
    
    mute.value(0)
    flash.value(0)
    
    timer = Timer(1)
    
    while True:
        host, msg = e.recv()
        if msg and host == ETH_01_MAC:
            if msg[0] == 1:
                # on
                print("on")
                mute.value(1)
                timer.init(mode=Timer.PERIODIC, period=1000, callback=lambda _: flash.toggle())
            elif msg[0] == 0:
                # off
                print("off")
                mute.value(0)
                flash.value(0)
                timer.deinit()
            else:
                # ????
                print("??", msg, msg[0])
                ...
        
def eth_01():
    print("I am: ETH_01")
    
    peer = MOS_X4_MAC
    e.add_peer(peer)
    
    button = Pin(12, Pin.IN, Pin.PULL_UP)
                         
    remote_state_on = False
        
    while True:
        wait_change(button)
        if button.value() == 0:
            remote_state_on = not remote_state_on
            print("Setting remote to:", "on" if remote_state_on else "off")
            e.send(peer, bytes([1 if remote_state_on else 0]))
            

if my_mac == MOS_X4_MAC:
    mos_x4()
elif my_mac == ETH_01_MAC:
    eth_01()
else:
    print("Unknown device!!!", my_mac)
