import network
import time
import ujson
from machine import Pin
from umqtt.simple import MQTTClient
# Inisialisasi LED
led = Pin(15, Pin.OUT)
# Konfigurasi WiFi
WIFI_SSID = "Wokwi-GUEST" # Ganti dengan SSID WiFi Anda
WIFI_PASSWORD = ""
# Konfigurasi MQTT
MQTT_BROKER = "broker.emqx.io" # Broker MQTT publik
MQTT_TOPIC = "/BRAINWAVE/renaldi_endrawan/aktuasi_led" # Topik untuk subscribe
# Fungsi untuk koneksi ke WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to WiFi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nConnected to WiFi:", wlan.ifconfig())
# Callback untuk menerima pesan MQTT
def on_message(topic, msg):
print(f"Message received on topic {topic}: {msg}")
try:
# Parse pesan JSON
data = ujson.loads(msg)
if data.get("msg") == "on":
led.on()
print("LED is ON")
elif data.get("msg") == "off":
led.off()
print("LED is OFF")
except Exception as e:
print("Error processing message:", e)
# Fungsi utama
def main():
connect_wifi()
# Koneksi ke MQTT broker
client = MQTTClient("ESP32", MQTT_BROKER)
client.set_callback(on_message)
client.connect()
print("Connected to MQTT broker")
# Subscribe ke topik
client.subscribe(MQTT_TOPIC)
print(f"Subscribed to topic: {MQTT_TOPIC}")
try:
while True:
# Tunggu pesan MQTT
client.check_msg()
time.sleep(0.1)
except KeyboardInterrupt:
print("Disconnected")
client.disconnect()
# Jalankan program
if __name__ == "__main__":
main()