import network
import time
from machine import Pin
from utime import sleep
import dht
import ujson
from umqtt.simple import MQTTClient
# Parameter MQTT Server
MQTT_CLIENT_ID = "testing"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_PUB = "/405_found/Mumtaza/sensor_data"
MQTT_TOPIC_SUB = "/405_found/Mumtaza/aktuasi_led"
# Inisialisasi
sensor = dht.DHT22(Pin(15))
led_b = Pin(12, Pin.OUT)
led_u = Pin(33, Pin.OUT)
prev_led_b_state = None
prev_led_u_state = None
# Callback MQTT
def mqtt_callback(topic, msg):
global prev_led_b_state, prev_led_u_state
print(f"Pesan diterima dari {topic}: {msg}")
try:
msg_dict = ujson.loads(msg.decode())
command = msg_dict.get("msg", "").strip().lower()
target = msg_dict.get("target", "").strip().lower()
on_commands = ["on", "turn on"]
off_commands = ["off", "turn off"]
if target == "blue":
if command in on_commands and prev_led_b_state != "on":
led_b.on()
response = {"status": "LED Biru menyala"}
prev_led_b_state = "on"
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command in off_commands and prev_led_b_state != "off":
led_b.off()
response = {"status": "LED Biru mati"}
prev_led_b_state = "off"
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif target == "purple":
if command in on_commands and prev_led_u_state != "on":
led_u.on()
response = {"status": "LED Ungu menyala"}
prev_led_u_state = "on"
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command in off_commands and prev_led_u_state != "off":
led_u.off()
response = {"status": "LED Ungu mati"}
prev_led_u_state = "off"
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
except ValueError:
print("Error: Format pesan bukan JSON valid")
except Exception as e:
print(f"Error dalam pemrosesan MQTT: {e}")
# Koneksi ke 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!")
# 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
sensor.measure()
# Format data dalam JSON
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.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(1)