from machine import Pin, ADC, I2C
import network, time
from utime import sleep, sleep_ms
from dht import DHT22
from hcsr04 import HCSR04
from ssd1306 import SSD1306_I2C
import ujson
from umqtt.simple import MQTTClient


# MQTT Server Parameters
MQTT_CLIENT_ID = "clineteu434svgdg"
MQTT_BROKER    = "broker.hivemq.com"
#MQTT_BROKER    = "192.168.20.25"  #  en docker apuntar al host local
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "andina/diplomado/python"



dis = HCSR04(trigger_pin=12, echo_pin=14)
sensor = DHT22(Pin(4))
i2c = I2C(sda=Pin(21), scl=Pin(22))
pantalla = SSD1306_I2C(128, 64, i2c)

print(i2c.scan(), "Conectada")

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

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

    print ("Conexión exitosa!")
    print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())

    print("Conectando a  MQTT server... ",MQTT_BROKER,"...", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
    client.connect()


    while True:
        sensor.measure()
        tem = sensor.temperature()
        hum = sensor.humidity()
        dista = dis.distance_cm()
        #print("Tem:{}°c, Hum:{}% , Dis:{}cm".format(tem,hum,dista))
        sleep_ms(400)
        pantalla.hline(0, 0, 128, 1)
        pantalla.hline(0, 20, 128, 1)
        pantalla.vline(0, 0, 20, 1)
        pantalla.vline(127, 0, 20, 1)
        pantalla.text("Datos", 40, 10)
        pantalla.text("Tem:", 0, 30)
        pantalla.text("Hum:", 0, 40)
        pantalla.text("Dis:", 0, 50)
        pantalla.text(str(tem), 40, 30)
        pantalla.text(str(hum), 40, 40)
        pantalla.text(str(dista), 40, 50)
        pantalla.text("C", 100, 30)
        pantalla.text("%", 100, 40)
        pantalla.text("cm", 100, 50)
        pantalla.show()
        sleep(1)

        print("Revisando Condiciones ...... ")
        message = ujson.dumps({
        "Humedad": hum,
        "Temperatura": tem,
        "Distancia":dista,
        })
     
        print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
        client.publish(MQTT_TOPIC, message)

        sleep(3)




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