import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# --- Configuration ---
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
MQTT_CLIENT_ID = "micropython-sensor-data"
MQTT_BROKER = "sensor-micro.cloud.shiftr.io"
MQTT_USER = "sensor-micro"
MQTT_PASSWORD = "ulcB4x2V9ghmWzTo"
PUBLISH_TOPIC = "wokwi-sensor"
SUBSCRIBE_TOPIC = "device/control"
DHT_PIN = 15
LED1_PIN = 33
LED2_PIN = 32
MEASURE_INTERVAL = 1 # seconds
# --- Initialize Devices ---
sensor = dht.DHT22(Pin(DHT_PIN))
led1 = Pin(LED1_PIN, Pin.OUT)
led2 = Pin(LED2_PIN, Pin.OUT)
# --- Connect to WiFi ---
def connect_wifi():
print("Connecting to WiFi", end="")
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect(WIFI_SSID, WIFI_PASSWORD)
while not sta.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# --- Handle Incoming Messages ---
def handle_message(topic, msg):
print(f"Received message on {topic}: {msg}")
try:
command = msg.decode().lower()
if command == "led 1 on":
led1.value(1)
print("LED 1 ON")
elif command == "led 1 off":
led1.value(0)
print("LED 1 OFF")
elif command == "led 2 on":
led2.value(1)
print("LED 2 ON")
elif command == "led 2 off":
led2.value(0)
print("LED 2 OFF")
else:
print("Unknown command")
except Exception as e:
print("Error handling message:", e)
# --- Connect to MQTT ---
def connect_mqtt():
print("Connecting to MQTT server... ", end="")
client = MQTTClient(
client_id=MQTT_CLIENT_ID,
server=MQTT_BROKER,
user=MQTT_USER,
password=MQTT_PASSWORD
)
client.set_callback(handle_message)
client.connect()
client.subscribe(SUBSCRIBE_TOPIC)
print("Connected and subscribed to control topic!")
return client
# --- Main Loop ---
def main():
connect_wifi()
client = connect_mqtt()
prev_message = ""
while True:
try:
# Check for incoming messages (non-blocking)
client.check_msg()
# Sensor update
sensor.measure()
message = ujson.dumps({
"temperature": sensor.temperature(),
"humidity": sensor.humidity()
})
if message != prev_message:
print(f"Reporting to MQTT topic {PUBLISH_TOPIC}: {message}")
client.publish(PUBLISH_TOPIC, message)
prev_message = message
else:
print("No sensor change")
time.sleep(MEASURE_INTERVAL)
except Exception as e:
print("Error in main loop:", e)
time.sleep(5)
# --- Run Program ---
if __name__ == "__main__":
main()