import network
import time
import urequests
from machine import Pin
from dht import DHT22
# Configuración de Twilio
ACCOUNT_SID = "AC6d5d03013b560130138f4fb04fb22981"
AUTH_TOKEN = "1fc50953b44e40d2225f7fe0abba239a"
FROM_WHATSAPP_NUMBER = "whatsapp:+14155238886"
TO_WHATSAPP_NUMBER = "whatsapp:+524443199652"
# Configuración del sensor
sensor_dht = DHT22(Pin(21)) # Sensor conectado al pin GPIO 21
# Conexión Wi-Fi
def conectarWIFI(red, password):
miRed = network.WLAN(network.STA_IF)
if not miRed.isconnected():
miRed.active(True)
miRed.connect(red, password)
print(f"Conectándose a la red {red}...")
timeout = time.time()
while not miRed.isconnected():
if time.ticks_diff(time.time(), timeout) > 10:
return False
return True
# Enviar mensaje por WhatsApp
def enviar_mensaje(mensaje):
url = f"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/Messages.json"
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = f"From={FROM_WHATSAPP_NUMBER}&To={TO_WHATSAPP_NUMBER}&Body={mensaje}"
auth = (ACCOUNT_SID, AUTH_TOKEN)
try:
response = urequests.post(url, data=data, headers=headers, auth=auth)
if response.status_code == 201:
print("Mensaje enviado con éxito:", mensaje)
else:
print("Error al enviar mensaje:", response.text)
response.close()
except Exception as e:
print("Error al conectarse a Twilio:", e)
# Monitorear cambios en temperatura y humedad
def monitorear_cambios():
temp_anterior = None
hum_anterior = None
while True:
try:
sensor_dht.measure()
temp = sensor_dht.temperature()
hum = sensor_dht.humidity()
print(f"Temperatura: {temp}°C, Humedad: {hum}%")
# Verificar cambios
if temp != temp_anterior or hum != hum_anterior:
mensaje = f" Actualización:\n- Temperatura: {temp}°C\n- Humedad: {hum}%"
enviar_mensaje(mensaje)
temp_anterior = temp
hum_anterior = hum
time.sleep(10) # Esperar 10 segundos entre lecturas
except Exception as e:
print("Error al leer el sensor:", e)
# Programa principal
if conectarWIFI("Wokwi-GUEST", ""):
print("¡Conexión Wi-Fi exitosa!")
enviar_mensaje("Bot de temperatura activado. Notificaciones listas.")
monitorear_cambios()
else:
print("Error al conectar a Wi-Fi. Verifica la red.")