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

# MQTT Server Parameters
MQTT_CLIENT_ID = "ESP32_UNI392"
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC_PUB = "/UNI392/SITINURSALAMAH/data_sensor"  # Topik untuk publish sensor data
MQTT_TOPIC_SUB = "/UNI392/SITINURSALAMAH/aktuasi_led"  # Topik untuk subscribe aktuasi LED

# DHT22 Sensors
sensor1 = dht.DHT22(Pin(15))  # Sensor pertama di GPIO15
sensor2 = dht.DHT22(Pin(2))   # Sensor kedua di GPIO2

# LED Setup
led = Pin(14, Pin.OUT)  # LED di GPIO14 

# WiFi Credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# Connect to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
while not sta_if.isconnected():
    print(".", end="")
    time.sleep(0.1)
print(" Connected!")

# MQTT Callback for LED Control
def sub_cb(topic, msg):
    print(f"Received message on topic {topic.decode()}: {msg.decode()}")
    if topic.decode() == MQTT_TOPIC_SUB:
        if msg.decode().lower() == "on":
            led.on()  # Menyalakan LED
            print("LED is ON")
        elif msg.decode().lower() == "off":
            led.off()  # Mematikan LED
            print("LED is OFF")

# Connect to MQTT Broker
print("Connecting to MQTT broker... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_TOPIC_SUB)
print("Connected!")

# Publish Sensor Data
prev_weather = ""
def publish_sensor_data():
    global prev_weather
    try:
        sensor1.measure()
        sensor2.measure()
        message = ujson.dumps({
            "temp1": sensor1.temperature(),
            "humidity1": sensor1.humidity(),
            "temp2": sensor2.temperature(),
            "humidity2": sensor2.humidity(),
        })
        if message != prev_weather:
            print(f"Publishing to {MQTT_TOPIC_PUB}: {message}")
            client.publish(MQTT_TOPIC_PUB, message)
            prev_weather = message
        else:
            print("No new data to publish")
    except Exception as e:
        print(f"Error reading sensors: {e}")

# Main Loop
while True:
    client.check_msg()  
    publish_sensor_data()  
    time.sleep(5)