# DHT11   -> ESP8266/ESP32
# 1(Vcc)  -> 3v3
# 2(Data) -> GPIO12
# 4(Gnd)  -> Gnd

import time, machine
from dht import DHT22
from machine import Pin
from umqtt.simple import MQTTClient

print("Iniciando...")
dht = DHT22(Pin(12, Pin.IN, Pin.PULL_UP))

#estacao = network.WLAN(network.STA_IF)
#estacao.active(True)
#estacao.connect('ap', 'senha')
#while estacao.isconnected() == False:
#  machine.idle()
#print('Conexao realizada.')
#print(estacao.ifconfig())

SERVIDOR = "mqtt.thingspeak.com"
CHANNEL_ID = "DHT22"
WRITE_API_KEY = "V5R1D7TG3AU012DM"
topico = "channels/" + CHANNEL_ID + "/publish/" + WRITE_API_KEY
cliente = MQTTClient("umqtt_client", SERVIDOR)

try:
  while True:
    dht.measure()
    temp = dht.temperature()
    umid = dht.humidity()
    print('Temperatura: %3.1f °C' %temp)
    print('Umidade: %3.1f %%' %umid)
    conteudo = "field1=" + str(temp) + "&field2=" + str(umid)
    print ('Conectando a ThingSpeak...')
    cliente.connect()
    cliente.publish(topico, conteudo)
    cliente.disconnect()
    print ('Envio realizado.')
    time.sleep(60.0)
except KeyboardInterrupt:
  #estacao.disconnect()
  #estacao.active(False)
  print("Fim.")