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

# Setări MQTT
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER    = "broker.mqttdashboard.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_IN  = "DataIN"
MQTT_TOPIC_OUT = "DataOut"

# WiFi connection
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
    time.sleep(0.1)
print("Connected to WiFi")

# Init MQTT client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected to MQTT broker")

sensor = dht.DHT22(Pin(15))



pir_sensor = Pin(12, Pin.IN)


ledBlue = Pin(32, Pin.OUT)
ledGreen = Pin(33, Pin.OUT)
ledRed = Pin(25, Pin.OUT)


ledSwitch = Pin(16, Pin.OUT)
prev_message = ""


def data_callback(topic, msg):
    print("Received data: {} on topic: {}".format(msg, topic))

def switch_callback(topic, msg):
    print("Received message: {} on topic: {}".format(msg, topic))
    if msg == b'1':
        ledSwitch.value(1)
        print("LED turned ON")
    elif msg == b'0':
        ledSwitch.value(0) 
        print("LED turned OFF")


client.set_callback(switch_callback)
client.subscribe(MQTT_TOPIC_OUT)

def send_sensor_data():
    sensor.measure() 
    data = {
        "temp": sensor.temperature(),
        "humidity": sensor.humidity(),
        "pir": pir_sensor.value() 
    }

    numeric_values = [str(value) for value in data.values()]
    message = ",".join(numeric_values)
    

    print("Reportng data to MQTT topic {}: {}".format(MQTT_TOPIC_IN, message))
    client.publish(MQTT_TOPIC_IN, message)


while True:
    send_sensor_data()
    
    if pir_sensor.value(): 
        ledBlue.value(1)
        time.sleep(1)
        ledGreen.value(1)
        time.sleep(1)
        ledRed.value(1)

    else:
        ledBlue.value(0)
        ledGreen.value(0)
        ledRed.value(0)
    
    client.check_msg()
    time.sleep(1)