import machine
import network
import _thread
import time
from time import sleep
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
from utelegram import Bot
# Sensor DHT22
sensor = dht.DHT22(Pin(15))
last_temperature = None
# Define los pines para los LEDs
coldLed = Pin(13, machine.Pin.OUT)
normalLed = Pin(12, machine.Pin.OUT)
warmLed = Pin(14, machine.Pin.OUT)
# Conecta con WiFi
def connect_wifi(ssid, password):
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, password)
while not wifi.isconnected():
sleep(0.5)
print("Conexión WiFi establecida:", wifi.ifconfig())
# Conecta con MQTT
def connect_mqtt(client_id, broker):
client = MQTTClient(client_id, broker)
client.connect()
return client
# Lógica para encender/apagar LEDs
def turn_on_led(led):
coldLed.off()
normalLed.off()
warmLed.off()
led.on()
# Callback para mensajes de MQTT
def on_mqtt_message(topic, msg):
print("Mensaje entrante MQTT:", msg)
try:
msg = ujson.loads(msg)
print(msg)
except Exception as e:
print("Error:", e)
# Nueva función para obtener y enviar la temperatura a través de Telegram y MQTT
last_led_state = None
def get_and_send_temperature(update=None):
global last_led_state # Necesitamos indicar que estamos utilizando la variable global
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
# Lógica para encender las luces según la temperatura
print("Temperatura actual:", temperature)
if temperature > 41:
print("Encendiendo warmLed")
turn_on_led(warmLed)
if last_led_state != "warmLed":
send_telegram_message(temperature, humidity, update, "warmLed")
last_led_state = "warmLed"
elif 15 < temperature <= 40:
print("Encendiendo normalLed")
turn_on_led(normalLed)
if last_led_state != "normalLed":
send_telegram_message(temperature, humidity, update, "normalLed")
last_led_state = "normalLed"
elif temperature < 15:
print("Encendiendo coldLed")
turn_on_led(coldLed)
if last_led_state != "coldLed":
send_telegram_message(temperature, humidity, update, "coldLed")
last_led_state = "coldLed"
mqtt_client.publish("TOPIC/mobile_00001/RQ", message)
# Nueva función para enviar mensajes a Telegram
def send_telegram_message(temperature, humidity, update, led_type):
reply_message = f"Temperatura: {temperature} °C\nHumedad: {humidity}%\nEncendiendo {led_type}"
if update:
update.reply(reply_message)
# Conexión con WiFi
connect_wifi("Wokwi-GUEST", "")
# Conexión con MQTT
mqtt_client = connect_mqtt("esp32_00001", "broker.hivemq.com")
mqtt_client.set_callback(on_mqtt_message)
mqtt_client.subscribe("topics/esp32_00001")
print("ESP32 conectado a MQTT!")
# Inicia el bucle de MQTT en un hilo separado
def wait_message_from_mqtt(name):
while True:
mqtt_client.wait_msg()
_thread.start_new_thread(wait_message_from_mqtt, (1,))
# Conexión con Telegram
TOKEN = '6842594474:AAHlTWaQd2Znsbs0oLMOslNKdVCYNNwQQbU'
bot = Bot(TOKEN)
@bot.add_message_handler('on')
def turn_on_all_leds(update):
coldLed.on()
normalLed.on()
warmLed.on()
get_and_send_temperature(update) # Envia mensaje a Telegram cuando se encienden los LEDs
update.reply("Todos los LEDs encendidos")
@bot.add_message_handler('off')
def turn_off_leds(update):
coldLed.off()
normalLed.off()
warmLed.off()
update.reply("Todos los LEDs apagados")
# Agrega el manejador para el comando 'datos' en Telegram
@bot.add_message_handler('datos')
def get_temperature(update):
global last_led_state # Necesitamos indicar que estamos utilizando la variable global
get_and_send_temperature(update)
# Lógica para manejar mensajes de Telegram (puedes agregar tu propia lógica)
def on_telegram_message(update):
# Puedes agregar lógica específica aquí
pass
# Inicia el bucle de Telegram en un hilo separado
bot.start_loop()
# Bucle principal
while True:
get_and_send_temperature() # Esto enviará la temperatura a través de MQTT y verificará las luces
time.sleep(1)