import network
import time
from machine import Pin
from machine import PWM
import dht
from umqtt.simple import MQTTClient

sensor = dht.DHT22(Pin(15))
led_incendio = Pin(4, Pin.OUT)
sensor_movimento = Pin(23, Pin.IN)
buzzer = PWM(Pin(22))
led_emergencia = Pin(32, Pin.OUT)

# Configuração do Buzzer
buzzer.freq(1000)  
buzzer.duty(0)     

# MQTT Server Parameters
MQTT_CLIENT_ID = "ciberfisicos2024"
MQTT_BROKER    = "broker.mqttdashboard.com"
MQTT_TOPIC_SEND = "ciberfisicos.2024/enviar"
MQTT_TOPIC_RECEIVE = "ciberfisicos.2024/receber"
MQTT_USER      = "hugoffs"
MQTT_PASSWORD  = "12345"

# Função com a resposta do tópico selecionado
def callback(topic, msg):
    print("Mensagem recebida: ", msg.decode())
    client.publish(MQTT_TOPIC_RECEIVE, "Funcionou!!!!!")

# Comunicação
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
    print(".", end="")
    time.sleep(0.1)
print(" Connected!")

print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)

# Criando retorno de informação
client.set_callback(callback)

# Conectando no cliente
client.connect()
print("Connected!")
# Fazendo inscrição no tópico "mensagens" para receber mensagens
client.subscribe(MQTT_TOPIC_RECEIVE)
# Publicação da mensagem que será enviada
client.publish(MQTT_TOPIC_SEND, "Teste")

def verificar_temperatura():
    incendio = 43
    sensor.measure()
    time.sleep(1)
    temperatura_atual = sensor.temperature()
    if temperatura_atual >= incendio:
        return True
    else:
        return False

def movimento(pin):
    print("Movimento Detectado: Ligando Luzes de Emergência:")
    client.publish(MQTT_TOPIC_SEND, "Movimento Detectado: Ligando Luzes de Emergência")
    led_emergencia.value(1)
    time.sleep(10)
    led_emergencia.value(0)

sensor_movimento.irq(trigger=Pin.IRQ_RISING, handler=movimento)

while True:
    while verificar_temperatura():
        print("Fogo")
        client.publish(MQTT_TOPIC_SEND, "Fogo")

        for i in range(5):
            led_incendio.value(1)
            buzzer.duty(512)  # Liga o buzzer
            time.sleep(1)
            led_incendio.value(0)
            buzzer.duty(0)    # Desliga o buzzer
            time.sleep(1)