import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "demoKARI"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "/UNI053/KARI/data_sensor"
led = Pin(12, Pin.OUT)
def connect_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def mqtt_callback(topic, msg):
print(f"Message received on topic {topic.decode()}: {msg.decode()}")
if msg.decode() == "on":
led.value(1) # Nyalakan LED
print("Lampu menyala")
elif msg.decode() == "off":
led.value(0) # Matikan LED
print("Lampu mati")
def connect_mqtt():
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(MQTT_TOPIC) # Subscribe ke topik
print("Connected and subscribed to topic!")
return client
# Main Program
connect_wifi()
client = connect_mqtt()
while True:
client.check_msg() # Periksa pesan masuk dari MQTT broker
time.sleep(1)