import network
import time
import dht
import ujson
from machine import Pin, ADC, time_pulse_us
from umqtt.simple import MQTTClient

# MQTT Server Parameters
CLIENT_ID    = "HSC293-Assignment-demo"
BROKER       = "broker.emqx.io"
USER         = ""
PASSWORD     = ""
TOPIC_SUBREK = "/HSC293/Muhammad_Faqih_Maulana_Riadi/aktuasi_led"
TOPIC_UTAMA  = "/HSC293/Muhammad_Faqih_Maulana_Riadi/data_sensor"

#Pin Setiap Komponen Sensor dan LED
dht_sensor = dht.DHT22(Pin(25))
LDR_sensor = ADC(Pin(34))
lampu = Pin(3, Pin.OUT)
Trig = Pin(23, Pin.OUT)
Echo = Pin(22, Pin.IN)

#Sambung Wifi
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!")

#Menyambungkan ke MQTT
def connect_MQTT():
  print("Connecting to MQTT server... ", end="")
  client = MQTTClient(CLIENT_ID, BROKER, user=USER, password=PASSWORD)
  client.set_callback(Subrek)
  client.connect()
  client.subscribe(TOPIC_SUBREK)
  print("Connected!")
  return client

# Subrek MQTT
def Subrek(topic, msg):
  print("Pesan : ", msg)
  try:
    # JSON
    pesan = ujson.loads(msg)
    if pesan.get("msg")=="ON":
      lampu.on()
    elif pesan.get("msg")=="OFF":
      lampu.off()
  except Kecuali as e:
    print("Gagal!", e)

# Status Lampu
def lamp():
    if x == 1:
        return "Menyala"
    else:
        return "Padam"

# Perhitungan Ultrasonic
def jaraknya():
    Trig.off()
    time.sleep_us(2)
    Trig.on()
    time.sleep_us(10)
    Trig.off()

    lama = time_pulse_us(Echo, 1, 30000)
    if lama < 0:
        return None
    
    jarak = (lama / 2) * 0.0343
    return jarak 

# Definisi tambahan
client = connect_MQTT()
cuaca = ""
nilai_LDR = LDR_sensor.read()
x = lampu.value()
y = lamp()
jauh = jaraknya()

# Wujud Aseli
while True:
  client.check_msg()

  print("Status Lampu: ", y)
  print(f"Jarak benda: {jauh}")
  print("Nilai LDR : ", nilai_LDR)
  print("Mengidentifikasi cuaca... ", end="")
  dht_sensor.measure() 
  message = ujson.dumps({
    "Suhu": dht_sensor.temperature(),
    "Kelembapan": dht_sensor.humidity(),
    "Jarak dalam cm": jauh,
    "Lampu": y,
  })
  
  if message != cuaca:
    print("Updated!")
    print("Reporting to MQTT topic {}: {}".format(TOPIC_UTAMA, message))
    client.publish(TOPIC_UTAMA, message)
    cuaca = message
  else:
    print("Tidak ada perubahan")
  time.sleep(1)