from machine import Pin, Signal
LED_PIN = Signal(13, Pin.OUT, invert=False)
BUTTON_PIN = Pin(0, Pin.IN)

button_triggered = False
def button_handler(pin):
    global button_triggered
    button_triggered = True

# Turn off "ready" LED
LED_PIN.off()

# Read configuration from JSON file
with open('config.json') as fd:
    import ujson
    config = ujson.load(fd)

# Configure wireless networking
import network
wifi_host = network.WLAN(network.AP_IF)
wifi_host.active(False)

wifi_guest = network.WLAN(network.STA_IF)
wifi_guest.active(True)
if not wifi_guest.isconnected():
    wifi_guest.connect(config['wifi']['ssid'], config['wifi']['password'])
    while not wifi_guest.isconnected():
        pass
print(wifi_guest.ifconfig())

# Set up interrupt handler
BUTTON_PIN.irq(button_handler, Pin.IRQ_RISING)

# Turn on "ready" LED
LED_PIN.on()

# Enter main loop
import time
while True:
    if button_triggered:
        import urequests as requests

        LED_PIN.off()

        btn_id = config['buttonId']
        endpoint = 'http://192.168.0.212:42069/rdp?id={0}'.format(btn_id)
        res = requests.get(endpoint)
#       print(res.status_code)

        time.sleep(5)
        button_triggered = False
        LED_PIN.on()
    else:
        time.sleep(1)
