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

pin15 = Pin(15, Pin.OUT)

wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")

while not wifi.isconnected():
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")

MQTT_CLIENT_ID = "FizenHSC079"
MQTT_BROKER    = "broker.hivemq.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_LED     = "/HSC079/TIMSTI21PEKANBARU/MRAFFIZEIN/aktuasi_led"

client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)

def on_message(topic, message):
    # print(str(message, "UTF-8"))
    message = str(message, "UTF-8")
    print("message received!")
    print(topic)
    print(message)
    if message == "on":
        pin15.on()
    elif message == "off":
        pin15.off()



client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_TOPIC_LED)

sensor = dht.DHT22(Pin(4))


# STEP 4: CONNECT MQTT SENSOR
MQTT_CLIENT_ID = "RaffiZein079"
MQTT_BROKER    = "mqtt-dashboard.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_SENSOR = "/HSC079/TIMSTI21PEKANBARU/MRAFFIZEIN/data_sensor"

client_sensor = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client_sensor.connect()

while True:
    time.sleep(1)

    sensor.measure()
    client.check_msg()
    hum = sensor.humidity()
    temp = sensor.temperature()
    print("humidity:", hum)
    print("temperature:", temp)

    message = f"suhu: {temp}, kelembapan: {hum}"
    client_sensor.publish(MQTT_TOPIC_SENSOR, message)

    try:
        client.check_msg()
    except OSError as e:
        print("Error in MQTT client:", e)
        try:
            client.connect()
            client.subscribe(MQTT_TOPIC_LED)
            print("Reconnected to MQTT broker.")
        except Exception as e:
            print("Reconnection failed:", e)