import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient

# Konfigurasi sensor
sensor_DHT22 = dht.DHT22(Pin(33))
led = Pin(2, Pin.OUT)

# Parameter WiFi
WiFi_SSID = 'Wokwi-GUEST'
WiFi_PASSWORD = ''

# Parameter MQTT Server
MQTT_CLIENT_ID = "demo"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
topic_DHT22 = "UNI453/adipriyantono/data_sensor/DHT22"
topic_LED = "UNI453/adipriyantono/aktuasi_led"

# Variabel global
client = None
old_data_dht = None

def connectWiFi():
    print("Connecting to WiFi", end="")
    wifi = network.WLAN(network.STA_IF)

    if not wifi.isconnected():
        wifi.active(True)
        wifi.disconnect()
        wifi.connect(WiFi_SSID, WiFi_PASSWORD)

        while not wifi.isconnected():
            print(".", end="")
            time.sleep(1)
    print("\nConnected to WiFi!")
    print("Network config:", wifi.ifconfig())
    print("")

def connectMQTT():
    global client
    try:
        print("Connecting to MQTT server... ", end="")
        client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
        client.set_callback(blink_led)
        client.connect()
        client.subscribe(topic_LED)
        print("Connected!")
        print("")
    except Exception as e:
        print("Failed to connect to MQTT server:", e)
        time.sleep(5)
        connectMQTT()  # Coba lagi hingga berhasil

def publishDHT():
    global old_data_dht
    try:
        sensor_DHT22.measure()
        data_dht = ujson.dumps({
            "temp1": sensor_DHT22.temperature(),
            "humidity1": sensor_DHT22.humidity(),
        })
        if data_dht != old_data_dht:
            print('Publish to MQTT Topic : {}'.format(topic_DHT22))
            print('Pesan Terkirim        : {}'.format(data_dht))
            print('')
            client.publish(topic_DHT22, data_dht)
            old_data_dht = data_dht

    except Exception as e:
        print("Error publishing DHT data:", e)

def blink_led(topic, msg):
    print(f"Message received on topic {topic.decode()}: {msg.decode()}")
    if msg.decode() == '1':
        led.on()
    else:
        led.off()

def main():
    connectWiFi()
    connectMQTT()

    while True:
        try:
            client.check_msg()  # Cek pesan MQTT masuk
            time.sleep(1)       # Berikan jeda 1 detik
            publishDHT()
        except Exception as e:
            print("Error in main loop:", e)
            connectMQTT()       # Rekoneksi MQTT jika diperlukan

# Menjalankan program utama
if __name__ == "__main__":
    main()