from machine import Pin
from machine import Timer
from hcsr04 import HCSR04
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
# Configura MQTT
mqtt_server = '01c42219114541d68dff24c221454076.s2.eu.hivemq.cloud'
mqtt_user = 'mechatronycs'
mqtt_pass = 'M3chatronycs'
client_id = ubinascii.hexlify(machine.unique_id())
topicoLaminaEntrada = 'topic/height/entrance'
topicoLaminaMeio = 'topic/height/middle'
topicoLaminaSaida = 'topic/height/exit'
topicoAlertaTweet = 'topic/alert/tweet'
localMonitoramento = 'Complexo Viario Ayrton Senna'
# NÃO é possível executar a conexão com a rede Wifi, pois o Wokwi não tem suporte ainda:
"""
ssid = 'Wokwi-GUEST'
password = ''
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
"""
# *****************************************************************************************
# Configura a altura que o sensor sera instalado e o minimo para alerta (cm)
alturaSensor = 400
laminaAguaAlerta = 30
margemErro = 3
# Confira a quantidade em segundos que o alerta comeca a ser considera (evitar falso positivo, ex: pedestre)
aguardaSegundoAlerta = 5 # mudar para 10
tempoAlertaSensorEntrada = time.time()
tempoAlertaSensorMeio = time.time()
tempoAlertaSensorSaida = time.time()
tempoNivelNormalSensorEntrada = time.time()
tempoNivelNormalSensorMeio = time.time()
tempoNivelNormalSensorSaida = time.time()
# Confira a quantidade em segundos que o twitter sera feito para evitar ficar twittando toda hora
aguardaSegundoTwitter = 10 # mudar para 600 (10 minutos)
tempoAlertaTwitter = time.time()
tweetAlertaAtivo = False
# Configura os sensores HCSR04:
sensorEntrada = HCSR04(trigger_pin=14, echo_pin=26, echo_timeout_us=1000000)
sensorMeio = HCSR04(trigger_pin=23, echo_pin=22, echo_timeout_us=1000000)
sensorSaida = HCSR04(trigger_pin=2, echo_pin=4, echo_timeout_us=1000000)
# Função que conecta no MQTT Broker
def connect_MQTT():
global client_id, mqtt_server
client = MQTTClient(client_id, mqtt_server, 8883, mqtt_user, mqtt_pass, True)
client.connect()
print('Conectado %s MQTT broker ' % (mqtt_server))
return client
# Função que restarta ESP32 e tenta reconectar
def restart_and_reconnect_MQTT():
print('Falha ao conectar MQTT broker. Reconectando...')
time.sleep(10)
machine.reset()
# Conexão com MQTT desabilitada, devido a não ter suporte no Wokwi
"""
try:
client = connect_MQTT()
except OSError as e:
restart_and_reconnect_MQTT()
"""
while True:
now = time.localtime()
distanciaEntrada = (sensorEntrada.distance_mm() / 10) - margemErro
distanciaMeio = (sensorMeio.distance_mm() / 10) - margemErro
distanciaSaida = (sensorSaida.distance_mm() / 10) - margemErro
laminaAguaEntrada = alturaSensor - distanciaEntrada
if laminaAguaEntrada <= 0:
laminaAguaEntrada = 0
laminaAguaMeio = alturaSensor - distanciaMeio
if laminaAguaMeio <= 0:
laminaAguaMeio = 0
laminaAguaSaida = alturaSensor - distanciaSaida
if laminaAguaSaida <= 0:
laminaAguaSaida = 0
msg = b'%.1f' % laminaAguaEntrada
#client.publish(topicoLaminaEntrada, msg)
print(f'** MQTT Publish: {topicoLaminaEntrada} - {laminaAguaEntrada:.1f}')
msg = b'%.1f' % laminaAguaMeio
#client.publish(topicoLaminaMeio, msg)
print(f'** MQTT Publish: {topicoLaminaMeio} - {laminaAguaMeio:.1f}')
msg = b'%.1f' % laminaAguaSaida
#client.publish(topicoLaminaSaida, msg)
print(f'** MQTT Publish: {topicoLaminaSaida} - {laminaAguaSaida:.1f}')
#print('Lâmina Sensor Entrada: ', laminaAguaEntrada, 'cm')
#print('Lâmina Sensor Meio: ', laminaAguaMeio, 'cm')
#print('Lâmina Sensor Saida: ', laminaAguaSaida, 'cm')
if (laminaAguaEntrada >= laminaAguaAlerta):
if (time.time() - tempoAlertaSensorEntrada >= aguardaSegundoAlerta):
tempoAlertaSensorEntrada = time.time()
if ((not tweetAlertaAtivo) or (time.time() - tempoAlertaTwitter >= aguardaSegundoTwitter)):
tweet = f'Alerta - Possivel area de alagamento{chr(10)}{chr(10)}'
tweet += f'Sensor: Entrada Tunel{chr(10)}{chr(10)}'
tweet += f"Lamina d'agua: {laminaAguaEntrada:.1f}cm{chr(10)}{chr(10)}"
tweet += f'Data e hora: {now[2]}/{now[1]}/{now[0]} {now[3]}:{now[4]}:{now[5]}{chr(10)}{chr(10)}'
tweet += f'Localizacao: {localMonitoramento}'
print('******************************************************')
print(tweet)
print('******************************************************')
#client.publish(topicoAlertaTweet, tweet)
tweetAlertaAtivo = True
tempoAlertaTwitter = time.time()
else:
if (not tweetAlertaAtivo):
tempoAlertaSensorEntrada = time.time()
elif (time.time() - tempoAlertaSensorEntrada >= aguardaSegundoAlerta):
tweetAlertaAtivo = False
tempoAlertaSensorEntrada = time.time()
if ((laminaAguaMeio < laminaAguaAlerta) and (laminaAguaSaida < laminaAguaAlerta)):
tweet = f'Alerta - Situacao NORMALIZADA{chr(10)}{chr(10)}'
tweet += f'Sensor: Entrada Tunel{chr(10)}{chr(10)}'
tweet += f"Lamina d'agua: {laminaAguaEntrada:.1f}cm{chr(10)}{chr(10)}"
tweet += f'Data e hora: {now[2]}/{now[1]}/{now[0]} {now[3]}:{now[4]}:{now[5]}{chr(10)}{chr(10)}'
tweet += f'Localizacao: {localMonitoramento}'
print('******************************************************')
print(tweet)
print('******************************************************')
#client.publish(topicoAlertaTweet, tweet)
if (laminaAguaMeio >= laminaAguaAlerta):
if (time.time() - tempoAlertaSensorMeio >= aguardaSegundoAlerta):
tempoAlertaSensorMeio = time.time()
if ((not tweetAlertaAtivo) or (time.time() - tempoAlertaTwitter >= aguardaSegundoTwitter)):
tweet = f'Alerta - Possivel area de alagamento{chr(10)}{chr(10)}'
tweet += f'Sensor: Meio Tunel{chr(10)}{chr(10)}'
tweet += f"Lamina d'agua: {laminaAguaMeio:.1f}cm{chr(10)}{chr(10)}"
tweet += f'Data e hora: {now[2]}/{now[1]}/{now[0]} {now[3]}:{now[4]}:{now[5]}{chr(10)}{chr(10)}'
tweet += f'Localizacao: {localMonitoramento}'
print('******************************************************')
print(tweet)
print('******************************************************')
#client.publish(topicoAlertaTweet, tweet)
tweetAlertaAtivo = True
tempoAlertaTwitter = time.time()
else:
if (not tweetAlertaAtivo):
tempoAlertaSensorMeio = time.time()
elif (time.time() - tempoAlertaSensorMeio >= aguardaSegundoAlerta):
tweetAlertaAtivo = False
tempoAlertaSensorMeio = time.time()
if ((laminaAguaEntrada < laminaAguaAlerta) and (laminaAguaSaida < laminaAguaAlerta)):
tweet = f'Alerta - Situacao NORMALIZADA{chr(10)}{chr(10)}'
tweet += f'Sensor: Meio Tunel{chr(10)}{chr(10)}'
tweet += f"Lamina d'agua: {laminaAguaMeio:.1f}cm{chr(10)}{chr(10)}"
tweet += f'Data e hora: {now[2]}/{now[1]}/{now[0]} {now[3]}:{now[4]}:{now[5]}{chr(10)}{chr(10)}'
tweet += f'Localizacao: {localMonitoramento}'
print('******************************************************')
print(tweet)
print('******************************************************')
#client.publish(topicoAlertaTweet, tweet)
if (laminaAguaSaida >= laminaAguaAlerta):
if (time.time() - tempoAlertaSensorSaida >= aguardaSegundoAlerta):
tempoAlertaSensorSaida = time.time()
if ((not tweetAlertaAtivo) or (time.time() - tempoAlertaTwitter >= aguardaSegundoTwitter)):
tweet = f'Alerta - Possivel area de alagamento{chr(10)}{chr(10)}'
tweet += f'Sensor: Saida Tunel{chr(10)}{chr(10)}'
tweet += f"Lamina d'agua: {laminaAguaSaida:.1f}cm{chr(10)}{chr(10)}"
tweet += f'Data e hora: {now[2]}/{now[1]}/{now[0]} {now[3]}:{now[4]}:{now[5]}{chr(10)}{chr(10)}'
tweet += f'Localizacao: {localMonitoramento}'
print('******************************************************')
print(tweet)
print('******************************************************')
#client.publish(topicoAlertaTweet, tweet)
tweetAlertaAtivo = True
tempoAlertaTwitter = time.time()
else:
if (not tweetAlertaAtivo):
tempoAlertaSensorSaida = time.time()
elif (time.time() - tempoAlertaSensorSaida >= aguardaSegundoAlerta):
tweetAlertaAtivo = False
tempoAlertaSensorSaida = time.time()
if ((laminaAguaEntrada < laminaAguaAlerta) and (laminaAguaMeio < laminaAguaAlerta)):
tweet = f'Alerta - Situacao NORMALIZADA{chr(10)}{chr(10)}'
tweet += f'Sensor: Saida Tunel{chr(10)}{chr(10)}'
tweet += f"Lamina d'agua: {laminaAguaSaida:.1f}cm{chr(10)}{chr(10)}"
tweet += f'Data e hora: {now[2]}/{now[1]}/{now[0]} {now[3]}:{now[4]}:{now[5]}{chr(10)}{chr(10)}'
tweet += f'Localizacao: {localMonitoramento}'
print('******************************************************')
print(tweet)
print('******************************************************')
#client.publish(topicoAlertaTweet, tweet)
time.sleep(1.0)
#NÃO RETIRAR