import gc
from machine import Pin, SoftI2C, ADC
import time
# 1. LIGA A TELA NA LINHA 1 (TESTE DE VIDA)
gc.collect()
try:
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
import ssd1306
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
oled.fill(0)
oled.text("SISTEMA VIVO!", 20, 30)
oled.show()
print("OLED inicializado.")
except:
print("Erro no visor. Verifique se o arquivo ssd1306.py existe!")
# 2. CARREGA O RESTO DEPOIS (ECONOMIA DE RAM)
import network, ujson, ntptime, dht, socket, ssl, ubinascii
# --- CONFIGURAÇÕES ---
REMETENTE = "[email protected]"
SENHA_APP = "hiqwvsdnkqexfpdu"
DESTINO = "[email protected]"
# PROGRAMADO PARA 00:20 (AJUSTE PELO RELÓGIO QUE APARECER NO OLED!)
HORA_ALVO, MIN_ALVO = 0, 20
# --- HARDWARE ---
sensor_dht = dht.DHT22(Pin(15))
mq2 = ADC(Pin(35))
mq2.atten(ADC.ATTN_11DB)
btn = Pin(4, Pin.IN, Pin.PULL_UP)
st = {'t':0, 'u':0, 'g':0, 'tela':0, 'l_btn':0}
def click(p):
if time.ticks_diff(time.ticks_ms(), st['l_btn']) > 300:
st['tela'] = (st['tela'] + 1) % 2
st['l_btn'] = time.ticks_ms()
btn.irq(trigger=Pin.IRQ_RISING, handler=click)
def get_gas(v):
# Sua calibração vitoriosa de pontos
a = [0, 2567, 3061, 3146, 3226, 3337, 3415, 3516, 3665, 3762, 3881, 3916, 3923, 3932, 4095]
p = [0, 10, 38, 50, 66, 100, 138, 219, 501, 1000, 3162, 5012, 5495, 6310, 100000]
if v <= a[0]: return p[0]
for i in range(len(a)-1):
if a[i] <= v <= a[i+1]:
return int(p[i] + (v-a[i])*(p[i+1]-p[i])/(a[i+1]-a[i]))
return 0
def enviar_email():
oled.fill(0); oled.text("ENVIANDO...", 20, 30); oled.show()
gc.collect()
m = (f"From: {REMETENTE}\r\nTo: {DESTINO}\r\n"
f"Subject: Relatorio UMC\r\n\r\n"
f"Estacao OK\nTemp: {st['t']}C\nUmid: {st['u']}%")
try:
s = socket.socket()
s.settimeout(15)
s.connect(socket.getaddrinfo("smtp.gmail.com", 465)[0][-1])
s = ssl.wrap_socket(s)
s.readline()
s.write(b"EHLO esp32\r\n"); s.readline()
s.write(b"AUTH LOGIN\r\n"); s.readline()
s.write(ubinascii.b2a_base64(REMETENTE.encode())[:-1]+b"\r\n"); s.readline()
s.write(ubinascii.b2a_base64(SENHA_APP.encode())[:-1]+b"\r\n")
if b"235" in s.readline():
s.write(f"MAIL FROM:<{REMETENTE}>\r\n".encode()); s.readline()
s.write(f"RCPT TO:<{DESTINO}>\r\n".encode()); s.readline()
s.write(b"DATA\r\n"); s.readline()
s.write(m.encode() + b"\r\n.\r\n"); s.readline()
s.write(b"QUIT\r\n"); s.close()
oled.fill(0); oled.text("EMAIL OK!", 30, 30); oled.show()
return True
s.close()
except: return False
# --- CONEXÃO ---
oled.fill(0); oled.text("CONECTANDO...", 0, 30); oled.show()
w = network.WLAN(network.STA_IF); w.active(True); w.connect('Wokwi-GUEST', '')
while not w.isconnected(): time.sleep(0.5)
try: ntptime.settime()
except: pass
last_s = time.time(); sent = False
# --- LOOP PRINCIPAL ---
while True:
try:
t_br = time.localtime(time.time() - 10800)
dh = f"{t_br[3]:02d}:{t_br[4]:02d}:{t_br[5]:02d}"
if t_br[3] == HORA_ALVO and t_br[4] == MIN_ALVO and not sent:
if enviar_email(): sent = True
elif t_br[3] != HORA_ALVO: sent = False
try:
sensor_dht.measure()
st['t'], st['u'] = sensor_dht.temperature(), sensor_dht.humidity()
except: pass
st['g'] = get_gas(mq2.read())
oled.fill(0)
oled.text(dh, 70, 0)
if st['tela'] == 0:
oled.text(f"Temp: {st['t']:.1f}C", 0, 25)
oled.text(f"Umid: {st['u']:.1f}%", 0, 45)
else:
oled.text(f"Gas: {st['g']} ppm", 0, 30)
oled.show()
if time.time() - last_s >= 40:
import urequests
try:
url = "https://script.google.com/macros/s/AKfycbw8WDhI_oV5Z1X8_sUb0UtdDRgDe46VzhaJB5-FPmBRtZajZrq-mYcWS24nYVahHaOnmg/exec"
urequests.post(url, json={"t": st['t'], "u": st['u']}).close()
except: pass
last_s = time.time(); gc.collect()
except: pass
time.sleep(0.5)