import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "renaldiendrawansic6"
MQTT_BROKER = "broker.emqx.io"
MQTT_TOPIC_SENSOR = "/BRAINWAVE/renaldi_endrawan/data_sensor"
MQTT_TOPIC_LED = "/BRAINWAVE/renaldi_endrawan/aktuasi_led"
led = Pin(4, Pin.OUT)
sensor = dht.DHT22(Pin(5))
# WiFi Connection
def connect_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.5)
print("Connected! 🎉")
connect_wifi()
# MQTT Connection
def connect_mqtt():
print("Connecting to MQTT server... 🧐", end=" ")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, keepalive=60)
client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_TOPIC_LED)
print("Connected! ✅")
return client
def on_message(topic, msg):
print(f"Message received on topic {topic}: {msg} 💬")
try:
data = ujson.loads(msg)
if data.get("msg") == "on":
led.on()
print("LED is ON 🔆")
elif data.get("msg") == "off":
led.off()
print("LED is OFF 💡")
except Exception as e:
print(f"Error processing message: {e} ⚠️")
client = connect_mqtt()
# Main loop
prev_weather = ""
led_state = None # Track current LED state (None, "on", "off")
while True:
try:
# Reconnect WiFi if disconnected
if not network.WLAN(network.STA_IF).isconnected():
connect_wifi()
# Read DHT22 sensor
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# Prepare message
message = ujson.dumps({"temp": temperature, "humidity": humidity})
# Publish sensor data
if message != prev_weather:
print(f"Publishing to {MQTT_TOPIC_SENSOR}: {message} 🌡️💧")
client.publish(MQTT_TOPIC_SENSOR, message)
prev_weather = message
# Check conditions for LED actuation
if 16 <= temperature <= 25 and 5 <= humidity <= 19:
if led_state != "on":
led_message = ujson.dumps({"msg": "on"})
print(f"Publishing to {MQTT_TOPIC_LED}: {led_message} 🔆")
client.publish(MQTT_TOPIC_LED, led_message)
led_state = "on"
else:
if led_state != "off":
led_message = ujson.dumps({"msg": "off"})
print(f"Publishing to {MQTT_TOPIC_LED}: {led_message} 💡")
client.publish(MQTT_TOPIC_LED, led_message)
led_state = "off"
# Handle incoming messages
client.check_msg()
# Delay to prevent excessive MQTT messages
time.sleep(2)
except Exception as e:
print(f"Error: {e} ❌")
time.sleep(5) # Prevent tight-loop in case of failure