import network
from machine import Pin
from umqtt.simple import MQTTClient
from utime import sleep

# Konfigurasi WiFi
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# Konfigurasi MQTT
MQTT_CLIENT_ID = "mqttx_f38cbcb1"
MQTT_BROKER = "test.mosquitto.org"  # Alternatif broker
MQTT_TOPIC = "/UNI193/Dian_Kartika_Putri/aktuasi_led"

# Inisialisasi LED
led = Pin(15, Pin.OUT)

# Fungsi untuk menghubungkan ke WiFi
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)

    print("Menghubungkan ke WiFi...", end="")
    while not wlan.isconnected():
        sleep(1)
        print(".", end="")
    print("\nTerhubung ke WiFi")
    print("IP Address:", wlan.ifconfig()[0])

# Fungsi callback untuk pesan MQTT
def mqtt_callback(topic, msg):
    print(f"DEBUG: Pesan diterima - Topic: {topic.decode()}, Message: {msg.decode()}")
    if msg.decode().strip() == "ON":
        led.on()
        print("LED menyala")
    elif msg.decode().strip() == "OFF":
        led.off()
        print("LED mati")
    else:
        print(f"Pesan tidak dikenali: {msg.decode()}")

# Fungsi utama
def main():
    # Hubungkan ke WiFi
    connect_wifi()

    # Inisialisasi MQTT Client
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
    client.set_callback(mqtt_callback)

    # Hubungkan ke broker MQTT
    print("Menghubungkan ke broker MQTT...")
    try:
        client.connect()
        print("Terhubung ke broker MQTT")
    except Exception as e:
        print(f"Gagal terhubung ke broker MQTT: {e}")
        return

    # Subscribe ke topic
    try:
        client.subscribe(MQTT_TOPIC)
        print(f"Berlangganan ke topic: {MQTT_TOPIC}")
    except Exception as e:
        print(f"Gagal subscribe ke topic: {e}")
        return

    # Loop utama
    try:
        while True:
            try:
                client.check_msg()
            except OSError as e:
                print(f"Kesalahan MQTT: {e}. Mencoba menyambung ulang...")
                try:
                    client.connect()
                    client.subscribe(MQTT_TOPIC)
                    print("Berhasil menyambung ulang ke broker MQTT")
                except Exception as reconnect_error:
                    print(f"Gagal menyambung ulang ke broker MQTT: {reconnect_error}")
                    break
            sleep(1)
    except KeyboardInterrupt:
        print("Program dihentikan")
    finally:
        client.disconnect()
        print("Terputus dari broker MQTT")

# Jalankan program
if __name__ == "__main__":
    main()