import network
import time
import machine
from umqtt.simple import MQTTClient
from dht import DHT22
import ujson


# Konfigurasi WiFi
SSID = "Wokwi-GUEST"
PASSWORD = ""

# Konfigurasi MQTT
MQTT_BROKER = "broker.emqx.io"
TOPIC_PUBLISH = "/uni075/muhammad_hafizh_faiqunnabil/data_sensor"
TOPIC_SUBSCRIBE = "/uni075/muhammad_hafizh_faiqunnabil/aktuasi_led"

# Inisialisasi pin
led = machine.Pin(2, machine.Pin.OUT)
buzzer = machine.Pin(25, machine.Pin.OUT)
button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_DOWN)
potentiometer = machine.ADC(machine.Pin(34))
potentiometer.atten(machine.ADC.ATTN_11DB)
dht_sensor = DHT22(machine.Pin(26))

# Fungsi koneksi WiFi
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(SSID, PASSWORD)
    while not wlan.isconnected():
        print("Menghubungkan ke WiFi...")
        time.sleep(1)
    print("WiFi terhubung!")
    print("IP Address:", wlan.ifconfig()[0])

# Fungsi callback MQTT
def on_message(topic, msg):
    print("Pesan diterima:", topic.decode(), msg.decode())
    if topic.decode() == TOPIC_SUBSCRIBE:
        try:
            data = ujson.loads(msg.decode())
            if data["msg"].upper() == "ON":
                led.on()
                print("LED dinyalakan")
            elif data["msg"].upper() == "OFF":
                led.off()
                print("LED dimatikan")
            else:
                print("Pesan tidak valid:", data["msg"])
        except ValueError as e:
            print("Gagal mem-parsing JSON:", e)

# Setup MQTT
client = MQTTClient("ESP32", MQTT_BROKER)
client.set_callback(on_message)

# Main Function
def main():
    connect_wifi()
    client.connect()
    client.subscribe(TOPIC_SUBSCRIBE)
    print("Subscribed ke topik:", TOPIC_SUBSCRIBE)
    
    last_publish = time.ticks_ms()

    while True:
        client.check_msg()

        # Baca nilai potensiometer
        pot_value = potentiometer.read()
        pot_percentage = (pot_value / 4095) * 100

        # Baca sensor DHT22
        try:
            dht_sensor.measure()
            temperature = dht_sensor.temperature()
            humidity = dht_sensor.humidity()
        except OSError as e:
            print("Gagal membaca DHT22:", e)
            temperature = None
            humidity = None

        # Publish data sensor ke MQTT setiap 5 detik
        if time.ticks_diff(time.ticks_ms(), last_publish) > 5000:
            payload = {
                "potentiometer": pot_percentage,
                "temperature": temperature,
                "humidity": humidity
            }
            client.publish(TOPIC_PUBLISH, str(payload))
            print("Data sensor dikirim:", payload)
            last_publish = time.ticks_ms()

        # Kontrol LED dengan tombol
        if button.value() == 1:
            led.toggle()
            buzzer.on()
            time.sleep(0.1)
            buzzer.off()

try:
    main()
except KeyboardInterrupt:
    print("Program dihentikan")
    client.disconnect()