from machine import Pin
from time import sleep
from umqtt.simple import MQTTClient
import network
# WiFi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# MQTT Broker details
MQTT_BROKER = "rail.kls.ac.th"
MQTT_TOPIC = "railtest007"
CLIENT_ID = "esp32_wokwi_client" # Unique client ID
# LED Pin (GPIO26)
LED_PIN = 26
led = Pin(LED_PIN, Pin.OUT)
# --- WiFi Connection ---
def connect_wifi():
print("Connecting to WiFi...", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
print(".", end="")
sleep(0.5)
print("\nWiFi Connected!")
print("IP Address:", sta_if.ifconfig()[0])
# --- MQTT Callback Function ---
def mqtt_callback(topic, msg):
print(f"Received MQTT message: Topic='{topic.decode()}', Message='{msg.decode()}'")
if msg.decode() == "true":
led.value(1) # Turn LED ON
print("LED ON")
elif msg.decode() == "false":
led.value(0) # Turn LED OFF
print("LED OFF")
# --- Main Program ---
def main():
connect_wifi()
# Initialize MQTT Client
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.set_callback(mqtt_callback)
client.connect()
print(f"Connected to MQTT Broker: {MQTT_BROKER}")
# Subscribe to the topic
client.subscribe(MQTT_TOPIC)
print(f"Subscribed to topic: {MQTT_TOPIC}")
try:
while True:
client.check_msg() # Check for new MQTT messages
sleep(1)
except Exception as e:
print(f"An error occurred: {e}")
finally:
client.disconnect()
print("Disconnected from MQTT Broker.")
if __name__ == "__main__":
main()