import network
import time
import sys
from machine import Pin
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "zarh777c"
MQTT_BROKER = " mqtt.flespi.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "/guru/reki/aktuasi_led"
led = Pin(4, Pin.OUT) # Pin 4 digunakan untuk LED
# WIFI Connection
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!")
# MQTT Server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected to MQTT server!")
# Callback function LED
def callback(topic, msg):
print(f"Message received on topic {topic.decode()}: '{msg.decode()}'")
try:
# Mendecode pesan JSON, contohnya {"command" : "on"}
raw_msg = ujson.loads(msg.decode("utf-8"))
print(f"Received JSON message: {raw_msg}")
# Jika pesan memiliki kunci 'command', nilai dari kunci diambil
# dan diubah menjadi huruf kecil dan dihapus spasi yang tidak diperlukan
if "command" in raw_msg:
command = raw_msg["command"].strip().lower()
else:
print("No 'command' key in the received message!")
return
# Jika pesan hanya string sederhana seperti "on" atau "off", fungsi akan langsung mengambil isi pesan sebagai string
except ValueError:
command = msg.decode("utf-8").strip().lower()
# Kontrol LED berdasarkan perintah
if command == "on":
led.value(1)
print("LED Turned ON")
elif command == "off":
led.value(0)
else:
print(f"Unknown command: '{command}'")
# CALLBACK
try:
# Subscribe to the topic
client.set_callback(callback)
client.subscribe(MQTT_TOPIC)
print(f"Subscribed to topic: {MQTT_TOPIC}")
# Loop to keep the connection alive and listen for messages
while True:
client.check_msg() # Check for incoming messages
time.sleep(1)
except Exception as e:
print("Failed to connect to MQTT broker:", e)
sys.exit()