import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "demoErick"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_SENSOR = "/UNI173/julius_calvin_kurniadi/data_sensor"
MQTT_TOPIC_LED = "/UNI173/julius_calvin_kurniadi/aktuasi_led"
# Configure sensors
sensor1 = dht.DHT22(Pin(15))
sensor2 = dht.DHT22(Pin(2))
# Configure LED pin
LED_PIN = 4 # Change as needed
led = Pin(LED_PIN, Pin.OUT)
led.off() # Ensure the LED is off at startup
# Connect to Wi-Fi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST') # No password needed for Wokwi-GUEST
# Wait for connection with a timeout
timeout = 10 # seconds
start_time = time.time()
while not sta_if.isconnected():
if time.time() - start_time > timeout:
print("Failed to connect to WiFi")
break
print(".", end="")
time.sleep(0.1)
else:
print(" Connected!")
# Callback function for receiving LED control messages
def led_callback(topic, msg):
print(f"Message received on topic {topic.decode()}: {msg.decode()}")
if msg.decode().strip().lower() == "on":
led.on()
print("LED turned ON")
elif msg.decode().strip().lower() == "off":
led.off()
print("LED turned OFF")
# Connect to MQTT server
print("Connecting to MQTT server... ", end="")
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(led_callback) # Set the callback function
client.connect()
print("Connected!")
except Exception as e:
print(f"Failed to connect to MQTT server: {e}")
raise
# Subscribe to the LED control topic
client.subscribe(MQTT_TOPIC_LED)
print(f"Subscribed to topic: {MQTT_TOPIC_LED}")
# Monitor and publish sensor data
prev_weather = ""
try:
while True:
# Handle incoming messages
client.check_msg()
# Measure sensor data
try:
sensor1.measure()
sensor2.measure()
# Prepare the message
message = ujson.dumps({
"temp1": sensor1.temperature(),
"humidity1": sensor1.humidity(),
"temp2": sensor2.temperature(),
"humidity2": sensor2.humidity(),
})
# Publish sensor data only if it changes
if message != prev_weather:
print("Updated!")
print(f"Reporting to MQTT topic {MQTT_TOPIC_SENSOR}: {message}")
client.publish(MQTT_TOPIC_SENSOR, message.encode())
prev_weather = message
except Exception as e:
print(f"Sensor error: {e}")
time.sleep(1) # Adjust as needed
except KeyboardInterrupt:
print("Disconnecting...")
finally:
client.disconnect()
print("Disconnected!")