# Sección 1 - Importación de librerías
import network
import time
from machine import Pin, ADC
import urequests as requests

# Sección 2 - Configuración de Adafruit IO
AIO_USERNAME = "kenney27"
AIO_KEY = "aio_rCzj69oIt5GIStso5xTUmSPniS1R"
nombre_feed_1 = "humedad"

# Sección 3 - Función para enviar datos a Adafruit IO
def enviar_valor(valor):
    url = f"https://io.adafruit.com/api/v2/{AIO_USERNAME}/feeds/{nombre_feed_1}/data"
    headers = {"X-AIO-Key": AIO_KEY, "Content-Type": "application/json"}
    data = {"value": valor}
    response = requests.post(url, json=data, headers=headers)
    response.close()

# Sección 4 - Configuración del sensor
sensor = ADC(Pin(34))
sensor.atten(ADC.ATTN_11DB)  # Mantener por compatibilidad
sensor.width(ADC.WIDTH_12BIT)

# Valor máximo correspondiente a 1.2V
VALOR_MAX_1V2 = int((1.2 / 3.3) * 4095)  # ≈ 1489

# Sección 5 - Conexión a WiFi
red = network.WLAN(network.STA_IF)
red.active(True)
red.connect('Wokwi-GUEST', '')  # Cambia si es necesario

print("Conectando", end="")
while not red.isconnected():
    print('.', end="")
    time.sleep(0.1)
print('\nConectado a la red')

# Sección 6 - Bucle principal
while True:
    try:
        valor_adc = sensor.read()

        # Limita el valor máximo a 1.2V por seguridad
        if valor_adc > VALOR_MAX_1V2:
            valor_adc = VALOR_MAX_1V2

        # Invertir la lectura: más humedad = menos voltaje
        humedad_percent = 100 - ((valor_adc / VALOR_MAX_1V2) * 100)
        humedad_percent = round(humedad_percent, 1)

        print(f"Humedad es: {humedad_percent} %")

        enviar_valor(humedad_percent)
        time.sleep(1)

    except Exception as e:
        print("Error:", e)
        time.sleep(1)