from machine import Pin, Timer
from utime import sleep_ms
from umqtt.simple import MQTTClient
import network
import dht

dht22 = dht.DHT22(Pin(14))

wifi_ssid = "Wokwi-GUEST"  # Fill in  your wifi info
wifi_pwd = ""

MQTT_BROKER = "mqtt.netpie.io"  
MQTT_CLIENT = "55f2409e-0eb4-4b4c-b502-f8e3bcf82dd0" # Client ID
MQTT_USER = "6Xbvq3aburaroXx92p58HWLS9aegL5VY" # Token
MQTT_PWD = "XLV8EfXnf4XQ7naKnYoSXi4vJbA6PX7R" # Secret

def update_humi_temp(event):
    	global client
        dht22.measure()
        publish_str = "Temp: " + str(dht22.temperature()) + "°C, Humi: " + 	str(dht22.humidity()) + "%"
    	print(publish_str)
    	client.publish("@msg/temp",'{:.1f}'.format(dht22.temperature()))
    	client.publish("@msg/humi",'{:.1f}'.format(dht22.humidity()))
    
def wifi_connect():
    	wlan = network.WLAN(network.STA_IF)
    	wlan.active(False)
        wlan.active(True)
    	if not wlan.isconnected():
        		print('connecting to network...')
        		wlan.connect(wifi_ssid, wifi_pwd)
        		while not wlan.isconnected():
            			pass
    	print('network config:', wlan.ifconfig())
          
def init_client():
    	global client
    	print("Trying to connect to MQTT Broker.")
        try:
                client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, port=1883, 		user=MQTT_USER,password=MQTT_PWD)
                client.connect()
                print("Connected to ",MQTT_BROKER)
    	except:
        		print("Trouble to init mqtt.") 

wifi_connect()  # connect to WiFi network
init_client()

dht_timer = Timer(1)
dht_timer.init(period=5000, mode=Timer.PERIODIC, callback=update_humi_temp)

while True:
    	client.check_msg()
    	sleep_ms(1000)