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

# Parameter Server MQTT
MQTT_CLIENT_ID = "Assignment1_SIC6_by_Qlio_Amanda_Febriany"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_PUBLISH = "/Infinity_Minds/Qlio_Amanda_Febriany/data_sensor"
MQTT_TOPIC_SUBSCRIBE = "/Infinity_Minds/Qlio_Amanda_Febriany/aktuasi_led"

# Konfigurasi Pin
LED_PIN = 13
DHT1_PIN = 15
DHT2_PIN = 2

# Inisialisasi komponen
led = Pin(LED_PIN, Pin.OUT)
sensor1 = dht.DHT22(Pin(DHT1_PIN))
sensor2 = dht.DHT22(Pin(DHT2_PIN))

# Koneksi ke WiFi
print("Menghubungkan ke WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')  # Sesuaikan SSID dan password WiFi Anda
while not sta_if.isconnected():
    print(".", end="")
    time.sleep(0.1)
print(" Terhubung!")

# Koneksi ke server MQTT
print("Menghubungkan ke server MQTT... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Terhubung!")

# Fungsi callback untuk pesan MQTT
def mqtt_callback(topic, msg):
    print("Pesan diterima di topik {}: {}".format(topic.decode(), msg.decode()))
    if topic.decode() == MQTT_TOPIC_SUBSCRIBE:
        if msg.decode().lower() == "on":
            led.value(1)  # Menyalakan LED
            print("LED dinyalakan")
        elif msg.decode().lower() == "off":
            led.value(0)  # Mematikan LED
            print("LED dimatikan")

# Mengatur callback MQTT
client.set_callback(mqtt_callback)
client.subscribe(MQTT_TOPIC_SUBSCRIBE)
print("Subscribe ke topik:", MQTT_TOPIC_SUBSCRIBE)

# Loop utama
prev_weather = ""
while True:
    print("Mengukur kondisi cuaca... ", end="")
    sensor1.measure()
    sensor2.measure()
    pesan = ujson.dumps({
        "temp1": sensor1.temperature(),
        "humidity1": sensor1.humidity(),
        "temp2": sensor2.temperature(),
        "humidity2": sensor2.humidity(),
    })
    if pesan != prev_weather:
        print("Diperbarui!")
        print("Melaporkan ke topik MQTT {}: {}".format(MQTT_TOPIC_PUBLISH, pesan))
        # Mengirim pesan
        client.publish(MQTT_TOPIC_PUBLISH, pesan)
        prev_weather = pesan
    else:
        print("Tidak ada perubahan")

    # Memeriksa pesan masuk
    client.check_msg()

    time.sleep(1)