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

# MQTT Server Parameters
MQTT_CLIENT_ID = "UNI525OktaviaLisaNurhalizah"
MQTT_BROKER    = "broker.emqx.io"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_DATA = "topic/UNI525/BismillahBerkah/data_sensor"
MQTT_TOPIC_LED  = "topic/UNI525/BismillahBerkah/aktuasi_led"

sensor1 = dht.DHT22(Pin(15))
sensor2 = dht.DHT22(Pin(2))
led = Pin(13, Pin.OUT)
led.off()

# WiFi Connection
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.5)
print(" Connected!")

# MQTT Callback
def mqtt_callback(topic, msg):
    print(f"Received message on {topic.decode()}: {msg.decode()}")
    if topic.decode() == MQTT_TOPIC_LED:
        command = msg.decode().strip().upper()
        if command == "ON":
            led.on()
            print("LED turned ON")
        elif command == "OFF":
            led.off()
            print("LED turned OFF")
        else:
            print("Unknown command received")

# MQTT Server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(MQTT_TOPIC_LED)
print("Connected and subscribed to LED topic!")

# Periodic sensor data publishing
last_sensor_time = 0
sensor_interval = 5

while True:
    client.check_msg()

    if time.time() - last_sensor_time >= sensor_interval:
        print("Measuring weather conditions... ", end="")
        sensor1.measure()
        sensor2.measure()
        message = ujson.dumps({
            "temp1": sensor1.temperature(),
            "humidity1": sensor1.humidity(),
            "temp2": sensor2.temperature(),
            "humidity2": sensor2.humidity(),
        })
        print(f"Reporting to MQTT topic {MQTT_TOPIC_DATA}: {message}")
        client.publish(MQTT_TOPIC_DATA, message)
        last_sensor_time = time.time()

    time.sleep(5)