from machine import Pin
from time import sleep
import dht,math,time,network,micropython,esp
from machine import ADC
from umqtt.simple import MQTTClient
import ubinascii
import network

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

sensor_dht = dht.DHT22(Pin(5,Pin.IN, Pin.PULL_UP))

SERVER = "picolab.embcircuit.com"
client = MQTTClient("weather_station", SERVER, 1883,user='picolab', password='ee211101980hunter')

CHANNEL_ID = "129600"
WRITE_API_KEY = "U1FYH6EF4907PGFM"
topic = "channels/" + CHANNEL_ID + "/publish/" + WRITE_API_KEY

while True:
    sensor_dht.measure()
    temperature = sensor_dht.temperature()
    humidity = sensor_dht.humidity()
    
    payload = "field1="+str(temperature)+"&field2="+str(humidity)

    client.connect()
    client.publish(topic, payload)
    print("Payload published successfully")
    #print(publish_check)
    client.disconnect() 
    time.sleep(20)