#imports requeridos
import network
from machine import Pin
from time import sleep
from umqtt.simple import MQTTClient

#Definimos las propiedades de conexion con el servidor
MQTT_BROKER = "broker.hivemq.com"
MQTT_CLIENT_ID = ""
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "jdjc/led"
MQTT_PORT = 1883

#Funcion para conexion wifi
def conectar_wifi():
    print("Conectando...", end="")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect("Wokwi-GUEST","")
    while not sta_if.isconnected():
        print(".", end="")
        sleep(0.3)
    print("Wifi conectada!")

#funcion para encender y apagar led

def llegada_mensaje(topic, msg):
    print("mensaje: ", msg)
    if msg == b'1':
        led.value(1)
    elif msg==b'0':
        led.value(0)
    else:
        print("Mensaje no valido")



def subscribir():
    client=MQTTClient(MQTT_CLIENT_ID,MQTT_BROKER,port=MQTT_PORT,user=MQTT_USER, password=MQTT_PASSWORD,keepalive=0)

    client.set_callback(llegada_mensaje)
    client.connect()
    client.subscribe(MQTT_TOPIC)
    print("Conectando a: ", MQTT_BROKER, "en el topico",MQTT_TOPIC)
    return client

                        
led=Pin(4,Pin.OUT)
led.value(0)


conectar_wifi()


client=subscribir()

#Ciclo infinito
while True:
    client.wait_msg()
Loading
esp32-devkit-c-v4