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

# MQTT Server Parameters
MQTT_CLIENT_ID = "NGFCFGBXDCHVJHJKN"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "NeoHorizon"

# Callback function for received messages
def message_callback(topic, msg):
    global last_topic, last_message
    last_topic = topic.decode()
    last_message = msg.decode()
    print(f"Pesan diterima di topik {last_topic}: {last_message}")

# Sensor initialization
sensor1 = dht.DHT22(Pin(15))
sensor2 = dht.DHT22(Pin(2))

# LED initialization
led = Pin(14, Pin.OUT)

# Initialize 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.1)
print(" Connected!")

# Initialize MQTT connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(message_callback)  # Set the callback for incoming messages
client.connect()
client.subscribe(MQTT_TOPIC)  # Subscribe to the topic
print("Connected!")

# Initialize variables
last_topic = ""
last_message = ""
prev_weather = ""

# Main loop
while True:
    # Measure sensor data and send to MQTT
    sensor1.measure()
    sensor2.measure()
    message = ujson.dumps({
        "temp1": sensor1.temperature(),
        "humidity1": sensor1.humidity(),
        "temp2": sensor2.temperature(),
        "humidity2": sensor2.humidity(),
    })
    if message != prev_weather:
        print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
        client.publish(MQTT_TOPIC, message)
        prev_weather = message

    # Wait for and process MQTT messages
    client.check_msg()  # Non-blocking call to check for new messages
    print(f"Last Message: {last_message}")  # Debugging log
    if last_message == "on":
        print("Turning LED ON")  # Debugging log
        led.on()
    elif last_message == "off":
        print("Turning LED OFF")  # Debugging log
        led.off()
    time.sleep(1)