#FUNDAMENTOS DE SISTEMAS EMBEBIDOS
#COMISION 06
#GRUPO: 6.2
#PROYECTO:SE ME QUEMA EL RANCHO
#ESPINOSA, JOAQUÍN MATEO
#PIETRANERA, NICOLAS AYRTON
#Universidad Nacional de La Matanza
###########################DESCRIPCION DEL PROYECTO#####################################
# El sistema cumple la necesidad de supervisar un
# ambiente (en nuestro caso, el rancho), detectando la presencia de gas y/o
# el aumento de la temperatura y alertando al usuario mediante la activación
# de una alarma y una notificacion al dashboard de Adafruit IO
# Este sistema se lleva acabo en tiempo real, brindando la capacidad de activar
# o desactivar la alarma remotamente mediante el dashboard.
# Para ello cumple los requisitos de conectividad WiFi, comunicación utilizando
# broker MQTT, control remoto desde Adafruit IO.
########################################################################################
import machine
import dht
import time
import ds1307
import network
from machine import Pin, ADC, I2C, PWM
from ds1307 import DS1307
from umqtt.simple import MQTTClient# Importa la clase para manejar conexión MQTT (publicar/suscribir)
#################SELECCION DE RED##################
ssid= 'Wokwi-GUEST'
wifipassword= ''
###################################################
#DATOS DE SERVIDOR Y PUERTO BROKER MQTT##########
mqtt_server = 'io.adafruit.com'
port= 1883
user= 'Joaquelson'
password= 'aio_tRBa32HmYbWIxHAH8GPDsj8n5x4m'
#######################
#ID Y TOPICOS########
client_id = 'PROYECTO'
Topic_MQ2 ='Joaquelson/feeds/proyecto.sensormq2'
Topic_DHT22 ='Joaquelson/feeds/proyecto.sensortemp'
Topic_EstadoALARMA = 'Joaquelson/feeds/proyecto.estadoalarma'
Topic_Notificacion = 'Joaquelson/feeds/proyecto.notificacion'
#######################
#####DEFINICION DE MODO STATION(CONEXION CON AC REMOTO)#############
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
####################################################################
#############################CONECTA A WIFI#########################
sta_if.connect(ssid, wifipassword)
print("CONECTANDO")
while not sta_if.isconnected():
print(".", end="")
time.sleep(1)
print("\nCONECTADO A LA RED WIFI:",sta_if.ifconfig())
####################################################################
# ESTADO DE ALARMA
EstadoALARMA = False
EstadoLED=Pin(6,Pin.OUT)
#DECLARACION DE FUNCIONES#########################################
def funcion_callback(topic, msg): #LA FUNCION ejecuta cada vez que recibe datos de un topico
global EstadoALARMA, EstadoLED
MSG= msg.decode('utf-8')
TOPICO= topic.decode('utf-8')
print("CAMBIO EN: ["+str(TOPICO)+"] ["+str(MSG)+"]")
if TOPICO==Topic_EstadoALARMA and "OFF" in MSG:
EstadoALARMA = False
else:
EstadoALARMA = True
#DEFINO UNA FUNCION PARA PRODUCIR LOS MENSAJES QUE VAN A LLEGARLE AL STREAM BLOCK
def PublicarNOTIFICACION(temp_actual, GAS_actual , fecha_hora, tipo_alarma):
mensaje= f"{tipo_alarma} | TEMP: {temp_actual}°C | GAS(ADC): {GAS_actual} \n{fecha_hora}"
conexionMQTT.publish(Topic_Notificacion,mensaje)
#################################################################################
#Funcion para fecha y hora
def funcion_fecha_hora(RTC):
anio, mes, dia, hora, minuto, segundo, weekday, day_year = RTC.datetime
fecha_str = f"{int(dia):02d}/{int(mes):02d}/{int(anio)}"
hora_str = f"{int(hora):02d}:{int(minuto):02d}."
fecha_hora= f"FECHA: {fecha_str} HORA: {hora_str}"
return fecha_hora
#####################################################################################################
####CONEXION AL MQTT#####################################################################
try:
conexionMQTT = MQTTClient(client_id,mqtt_server,user=user,password=password,port=int(port)) #la variable"conexionMQTT"" contiene un objeto producido con la funcion "MQTT.Client"
conexionMQTT.set_callback(funcion_callback)
conexionMQTT.connect()
conexionMQTT.subscribe(Topic_EstadoALARMA)
print("CONEXION ESTABLECIDA AL BROKER MQTT")
except OSError as error:#OSError errores del sistema operativo del ESP32(archivo inexistente, errores de comunicacion, falta de conexion a internet)
print(f"ERROR EN LA CONEXION, REINICIANDO.\"{str(error)}\"")
time.sleep(5)
machine.reset()# La funcion devuelve un 1 y resetea el dispositivo
#########################################################################################
#######---OPERACION DEL SISTEMA---#########
#inicializacion de sensores y perifericos
BUZZER= PWM(Pin(7))
BUZZER.freq(1200)
BUZZER.duty(0)
SensorTEMP= dht.DHT22(Pin(1))
SensorMQ2=ADC(Pin(3))
i2c = I2C(0, scl=Pin(8), sda=Pin(9))#configuracion de la comunicacion i2c (el cero es el microcontrolador interno del ESP32 para usar i2c)
RTC = ds1307.DS1307(i2c=i2c)#el i2c de la izauierda es el parametro que espera la clase DS1307 / el i2c de la derecha es la variable definida previamente
temp_anterior= None
GAS_anterior= None
UMBRAL_TEMP= 50
UMBRAL_GAS= 3500
#ESTADOS
E_0=0 # MEDICION (ENVIA TEMP Y CON_GAS)
E_1=1 # activo prende el led(habilita la alarma)
E_2=2 # Alarma por concentracion de gas
E_3=3 # Alarma por temperatura
E_4=4 # Aalarma por posible incendio
estado= 0
#bucle principal #####################################################
while True:
try:
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.ping()
SensorTEMP.measure()
temp_actual = SensorTEMP.temperature()
GAS_actual = SensorMQ2.read()
fecha_hora=funcion_fecha_hora(RTC)
if estado== E_0:
if temp_actual != temp_anterior:
temp_anterior = temp_actual
conexionMQTT.publish(Topic_DHT22,str(temp_actual))
if GAS_actual!=GAS_anterior:
GAS_anterior = GAS_actual
conexionMQTT.publish(Topic_MQ2,str(GAS_actual))
if EstadoALARMA:
estado=E_1
elif estado==E_1:
EstadoLED.value(EstadoALARMA)
if GAS_actual>=UMBRAL_GAS and temp_actual>=UMBRAL_TEMP:
estado= E_4
elif temp_actual>=UMBRAL_TEMP:
estado= E_3
elif GAS_actual>=UMBRAL_GAS:
estado= E_2
else:
estado= E_0
elif estado==E_2:
BUZZER.duty(512)
PublicarNOTIFICACION(temp_actual, GAS_actual, fecha_hora, "ALERTA: GAS ELEVADO")
if not EstadoALARMA:
BUZZER.duty(0)
estado=E_0
elif estado==E_3:
BUZZER.duty(512)
PublicarNOTIFICACION(temp_actual, GAS_actual, fecha_hora, "ALERTA: TEMPERATURA ALTA")
if not EstadoALARMA:
BUZZER.duty(0)
estado=E_0
elif estado==E_4:
BUZZER.duty(1023)
PublicarNOTIFICACION(temp_actual, GAS_actual, fecha_hora, "ALERTA: POSIBLE INCENDIO DEL RANCHO")
if not EstadoALARMA:
BUZZER.duty(0)
estado=E_0
except OSError as e:
print("ERROR: "+str(e))
time.sleep(5)
machine.reset()