# Menghidupkan secara bersamaan
# Mematikan lampu led secara bersamaan
# Blink secara bersamaan
# Jika blink stop, maka kedua led langsung mati secara bersamaan
import network
import time
from machine import Pin
from utime import sleep
import dht
import ujson
from umqtt.simple import MQTTClient
import _thread # Tambahan untuk menjalankan blink secara terpisah
# MQTT Server Parameters
MQTT_CLIENT_ID = "testing"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_PUB = "/taza/testing/data"
MQTT_TOPIC_SUB = "/taza/testing/led"
sensor1 = 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
is_blinking = False # Variabel untuk mengontrol kedipan
# Fungsi untuk membuat LED berkedip
def blink_leds():
global is_blinking
while is_blinking:
led_b.on()
led_u.on()
time.sleep(0.5)
led_b.off()
led_u.off()
time.sleep(0.5)
def mqtt_callback(topic, msg):
global prev_led_b_state, prev_led_u_state, is_blinking
print(f"Pesan diterima dari {topic}: {msg}")
try:
msg_dict = ujson.loads(msg.decode())
command = msg_dict.get("msg", "").strip().lower()
if command == "blink":
is_blinking = True
response = {"status": "LED mulai berkedip"}
_thread.start_new_thread(blink_leds, ())
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command == "stop":
is_blinking = False
led_b.off()
led_u.off()
response = {"status": "LED berhenti berkedip"}
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command in ["on", "turn on"]:
is_blinking = False # Hentikan kedipan jika sedang berjalan
led_b.on()
led_u.on()
response = {"status": "Kedua LED menyala"}
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command in ["off", "turn off"]:
is_blinking = False # Hentikan kedipan jika sedang berjalan
led_b.off()
led_u.off()
response = {"status": "Kedua LED mati"}
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="")
sensor1.measure()
message = ujson.dumps({
"temp1": sensor1.temperature(),
"humidity1": sensor1.humidity(),
})
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")
client.check_msg()
time.sleep(3)