import network
import time
from machine import Pin
import ujson  # Mengimpor modul JSON untuk parsing pesan
from umqtt.simple import MQTTClient

# MQTT Server Parameters
MQTT_CLIENT_ID = "M.Fakhri A"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "HSC124/MuhammadFakhriAndriza/LED"

# LED Setup (misalnya LED di GPIO 4)
led = Pin(4, Pin.OUT)

# WIFI Connection
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')  # Sesuaikan dengan SSID dan password Wi-Fi Anda
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!")

        # Function to handle received messages for LED control
        def on_message(topic, msg):
            print(f"Received message on {topic}: {msg}")
                
                    # Parsing JSON message
                        try:
                                message = ujson.loads(msg)  # Parse JSON
                                        command = message.get("msg", "")  # Mendapatkan nilai dari key 'msg'
                                                
                                                        if command == "on":
                                                                    print("Turning LED ON")
                                                                                led.on()  # Menyalakan LED
                                                                                        elif command == "off":
                                                                                                    print("Turning LED OFF")
                                                                                                                led.off()  # Mematikan LED
                                                                                                                        else:
                                                                                                                                    print("Unknown command in message")
                                                                                                                                        
                                                                                                                                            except Exception as e:
                                                                                                                                                    print(f"Failed to parse message: {e}")

                                                                                                                                                    # Set the callback function for the subscribed topic
                                                                                                                                                    client.set_callback(on_message)

                                                                                                                                                    # Subscribe to the topic where the command to control LED will be sent
                                                                                                                                                    client.subscribe(MQTT_TOPIC)
                                                                                                                                                    print(f"Subscribed to {MQTT_TOPIC}")

                                                                                                                                                    # Main loop to check for new messages and control LED
                                                                                                                                                    while True:
                                                                                                                                                        print("Waiting for messages...")
                                                                                                                                                            # Check if there are new messages on the subscribed topic
                                                                                                                                                                client.check_msg()

                                                                                                                                                                    time.sleep(1)  # Add delay to avoid busy loop