import network, time, urequests, _thread
import utime
from machine import SoftI2C,Pin
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
from dht import DHT22 # DHT11
from umqtt.simple import MQTTClient
import ujson


# MQTT Server Parameters
MQTT_CLIENT_ID = "server4477hdhdghdgd"#cambiar siempre
MQTT_BROKER    = "broker.hivemq.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "rac/servidor/dato/"


sensor_dht = DHT22(Pin(4)) #DHT11

#Dirección del I2C y tamaño del LCD
I2C_ADDR  =  0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16

#Esp32
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)

#Configuración LCD
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)

def lcd_str(message, col, row):
    lcd.move_to(col, row) # Mover a la posición según los valores de fila y col (Y, X)
    lcd.putstr(message) #Envía una cadena de caracteres a la pantalla. IMPORTANTE: para
    #imprimir una variable puedes usar la siguiente instrucción: lcd.putstr (str (Variable))


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 ("Conexion 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()
    
    print("Conectado al Broker!")

    while True:
        #lectura del sensor y muestra por consola
        sensor_dht.measure()
        tem = sensor_dht.temperature()
        hum = sensor_dht.humidity() 
        print("Tem: {}°C, Hum: {}% ".format(tem, hum))
        
        lcd.blink_cursor_on()  # El cursor parpadeante al imprimir
        lcd_str("Sistema De", 2,0)
        lcd_str("Monitoreo RAC",0,1)
        utime.sleep(2)
        lcd.clear()
        lcd_str("Tem:"+str(tem),0,0)
        lcd_str("Hum:"+str(hum),0,1)
        utime.sleep(2)         
        lcd.blink_cursor_off()  # Apaga el cursor parpadeante al imprimir
        lcd.clear()

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

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