# Importação de Bibliotecas
from wifi_lib import conecta
from umqttsimple import MQTTClient
from machine import Pin, I2C, PWM
import ssd1306
import dht
import time

# Configurações do MQTT
mqtt_server = "broker.mqttdashboard.com"  
mqtt_port = 1883
mqtt_user = ""  
mqtt_password = ""  
mqtt_client_id = "clientId-dT8PhdfWfT-wokwi"
mqtt_temp_topic = "pucpr/wainy/temperatura"
mqtt_hum_topic = "pucpr/wainy/umidade"

# Conectar ao Wi-Fi
print("Conectando...")
station = conecta("Wokwi-GUEST", "")
if not station.isconnected():
    print("Falha na conexão")
else:
    print("Conectado ao Wi-Fi")
    print("Conectando ao Broker MQTT")
    client = MQTTClient(mqtt_client_id, mqtt_server, mqtt_port, mqtt_user, mqtt_password)
    client.connect()

sensor = dht.DHT22(Pin(15))
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)  
buzzer_pin = Pin(23, Pin.OUT)  

# Loop Principal
while True:
    try:
        sensor.measure()
        temp = sensor.temperature()  
        hum = sensor.humidity()    

        oled.fill(0)

        # Publicar os dados de temperatura e umidade no tópico do HiveMQ
        client.publish("pucpr/wainy/temperatura", str(temp)) 
        client.publish("pucpr/wainy/umidade", str(hum)) 

        # Exibir temperatura e umidade no display OLED
        oled.text("Temp: {}C".format(temp), 0, 0)
        oled.text("Umidade: {}%".format(hum), 0, 10)

        # Verificar as condições
        if temp > 26 and hum < 50:
            oled.text("Temperatura alta e", 0, 20)
            oled.text("umidade baixa", 0, 30)
            oled.text("Hidrate-se!", 0, 40)
            buzzer_pin.on()  
        elif temp > 26:
            oled.text("Temperatura alta", 0, 20)
            oled.text("Hidrate-se!", 0, 30)
            buzzer_pin.on()  
        elif hum < 50:
            oled.text("Umidade baixa", 0, 20)
            oled.text("Hidrate-se!", 0, 30)
            buzzer_pin.on()  
        else:
            oled.text("Clima ok", 0, 20)
            buzzer_pin.off()  

        # Atualizar o display com o conteúdo
        oled.show()

        time.sleep(2)

    except OSError as e:
        print("Erro ao ler o sensor:", e)