import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
# MQTT Parameters
client_id = "ahmad-led"
broker = "broker.emqx.io"
user = ""
password = ""
topic = "/NOVA/ahmadatoillah/aktuasi_led"
# WIFI Connection
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!")
# MQTT Server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(client_id, broker, user=user, password=password)
client.connect()
print('Connected')
# SETUP LAMPU
led = Pin(5, Pin.OUT)
led.on()
led_state = True
# SETUP LISTENER
def listener(b_topic, b_msg):
global led_state
topic = str(b_topic, 'utf-8')
msg = str(b_msg, 'utf-8')
print(msg)
if msg.lower() == 'lampu nyala':
led_state = True
led.on()
client.publish(topic, f"Kondisi lampu: {'NYALA' if led_state else 'MATI'}")
elif msg.lower() == 'lampu mati':
led_state = False
led.off()
client.publish(topic, f"Kondisi lampu: {'NYALA' if led_state else 'MATI'}")
elif msg.lower() == 'lampu toggle':
if led_state:
led_state = False
led.off()
else:
led_state = True
led.on()
client.publish(topic, f"Kondisi lampu: {'NYALA' if led_state else 'MATI'}")
elif msg.lower() in ['help', 'h']:
client.publish(topic, """
Available command:
- lampu nyala
- lampu mati
- lampu toggle
- help
Type 'help' to show this text again!
""")
client.set_callback(listener)
client.subscribe(topic)
client.publish(topic, """
Program Launch!
Kondisi lampu saat ini: NYALA
Available command:
- lampu nyala
- lampu mati
- lampu toggle
- help
Type 'help' to show this text again!
""")
while True:
client.wait_msg()