import network
import time
from machine import Pin
import urequests as requests
from mqtt import MQTTClient
import json

# Konfigurasi WiFi
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# Konfigurasi MQTT
mqtt_server = "broker.hivemq.com"
client_id = "wokwi-esp32"
topic_pub = b"hsc123/data_sensor"
topic_sub = b"hsc123/aktuasi_led"

# Setup GPIO
led = Pin(2, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)

def wifi_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('Connecting to WiFi...')
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        while not wlan.isconnected():
            pass
    print('Connected to WiFi')
    print('Network config:', wlan.ifconfig())

def sub_cb(topic, msg):
    print(f'Received message: {msg} on topic: {topic}')
    if msg == b"on":
        led.value(1)
        print('LED ON')
    elif msg == b"off":
        led.value(0)
        print('LED OFF')

def main():
    print("Connecting to WiFi...")
    wifi_connect()
    
    print("Connecting to MQTT...")
    client = MQTTClient(client_id, mqtt_server, port=1883)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic_sub)
    print("Connected to MQTT Broker")
    
    while True:
        try:
            # Read button state
            button_state = button.value()
            
            # Publish sensor data
            message = json.dumps({
                "sensor": "button",
                "value": button_state
            })
            client.publish(topic_pub, message)
            print(f"Published: {message}")
            
            # Check for messages
            client.check_msg()
            
            time.sleep(1)
            
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(1)

if __name__ == "__main__":
    main()