import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "SMART-HOME"
MQTT_USER1_CLIENT_ID = "USER1"
MQTT_BROKER = "broker.emqx.io"
MQTT_PORT = 1883
MQTT_USER = "your_username" # Update with your username
MQTT_PASSWORD = "your_password" # Update with your password
MQTT_STATUS_TOPIC = "home/status"
MQTT_PRIVATE_TOPIC = "home/private"
MQTT_USER1_TOPIC = "home/user1"
# DHT Sensor Initialization
sensor = dht.DHT22(Pin(15))
# Connect to 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!")
# MQTT Callback Function to Handle Incoming Messages
def message_callback(topic, msg):
print("Received message from topic {}: {}".format(topic.decode(), msg.decode()))
# Add your message processing logic here
# Connect to MQTT Broker with Authentication for SMART-HOME Client
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(message_callback)
client.connect()
print("Connected to MQTT broker!")
# Subscribe to the Private Topic for SMART-HOME Client
client.subscribe(MQTT_PRIVATE_TOPIC)
print("Subscribed to private topic: {}".format(MQTT_PRIVATE_TOPIC))
# Connect to MQTT Broker with Authentication for USER1 Client
print("Connecting USER1 to MQTT server... ", end="")
user1_client = MQTTClient(MQTT_USER1_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
user1_client.set_callback(message_callback)
user1_client.connect()
print("USER1 Connected to MQTT broker!")
# Subscribe to the Private Topic for USER1 Client
user1_client.subscribe(MQTT_USER1_TOPIC)
print("USER1 Subscribed to topic: {}".format(MQTT_USER1_TOPIC))
# Indicate USER1 is connected
connection_message = "USER1 has connected"
client.publish(MQTT_PRIVATE_TOPIC, connection_message)
print("Published connection message to {}: {}".format(MQTT_PRIVATE_TOPIC, connection_message))
# Main Loop to Publish Sensor Data
prev_weather = ""
while True:
try:
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_STATUS_TOPIC, message))
client.publish(MQTT_STATUS_TOPIC, message)
prev_weather = message
else:
print("No change")
# Check for new messages for both clients
client.check_msg()
user1_client.check_msg()
except OSError as e:
print("Failed to read sensor.", e)
time.sleep(1)