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

led = Pin(15, Pin.OUT)
dht_sensor = dht.DHT22(Pin(13))

MQTT_CLIENT_ID = "LuthfanLeD"
MQTT_BROKER = "broker.emqx.io"
MQTT_TOPIC = "/TimSinga/LuthfanHilmiBudiSaputra/aktuasi_led"

# ini untuk mengatur mau di berapa persen tingkat kelembaban supaya led menyalaa
HUMIDITY_THRESHOLD = 50

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
print("Connecting to WiFi", end="")
while not sta_if.isconnected():
    print(".", end="")
    sleep(0.1)
print("\nWiFi connected!")

print("Connecting to MQTT broker...")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
print("Connected to MQTT broker!")

def message_callback(topic, msg):
    print(f"Message received on topic {topic}: {msg}")
    if msg == b'on':
        led.on()
    elif msg == b'off':
        led.off()

client.set_callback(message_callback)
client.subscribe(MQTT_TOPIC)

while True:
    client.check_msg()

    try:
        dht_sensor.measure()
        temp = dht_sensor.temperature()
        hum = dht_sensor.humidity()

        if hum > HUMIDITY_THRESHOLD:
            led.on()
            led_status = "on"
            print("Kelembapan tinggi! LED menyala.")
        else:
            led.off()
            led_status = "off"
            print("Kelembapan normal. LED mati.")

        message = ujson.dumps({
            "temperature": temp,
            "humidity": hum,
            "led_status": led_status
        })
        client.publish(MQTT_TOPIC, message)
        print("Data sent:", message)

    except Exception as e:
        print("Failed to read DHT sensor or send data:", e)

    sleep(5)