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

ubidotsToken = "BBUS-pqwnvN7njzDaHvMxJXkpMjOu0Ix1HX"
clientID = "dandebharath09"

sensor = dht.DHT22(Pin(15))

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(clientID, "industrial.api.ubidots.com", 1883, user=ubidotsToken, password=ubidotsToken)
client.connect()
print("Connected!")

perv_wheather = ""
while True:
    print("Measuring wheather conditions... ",end="")
    sensor.measure()
    temperature = sensor.temperature()
    humidity = sensor.humidity()

    message = ujson.dumps({
        "temperature":sensor.temperature(),
        "humidity":sensor.humidity(),
    })
    if message != perv_wheather:
        print("Updated!")
        client.publish(b"/v1.6/devices/ESP32",message)
        perv_wheather = message
    else:
        print("No change")
    time.sleep(1)