import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient

# MQTT Server Parameters
MQTT_CLIENT_ID     = "ESP"
MQTT_BROKER        = "broker.emqx.io"
MQTT_USER          = ""
MQTT_PASSWORD      = ""
MQTT_TOPIC_AKTU    = "/UNI322/Eka_Hernanda_Fulca/aktuasi_led"
MQTT_TOPIC_SENDATA = "/UNI322/Eka_Hernanda_Fulca/data_sensor"

# Pin lampu
pin_merah = Pin(18, Pin.OUT)
pin_hijau = Pin(19, Pin.OUT)

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 server1... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connecting to MQTT server2... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")

# Data store
cmd_lampu = ""
lampu_merah = 0
lampu_hijau = 0

def lampu_ctrl(cmd):
    global lampu_merah
    global lampu_hijau
    if cmd == "merah nyala":
        lampu_merah = 1
        pin_merah.on()
    elif cmd == "merah mati":
        lampu_merah = 0
        pin_merah.off()
    elif cmd == "hijau nyala":
        lampu_hijau = 1
        pin_hijau.on()
    elif cmd == "hijau mati":
        lampu_hijau = 0
        pin_hijau.off()

def sub_cb(topic, msg):
    global cmd_lampu
    try:
        payload = ujson.loads(msg)
        cmd_lampu = payload["msg"]  # Memastikan 'msg' ada di JSON payload
        print(f"Pesan diterima: {cmd_lampu}")
        lampu_ctrl(cmd_lampu)
    except KeyError:
        print("Key 'msg' tidak ditemukan dalam pesan:")
        print(payload)
    except ValueError:
        print("JSON payload tidak valid:\n", msg)

client.set_callback(sub_cb)
client.subscribe(MQTT_TOPIC_AKTU, qos=0)
print("Subscribed to topic!")

prev_pesan = ""
while True:
  print("Menunggu perintah... ", end="")
  time.sleep(3)
  #client.wait_msg()  # Blocking check for new messages

  message = ujson.dumps({
    "Status Lampu": {
        "Merah" : lampu_merah,
        "Hijau" : lampu_hijau
    }
  })

  if message != prev_pesan:
    print("Updated!")
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC_AKTU, message))
    client.publish(MQTT_TOPIC_AKTU, message, qos=0)
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC_SENDATA, message))
    client.publish(MQTT_TOPIC_SENDATA, message, qos=0)
    prev_pesan = message
  else:
    print("Belum ada perintah")
  time.sleep(1)