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

# Pin Definitions
LED_PIN = 2
DHT_PIN = 13

# MQTT Server Parameters
MQTT_CLIENT_ID = "Cobasajasini"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = "amza"
MQTT_PASSWORD = "amza"
MQTT_TOPIC_PUB = "Arborea/Amri/data_sensor"
MQTT_TOPIC_SUB = "Arborea/Amri/aktuasi_led"
MQTT_PORT = 1883

# Initialize LED and DHT22
led = Pin(LED_PIN, Pin.OUT)
dht_sensor = dht.DHT22(Pin(DHT_PIN))

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

# MQTT Callback Function 
def mqtt_callback(topic, msg):
    print("Received message:", msg.decode())
    if msg.decode() == "ON":
        led.value(1)
    elif msg.decode() == "OFF":
        led.value(0)

# Initialize MQTT Client
# client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD, port=MQTT_PORT, ssl=True)
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD, port=MQTT_PORT)
client.set_callback(mqtt_callback)
while True:
    try:
        client.connect()
        print("Connected to MQTT Broker")
        break
    except Exception as e:
        print(f"Connection failed: {e}")
        time.sleep(5)

client.subscribe(MQTT_TOPIC_SUB)

print("Subscripted to MQTT Broker data_sensor")

# Main Loop
try:
    while True:
        # Publish Sensor Data
        dht_sensor.measure()
        temperature = dht_sensor.temperature()
        humidity = dht_sensor.humidity()
        sensor_data = f"Temperature: {temperature}°C, Humidity: {humidity}%"
        client.publish(MQTT_TOPIC_PUB, sensor_data)
        print(f"Published: {sensor_data}")

        # Check for new messages
        client.check_msg()

        # Wait for a while before next reading
        time.sleep(10)

except Exception as e:
    print(f"Error: {e}")
finally:
    client.disconnect()