import time
import urequests as requests
import network


import machine

# Define RGB LED cathode pins
red = machine.Pin(4, machine.Pin.OUT)

def do_connect():
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect("Wokwi-GUEST", '')
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
    
do_connect()
# Function to set the color of the common anode RGB LED
def ledON():
    red.on()

def ledOFF():
    red.off()

def get_button_state():
    response = requests.get('http://arifanedian.pythonanywhere.com/api/get-led-state')
    data = response.json()
    return data

# Initialize the previous state to an initial value
prev_button_state = {"state": None}

while True:
    try:
        button_state = get_button_state()
        if button_state != prev_button_state:
            print(f'Button state: {button_state}')
            prev_button_state = button_state
            index = prev_button_state['led_state']
            print(type(index))
            if index == 0:
                ledOFF()
            else:
                ledON()

        time.sleep(1)  # Check the state every 1 second
    except KeyboardInterrupt:
        break

# Disconnect from Wi-Fi when done
network.WLAN(network.STA_IF).disconnect()


# from machine import Pin
# from time import sleep

# # ESP32 GPIO 26
# relay = Pin(4, Pin.OUT)

# # ESP8266 GPIO 5
# #relay = Pin(5, Pin.OUT)

# while True:
#   # RELAY ON
#   relay.value(1)
#   sleep(2) # should be greater than 2 sec 
#   # RELAY OFF
#   relay.value(0)
#   sleep(2) # should be greater than 2 sec
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
NOCOMNCVCCGNDINLED1PWRRelay Module
relay1:VCC
relay1:GND
relay1:IN
relay1:NC
relay1:COM
relay1:NO
led1:A
led1:C