# UNI405-405 found-Mohammad Bayu Rizki

# MQTT Server Parameters
MQTT_CLIENT_ID = "project_405found_MohammadBayuRizki"
MQTT_BROKER    = "broker.emqx.io"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_PUB = "/405_found/Mohammad_Bayu_Rizki/data_sensor"
MQTT_TOPIC_SUB = "/405_found/Mohammad_Bayu_Rizki/aktuasi_led"

sensor1 = dht.DHT22(Pin(15))
sensor2 = dht.DHT22(Pin(2))
led = Pin(12, Pin.OUT)
led_y = Pin(14, Pin.OUT)
led_g = Pin(13, Pin.OUT)
prev_led_state = None  


# Fungsi Callback MQTT : menangani pesan yang diterima
def mqtt_callback(topic, msg):
    global prev_led_state  
    print(f"Pesan diterima dari {topic}: {msg}")

    try:
        # Parsing JSON
        msg_dict = ujson.loads(msg.decode())  
        command = msg_dict.get("msg", "").strip().lower()  

        # Perintah yang dikenali untuk menyalakan dan mematikan LED
        on_commands = ["on", "turn on"]
        off_commands = ["off", "turn off"]

        if command in on_commands and prev_led_state != "on":
            led.on()
            led_y.on()
            led_g.on()  
            response = {"status": "LED berhasil menyala"}
            prev_led_state = "on"  
            print(response["status"])
            client.publish(MQTT_TOPIC_SUB, ujson.dumps(response)) 

        elif command in off_commands and prev_led_state != "off":
            led.off()
            led_y.off()
            led_g.off()  
            response = {"status": "LED berhasil mati"}
            prev_led_state = "off"  
            print(response["status"])
            client.publish(MQTT_TOPIC_SUB, ujson.dumps(response)) 

        else:
            print("No change")  

    except ValueError:
        print("Error: Format pesan bukan JSON valid")
    except Exception as e:
        print(f"Error dalam pemrosesan MQTT: {e}")


# Koneksi ke MQTT Server
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(MQTT_TOPIC_SUB)
print("Connected & Subscribed!")

# Loop utama
prev_weather = ""
while True:
    print("Measuring weather conditions... ", end="")
    
    # Membaca data dari sensor DHT22
    sensor1.measure() 
    sensor2.measure() 

    # Format data dalam JSON
    message = ujson.dumps({
        "temp1": sensor1.temperature(),
        "humidity1": sensor1.humidity(),
        "temp2": sensor2.temperature(),
        "humidity2": sensor2.humidity(),
    })

    # Publish data hanya jika ada perubahan
    if message != prev_weather:
        print("Updated!")
        print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC_PUB, message))
        client.publish(MQTT_TOPIC_PUB, message)
        prev_weather = message
    else:
        print("No change")

    # Periksa pesan MQTT yang masuk
    client.check_msg()

    time.sleep(3)