#------------------------------ [IMPORT]------------------------------------

import network, time, urequests
from machine import Pin, ADC, PWM
import dht
import utime # time
import ujson
from umqtt.simple import MQTTClient

#--------------------------- [OBJETOS]---------------------------------------

# MQTT Server Parameters
MQTT_CLIENT_ID = "wilson1651631"
MQTT_BROKER    = "industrial.api.ubidots.com"
MQTT_USER      = "Token"
MQTT_PASSWORD  = "token"
MQTT_TOPIC     = "/v1.6/devices/temperatura"


sensor = dht.DHT22(Pin(15))


#----------------------[ CONECTAR WIFI ]---------------------------------------------------------#

def conectaWifi (red, password):
      global miRed
      miRed = network.WLAN(network.STA_IF)     
      if not miRed.isconnected():              #Si no está conectado…
          miRed.active(True)                   #activa la interface
          miRed.connect(red, password)         #Intenta conectar con la red
          print('Conectando a la red', red +"…")
          timeout = time.time ()
          while not miRed.isconnected():           #Mientras no se conecte..
              if (time.ticks_diff (time.time (), timeout) > 10):
                  return False
      return True

    

#------------------------------------[BOT]---------------------------------------------------------------------#

if conectaWifi ("Wokwi-GUEST", ""):

    print ("Conexión exitosa!")
    print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())
    
    
    print("Connecting to MQTT server... ", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
    client.connect()

    print("Connected!")

    prev_weather = ""
    while True:
      print("Measuring weather conditions... ", end="")
      sensor.measure() 
      message = ujson.dumps({
        "temp": sensor.temperature(),
        "humedad": sensor.humidity(),
      })
      if message != prev_weather:
        print("Updated!")
        print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
        client.publish(MQTT_TOPIC, message)
        prev_weather = message
      else:
        print("No change")
      time.sleep(1)

else:
       print ("Imposible conectar")
       miRed.active (False)