# Jika msg on, lampu hidup secara bersamaan
# Jika msg off, lampu hidup secara bersamaan
# Jika msg blink, lampu akan hidup kedap kedip secara bergantian
# Jika msg stop, maka lampu akan kembali ke perintah sebelum blink. Jika sempat off, maka mati. Jika sempat on, maka hidup
import network
import time
from machine import Pin
from utime import sleep
import dht
import ujson
from umqtt.simple import MQTTClient
import _thread
# 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_state = None
is_blinking = False
last_state = "off" # Menyimpan status terakhir sebelum blink
# Fungsi untuk membuat LED berkedip bergantian
def alternate_blink():
global is_blinking
while is_blinking:
# Biru nyala, Ungu mati
led_b.on()
led_u.off()
time.sleep(0.5)
# Biru mati, Ungu nyala
led_b.off()
led_u.on()
time.sleep(0.5)
def restore_state():
if last_state == "on":
led_b.on()
led_u.on()
else:
led_b.off()
led_u.off()
def mqtt_callback(topic, msg):
global prev_led_state, is_blinking, last_state
print(f"Pesan diterima dari {topic}: {msg}")
try:
msg_dict = ujson.loads(msg.decode())
command = msg_dict.get("msg", "").strip().lower()
if command in ["on", "turn on"]:
is_blinking = False # Hentikan kedipan jika sedang berjalan
time.sleep(0.1) # Beri waktu thread blink untuk berhenti
led_b.on()
led_u.on()
last_state = "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
time.sleep(0.1) # Beri waktu thread blink untuk berhenti
led_b.off()
led_u.off()
last_state = "off"
response = {"status": "Kedua LED mati"}
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command == "blink":
is_blinking = True
response = {"status": "LED berkedip bergantian"}
_thread.start_new_thread(alternate_blink, ())
client.publish(MQTT_TOPIC_SUB, ujson.dumps(response))
elif command == "stop":
is_blinking = False
time.sleep(0.1) # Beri waktu thread blink untuk berhenti
restore_state() # Kembalikan ke status sebelum blink
response = {"status": f"LED kembali ke status {last_state}"}
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)