from machine import Pin
from machine import SoftI2C
import ssd1306
import time
import dht
import network
import ujson
from umqtt.simple import MQTTClient
try:
import iotc
except:
import mip
mip.install('github:Azure/iot-central-micropython-client/package.json')
import iotc
#Parametrizar el servidor MQTT.
MQTT_CLIENT_ID = "micropython-weather-demo_chaux"
#MQTT_BROKER = "66.29.142.107"
MQTT_BROKER = "broker.emqx.io"
MQTT_PORT = 1883 #Puerto por defecto sin SSL
MQTT_USER = ""
MQTT_PASSWORD = ""
# Tópicos MQTT
MQTT_TOPIC_SUB = "variables/rele"
MQTT_TOPIC_PUB = "variables/temphum"
# Configurar el pin GPIO 2 como salida
led = Pin(15, Pin.OUT)
# Configurar el pin donde está conectado el DHT22
dht_pin = Pin(23) # Cambia el número de pin si es necesario
sensor = dht.DHT22(dht_pin)
# Configurar SoftI2C (SDA en GPIO21, SCL en GPIO22)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
# Inicializar la pantalla OLED (128x64)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Limpiar la pantalla antes de comenzar
oled.fill(0)
# Mostrar texto en la pantalla OLED
oled.text("Hola, MicroPython!", 0, 0) # (texto, x, y)
# Actualizar la pantalla para reflejar los cambios
oled.show()
# Esperar unos segundos
time.sleep(5)
# Limpiar la pantalla nuevamente
oled.fill(0)
oled.show()
# Conectar a la red Wi-Fi
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("Wokwi-GUEST", '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
msg_str="off"
# Función de callback para cuando recibimos un mensaje
def mqtt_callback(topic, msg):
#Cuando recibo datos por MQTT los recibo como bytes b'Hola'
global msg_str
topic_str = topic.decode('utf-8')
msg_str = msg.decode('utf-8')
print(f'Recibido mensaje en {topic_str}: {msg_str}')
if msg_str == 'on':
# Encender el LED
led.on()
if msg_str == 'off':
# Apagar el LED
led.off()
# Configuración y conexión al broker MQTT
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
print('Conectado al broker MQTT')
return client
# Publicar un mensaje
def publish_message(client, message):
client.publish(MQTT_TOPIC_PUB, message)
# Suscribirse a un tema
def subscribe_topic(client):
client.subscribe(MQTT_TOPIC_SUB)
print(f'Suscrito al tema {MQTT_TOPIC_SUB}')
#Bucle Principal.
prev_weather = ""
prev_msg_str = "X"
ciclo = 0
try:
connect_wifi()
client = connect_mqtt()
subscribe_topic(client)
while True:
client.check_msg() # Verifica si hay mensajes sin bloquear el loop
sensor.measure()
message = ujson.dumps({
"temperatura": sensor.temperature(),
"humedad": sensor.humidity(),
})
if message != prev_weather: #Solo publica cuando el dato a cambiado
publish_message(client, message)
print(message)
prev_weather = message
oled.fill(0)
oled.text("TEMP: "+ str(sensor.temperature())+ " oC", 0, 0) # (texto, x, y)
oled.text("HUM: "+ str(sensor.humidity())+" %", 0, 20) # (texto, x, y)
oled.text("LED: "+ str(msg_str), 0, 40) # (texto, x, y)
oled.show()
if msg_str != prev_msg_str: #Solo publica cuando el dato a cambiado
prev_msg_str = msg_str
oled.fill(0)
oled.text("TEMP: "+ str(sensor.temperature())+ " oC", 0, 0) # (texto, x, y)
oled.text("HUM: "+ str(sensor.humidity())+" %", 0, 20) # (texto, x, y)
oled.text("LED: "+ str(msg_str), 0, 40) # (texto, x, y)
oled.show()
ciclo += 1
oled.fill_rect(60, 50, 30, 10, 0)
oled.text("Ciclo: "+ str(ciclo), 0, 50) # (texto, x, y)
oled.show()
time.sleep(0.05)
except OSError as e:
print('Error de conexión', e)