import network, time
from utime import sleep, sleep_ms, ticks_us
from machine import Pin, ADC, I2C
from dht import DHT22
from ssd1306 import SSD1306_I2C
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "clientId-EJzX7rQAlD"
MQTT_BROKER = "broker.hivemq.com"
#MQTT_BROKER = "192.168.20.25" # en docker apuntar al host local
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "ruscustech/tech"
ldr = ADC(Pin(4))
i2c = I2C(sda=Pin(21), scl=Pin(22))
pantalla = SSD1306_I2C(128, 64, i2c)
def map_value(value, in_min, in_max, out_min, out_max):
return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
sensor = DHT22(Pin(16))
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()
# dato = ldr.read_u16()
# sleep_ms(50)
# dato_mapeado = map_value(dato, 0, 65535, 100, 0)
print("Tem: {}, Hum {}".format(tem, hum))
# textIn = "Int luz {:.0f} %".format(dato_mapeado)
sleep_ms(2000)
texto = "Tem: {:.0f} Hum: {:.0f}".format(tem, hum)
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, 8, 1)
pantalla.text(str(texto), 0, 30, 1)
# pantalla.text(str(textIn), 0, 50, 1)
pantalla.show()
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)