import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
#import paho.mqtt.client as mqtt

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

def on_connect(client, userdata, flags, rc, properties):
    print("Connected with result code "+str(rc))
    print("\n connected with client "+ str(client))
    print("\n connected with userdata "+str(userdata))
    print("\n connected with flags "+str(flags))

def on_message(client, userdata, msg):
    print("\n on message: "+msg.topic+" "+str(msg.payload))

def on_log(client, userdata, paho_log_level, messages):
    print("\n log:client = "+ str(client))
    print("\n log:level ="+str(paho_log_level))
    print("\n log:buffer "+str(messages))

def on_subscribe(client, userdata, mid, reason_code_list, properties):
    if reason_code_list[0].is_failure:
        print(f"Broker rejected you subscription: {reason_code_list[0]}")
    else:
        print(f"Broker granted the following QoS: {reason_code_list[0].value}")
        
def on_publish(client, userdata, mid, reason_code, properties): #create function for callback
    print("\non_publish data published \n")
    print("\non_pub: mid = ", mid)
    

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

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_publish = on_publish
client.on_log = on_log
client.connect(MQTT_TOPIC, 1883, 60)


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

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


        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(0.3)
finally:
    print("connection lost")
    client.disconnect()