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

MQTT_CLIENT_ID = "AssignmentUNI"
MQTT_BROKER    = "broker.emqx.io"
MQTT_TOPIC_SENSOR  = "/UNI561/hairul_anam/data_sensor"
MQTT_TOPIC_LED_CONTROL = "/UNI561/hairul_anam/aktuasi_led"

led1 = machine.Pin(23, machine.Pin.OUT)
led2 = machine.Pin(19, machine.Pin.OUT)

dht_sensor = dht.DHT22(machine.Pin(12))

"""    
Contoh pesan untuk menghidupkan LED1:
{"led": "LED1", "action": "ON"}

Contoh pesan untuk mematikan LED2:
{"led": "LED2", "action": "OFF"}
"""

def control_led(topic, msg):
    try:
        data = ujson.loads(msg)
        led_status = data.get("led", "")
        action = data.get("action", "")

        if led_status == "LED1" and action == "ON":
            led1.on()
            print("LED1 On")
        elif led_status == "LED1" and action == "OFF":
            led1.off()
            print("LED1 Off")
        elif led_status == "LED2" and action == "ON":
            led2.on()
            print("LED2 On")
        elif led_status == "LED2" and action == "OFF":
            led2.off()
            print("LED2 Off")
    except Exception as e:
        print("Error decoding JSON:", e)

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

print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user='', password='')
client.set_callback(control_led)
client.connect()
client.subscribe(MQTT_TOPIC_LED_CONTROL)
print("Connected!")

def publish_sensor():
    dht_sensor.measure()
    temperature = dht_sensor.temperature()
    humidity = dht_sensor.humidity()

    msg = "Temp: {}, Humidity: {}".format(temperature, humidity)
    client.publish(MQTT_TOPIC_SENSOR, msg)

while True:
    publish_sensor()          # Publish sensor data
    client.check_msg()        # Check for incoming MQTT messages
    time.sleep(10)            # Delay between sensor readings