import urequests
import json
import time
import machine
import dht
import network
import ujson
import umail
from machine import Pin, ADC, I2C
from ssd1306 import SSD1306_I2C
from umqtt.simple import MQTTClient
# --- Configurações de Hardware ---
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
sensor_dht = dht.DHT22(Pin(15))
ldr = ADC(Pin(34))
ldr.atten(ADC.ATTN_11DB)
mq2 = ADC(Pin(35))
mq2.atten(ADC.ATTN_11DB)
botao = Pin(13, Pin.IN, Pin.PULL_UP)
# --- Configurações de Rede e Endpoints ---
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
MQTT_BROKER = "broker.hivemq.com"
MQTT_CLIENT_ID = "estacao_matheus2004"
MQTT_TOPIC = "estacao_meteorologica"
URL_GOOGLE = "https://script.google.com/macros/s/AKfycbwexiJLHSLkaGxt4Xa5CaVGhqjnuUv4r_F1FsCq8LZLDTYqI25sM4yUB0yVWvdMyJ4/exec"
# --- Configurações de E-mail ---
EMAIL_USER = "[email protected]"
EMAIL_PASS = "tbdyszwrgcswtzmj"
EMAIL_TO = "[email protected]"
# --- Variáveis de Controle ---
tela = 0
ultimo_tempo_mqtt = 0
ultimo_tempo_sheets = 0
ultimo_tempo_email = 0
botao_pressionado = False
media_temp_diaria = 0.0
media_hum_diaria = 0.0
total_leituras_diaria = 0
# --- Funções de Comunicação ---
def conecta_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Conectando ao WiFi...')
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected(): pass
print('WiFi Conectado:', wlan.ifconfig())
def envia_dados_mqtt(dados):
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
client.publish(MQTT_TOPIC, ujson.dumps(dados))
client.disconnect()
print("MQTT Enviado OK")
except: print("Erro MQTT")
def envia_email_relatorio():
print("Iniciando envio automático de e-mail...")
try:
# Usamos a porta 587 (STARTTLS) que é a mais compatível
smtp = umail.SMTPSession("smtp.gmail.com", 587)
smtp.login(EMAIL_USER, EMAIL_PASS)
# O SEGREDO ESTÁ AQUI: O Gmail exige esses headers formatados
# From, To e Subject precisam estar no início do corpo da mensagem
header = "From: {}\r\n".format(EMAIL_USER)
header += "To: {}\r\n".format(EMAIL_TO)
header += "Subject: Relatorio Diario Estufa - Matheus\r\n\r\n"
corpo = """Relatorio de Monitoramento
Media Temp: {} C
Media Umid: {} %
Total de Leituras: {}""".format(media_temp_diaria, media_hum_diaria, total_leituras_diaria)
# Enviamos o header + corpo juntos
smtp.send(EMAIL_USER, EMAIL_TO, "Relatorio Diario Estufa - Matheus", header + corpo)
print("E-mail enviado com sucesso!")
except Exception as e:
print("Erro SMTP:", e)
def envia_google_sheets(t, h):
global media_temp_diaria, media_hum_diaria, total_leituras_diaria
try:
res = urequests.post(URL_GOOGLE, json={"temp": t, "hum": h})
if res.status_code == 200:
dados = res.json()
media_temp_diaria = float(dados["mediaTemp"])
media_hum_diaria = float(dados["mediaHum"])
total_leituras_diaria = int(dados["leituras"])
res.close()
except: pass
# --- Inicialização ---
conecta_wifi()
while True:
# 1. Lógica do Botão
if botao.value() == 0 and not botao_pressionado:
tela = (tela + 1) % 4
botao_pressionado = True
time.sleep(0.2)
elif botao.value() == 1:
botao_pressionado = False
# 2. Leitura dos Sensores
try:
sensor_dht.measure()
temp, hum = sensor_dht.temperature(), sensor_dht.humidity()
except: temp, hum = 0, 0
luz, gas = ldr.read(), mq2.read()
# 3. Lógica do Display
oled.fill(0)
if tela == 0:
if temp > 35: oled.text("ALERTA: CALOR!", 0, 0)
else: oled.text("Status: Normal", 0, 0)
oled.text("Temp: {}C".format(temp), 0, 15)
oled.text("Umid: {}%".format(hum), 0, 25)
elif tela == 1:
if gas > 3000: oled.text("ALERTA: AR RUIM!", 0, 0)
else: oled.text("Status: Normal", 0, 0)
oled.text("Luz: {}".format(luz), 0, 15)
oled.text("Gas: {}".format(gas), 0, 25)
elif tela == 2:
oled.text("MEDIAS DIA", 0, 15)
oled.text("T:{} H:{}".format(media_temp_diaria, media_hum_diaria), 0, 25)
oled.text("Leituras: {}".format(total_leituras_diaria), 0, 35)
elif tela == 3:
oled.text("Sheets: Online", 0, 15)
oled.text("MQTT: Conectado", 0, 25)
oled.show()
# 4. Envio Nuvem e E-mail (Temporizados)
tempo_atual = time.time()
# Envio MQTT
if (tempo_atual - ultimo_tempo_mqtt) > 10:
envia_dados_mqtt({"temp": temp, "umid": hum, "luz": luz, "gas": gas})
ultimo_tempo_mqtt = tempo_atual
# Envio Sheets
if (tempo_atual - ultimo_tempo_sheets) > 15:
envia_google_sheets(temp, hum)
ultimo_tempo_sheets = tempo_atual
# Envio E-mail
if (tempo_atual - ultimo_tempo_email) > 20:
if total_leituras_diaria > 0:
envia_email_relatorio()
ultimo_tempo_email = tempo_atual
time.sleep(0.1)