"""
MicroPython IoT Weather Station Example for Wokwi.com

To view the data:

1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"

Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.

Copyright (C) 2022, Uri Shaked

https://wokwi.com/arduino/projects/322577683855704658
"""

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

# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER    = "broker.mqttdashboard.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "franky-weather"


sensor = dht.DHT22(Pin(15))
led = Pin(5, Pin.OUT)
led_val = False

def byte_to_bool(byte_val):
    # Decodifica il byte in una stringa
    str_val = byte_val.decode('utf-8')  # Decodifica in UTF-8
    
    # Rimuove spazi e confronta insensibile alle maiuscole/minuscole
    cleaned_str = str_val.strip().lower()  
    
    # Converte in booleano
    if cleaned_str == 'true':
        return True
    elif cleaned_str == 'false':
        return False
    else:
        raise ValueError("Il byte non può essere convertito in un booleano.")

def on_message(topic, msg):
    print("Messaggio ricevuto:", topic, str(msg))
    global led_val
    led_val = byte_to_bool(msg)  # Imposta il valore del LED in base al messaggio ricevuto
    print(led_val)

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

print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
client.set_callback(on_message)

print("Connected!")

prev_temp = ""
prev_hum = ""
prev_led = False

try:
    client.subscribe(MQTT_TOPIC+"_led")
    while True:
        client.check_msg()
        if led_val != prev_led:
            if led_val == False:
                led.off()
            else:
                led.on()
            prev_led=led_val

        sensor.measure() 
        tempMessage = ujson.dumps({
            sensor.temperature(),
        })
        humMessage = ujson.dumps({
            sensor.humidity(),
        })
        if tempMessage != prev_temp:
            print("Updated!")
            print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC+"_temp", tempMessage))
            client.publish(MQTT_TOPIC+"_temp", tempMessage)
            prev_temp = tempMessage
        if humMessage != prev_hum:
            print("Updated!")
            print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC+"_hum", humMessage))
            client.publish(MQTT_TOPIC+"_hum", humMessage)
            prev_hum = humMessage
        
        time.sleep(1)
finally:
    print("connection lost")
    client.disconnect()