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

# MQTT_CLIENT_ID = "Assigment"
# MQTT_BROKER = "broker.emqx.io"
# MQTT_USER = "Damar"
# MQTT_PASSWORD = "Damar12345"
# PUBLISH_TOPIC = "/UNI069/DamarGalih/data_sensor"
# SUBSCRIBE_TOPIC = "/UNI069/DamarGalih/aktuasi_led"

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

# 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!")

# def on_message(topic, msg):
#     global publish_data
#     print("Message received:", topic, msg)
    
#     if topic.decode() == SUBSCRIBE_TOPIC:
#         try:
#             msg_data = ujson.loads(msg)
#             action = msg_data.get("msg")
            
#             if action == "ON":
#                 publish_data = {
#                     "temperature": 80,
#                     "humidity": 48
#                 }
#                 print("LED ON: Publishing temperature 80 and humidity 48")
#                 led.on()
                
#             elif action == "OFF":
#                 publish_data = {
#                     "temperature": 40,
#                     "humidity": 24
#                 }
#                 print("LED OFF: Publishing temperature 40 and humidity 24")
#                 led.off()
#             else:
#                 print("Invalid message:", msg_data)
#         except Exception as e:
#             print("Error parsing message:", e)

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

# prev_weather = ""  # To track previous sensor data
# publish_data = None

# while True:
#     try:
#         if publish_data:
#             # Publish data based on the current LED state
#             message = ujson.dumps(publish_data)

#             # Publish Sensor Data if There Is a Change
#             if message != prev_weather:
#                 print("Updated!")
#                 print("Publishing to topic {}: {}".format(PUBLISH_TOPIC, message))
#                 client.publish(PUBLISH_TOPIC, message)
#                 prev_weather = message  # Update prev_weather after publishing
#             else:
#                 print("No change")

#         # Check for incoming messages
#         client.check_msg()

#         # Wait for 5 seconds before publishing again
#         time.sleep(5)
#     except Exception as e:
#         print("Error:", e)
#         time.sleep(5)

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

MQTT_CLIENT_ID = "Assigment"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = "Damar"
MQTT_PASSWORD = "Damar12345"
PUBLISH_TOPIC = "/UNI069/DamarGalih/data_sensor"
SUBSCRIBE_TOPIC = "/UNI069/DamarGalih/aktuasi_led"

sensor = dht.DHT22(Pin(15))  # Pin yang digunakan untuk sensor
led = Pin(13, Pin.OUT)  # Pin untuk LED

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!")

def on_message(topic, msg):
    global led, temperature, humidity
    print("Message received:", topic, msg)
    
    if topic.decode() == SUBSCRIBE_TOPIC:
        try:
            msg_data = ujson.loads(msg)
            action = msg_data.get("msg")
            
            if action == "ON":
                print("LED ON")
                led.on()
                # Simulate sensor update when LED is ON
                temperature = 48
                humidity = 80
                # Send updated values to MQTT
                publish_data = {
                    "temperature": temperature,
                    "humidity": humidity
                }
                message = ujson.dumps(publish_data)
                print("Publishing:", message)
                client.publish(PUBLISH_TOPIC, message)

            elif action == "OFF":
                print("LED OFF")
                led.off()
                # Simulate sensor update when LED is OFF (default values)
                temperature = 24
                humidity = 40
                # Send updated values to MQTT
                publish_data = {
                    "temperature": temperature,
                    "humidity": humidity
                }
                message = ujson.dumps(publish_data)
                print("Publishing:", message)
                client.publish(PUBLISH_TOPIC, message)
            else:
                print("Invalid message:", msg_data)
        except Exception as e:
            print("Error parsing message:", e)

# Initialize MQTT client
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(on_message)
client.connect()
client.subscribe(SUBSCRIBE_TOPIC)
print("Connected and subscribed to topic!")

# Main loop to read from sensor and publish data
while True:
    try:
        # Read the sensor value every loop
        sensor.measure()  # Read the sensor
        temperature = sensor.temperature()  # Get the temperature from sensor
        humidity = sensor.humidity()  # Get the humidity from sensor
        
        # Publish sensor data to MQTT
        publish_data = {
            "temperature": temperature,
            "humidity": humidity
        }
        message = ujson.dumps(publish_data)
        print(f"Publishing: {message}")
        client.publish(PUBLISH_TOPIC, message)

        # Check for incoming MQTT messages
        client.check_msg()

        # Wait for a while before reading again
        time.sleep(5)
        
    except Exception as e:
        print("Error:", e)
        time.sleep(5)