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  = "ClientIDHSC053LED"
MQTT_BROKER     = "mqtt-dashboard.com"
MQTT_USER       = ""
MQTT_PASSWORD   = ""
MQTT_TOPIC_LED  = "/HSC053/Tim16STIPekanbaru/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(2))

MQTT_CLIENT_ID    = "ClientIDHSC53Data"
MQTT_BROKER       = "mqtt-dashboard.com"
MQTT_USER         = ""
MQTT_PASSWORD     = ""
MQTT_TOPIC_SENSOR = "/HSC053/Tim16STIPekanbaru/datasensor"

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}, kelembaban: {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)