import network
import time
from umqtt.simple import MQTTClient
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# MQTT Broker settings
MQTT_BROKER = "broker.emqx.io"
MQTT_PORT = 1883
MQTT_TOPIC = b"esp32/test"
# WiFi Connect
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
# Callback function (must be defined before use!)
def sub_cb(topic, msg):
print("Received message from topic:", topic.decode(), "->", msg.decode())
# Main
wifi_connect()
client = MQTTClient("esp32_sub", MQTT_BROKER, port=MQTT_PORT)
client.set_callback(sub_cb) # set callback first
client.connect()
client.subscribe(MQTT_TOPIC) # then subscribe
print("Subscribed to topic:", MQTT_TOPIC)
while True:
client.wait_msg() # blocking wait for new message