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

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

SSID = "Wokwi-GUEST"
PASSWORD = ""

MQTT_BROKER = "broker.emqx.io"
MQTT_CLIENT_ID = "espclient_ehfu1123"
MQTT_PUBLISH_TOPIC = "/ARUNIKA/helmirifqinasrullahsukaton/data_sensor"
MQTT_SUBSCRIBE_TOPIC = "/ARUNIKA/helmirifqinasrullahsukaton/aktuasi_led"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    print("Menghubungkan ke WiFi...")
    wlan.connect(SSID, PASSWORD)
    attempt = 0
    while not wlan.isconnected() and attempt < 10:
        attempt += 1
        time.sleep(1)
connect_wifi()

def on_message(topic, msg):
    print("Pesan diterima [" + topic.decode() + "]: " + msg.decode())
    command = msg.decode().lower()
    if command == "on":
        led.on()
    elif command == "off":
        led.off()


client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_SUBSCRIBE_TOPIC)
print("Terhubung ke broker MQTT dan berlangganan ke topik", MQTT_SUBSCRIBE_TOPIC)

try:
    while True:
        client.check_msg()
        dht_sensor.measure()
        temperature = dht_sensor.temperature()
        humidity = dht_sensor.humidity()
        payload = '{{"temperature": {}, "humidity": {}}}'.format(temperature, humidity)
        client.publish(MQTT_PUBLISH_TOPIC, payload)
        print("Mempublikasikan pesan:", payload)
        time.sleep(5) 
except KeyboardInterrupt:
    client.disconnect()
    print("Terputus dari broker MQTT")