Implement a Python script to control smart home devices via MQTT.
- User
Implement a Python script to control smart home devices via MQTT.
Assistant
Implement a Python script to control smart home devices via MQTT.
The user wants a Python script to control smart home devices using MQTT. To provide a comprehensive answer, I need to cover:
SmartHomeController).paho.mqtt.client.on_connect, on_message).test.mosquitto.org or hivemq) or set up a local one (Mosquitto). I'll stick to broker.emqx.io or test.mosquitto.org for the example so they can run it immediately.Plan:
pip install paho-mqttmqtt_client.py: The main script.connect()on_connect: Subscribe to topics.on_message: Parse incoming data (simulating device feedback).publish_command: Send JSON payloads to specific topics.Refining the Code:
paho-mqtt version 2.0.0+ API (CallbackAPIVersion.VERSION2) because version 1.6 is deprecated and causes errors in newer Python versions.Drafting the Script (Mental or Scratchpad):
import paho.mqtt.client as mqtt
import json
import time
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
client.subscribe("home/livingroom/light/status")
def on_message(client, userdata, msg):
print(f"Topic: {msg.topic}, Message: {msg.payload.decode()}")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
# Loop start
client.loop_start()
# Control logic
client.publish("home/livingroom/light/set", json.dumps({"state": "ON"}))
Adding Value:
.../set vs .../status pattern (common pattern).requirements.txt hint.Final Output Structure:
on_connect, on_message, and publish sections.Let's write the actual Python code now, ensuring I use the new Paho-MQTT API signature to avoid the common DeprecationWarning or AttributeError seen in recent updates.
Self-Correction during drafting: The user asked for control. That implies sending commands. But a good controller also listens for state changes. I will implement both directions.
Let's proceed with generating the response.
Here is a complete, robust Python script to control smart home devices using the paho-mqtt library.
You will need the Paho MQTT library. Install it via pip:
pip install paho-mqtt
This script sets up an MQTT client that can both publish commands (to turn devices on/off) and subscribe to status updates (to listen for changes).
I have designed it to simulate a smart light, but you can swap out the TOPICS and PAYLOADS to match your specific smart home devices (like Tasmota, Shelly, Zigbee2MQTT, or Home Assistant).
import paho.mqtt.client as mqtt
import json
import time
import threading
# --- CONFIGURATION ---
# If you don't have a broker, use 'broker.emqx.io' (public test broker)
BROKER_ADDRESS = "broker.emqx.io"
BROKER_PORT = 1883
CLIENT_ID = "python_smart_home_controller"
# Topics (Simulating a Living Room Light)
# In a real scenario, these depend on your device firmware (e.g., Zigbee2MQTT)
TOPIC_COMMAND = "home/living_room/light/set"
TOPIC_STATUS = "home/living_room/light/state"
class SmartHomeController:
def __init__(self):
# Initialize the client with CallbackAPIVersion.VERSION2 (required for latest paho)
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=CLIENT_ID)
# Bind internal callbacks
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect
self.connected = False
def start(self):
"""Connect to the broker and start the background loop."""
try:
print(f"Connecting to {BROKER_ADDRESS}...")
self.client.connect(BROKER_ADDRESS, BROKER_PORT, keepalive=60)
# loop_start runs the network loop in a separate thread.
# This allows your main script to keep running while listening for messages.
self.client.loop_start()
except Exception as e:
print(f"Error connecting: {e}")
def stop(self):
"""Disconnect and stop the loop."""
self.client.loop_stop()
self.client.disconnect()
print("Disconnected.")
# --- CALLBACKS ---
def _on_connect(self, client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected successfully!")
self.connected = True
# Subscribe to the status topic once connected
client.subscribe(TOPIC_STATUS)
print(f"Subscribed to: {TOPIC_STATUS}")
else:
print(f"Connection failed with code: {reason_code}")
def _on_disconnect(self, client, userdata, flags, reason_code, properties):
print(f"Disconnected with code: {reason_code}")
self.connected = False
def _on_message(self, client, userdata, msg):
"""Callback triggered when a message is received on subscribed topics."""
try:
payload = msg.payload.decode('utf-8')
print(f"\n[MSG RECEIVED] Topic: {msg.topic} | Payload: {payload}")
# Logic to handle incoming status updates
if msg.topic == TOPIC_STATUS:
self._handle_device_update(payload)
except Exception as e:
print(f"Error processing message: {e}")
# --- LOGIC ---
def _handle_device_update(self, payload):
"""Parse the device state."""
try:
data = json.loads(payload)
state = data.get("state", "UNKNOWN")
brightness = data.get("brightness", 0)
print(f" >> Device Updated: State={state}, Brightness={brightness}")
except json.JSONDecodeError:
print(f" >> Raw status update: {payload}")
def publish_command(self, state, brightness=None):
"""Public method to send a command to the device."""
if not self.connected:
print("Error: Not connected to broker.")
return
payload_dict = {"state": state.upper()}
if brightness is not None:
payload_dict["brightness"] = brightness
# Convert dictionary to JSON string
payload_json = json.dumps(payload_dict)
print(f"Sending Command: {payload_json} to {TOPIC_COMMAND}")
info = self.client.publish(TOPIC_COMMAND, payload_json, qos=1)
# Wait briefly to ensure delivery (optional, good for scripts)
info.wait_for_publish()
# --- MAIN EXECUTION ---
if __name__ == "__main__":
controller = SmartHomeController()
controller.start()
# Allow time for connection to establish
time.sleep(1)
try:
# Example Control Loop
if controller.connected:
print("\n--- Controlling Device ---")
# 1. Turn Light ON
controller.publish_command("ON")
time.sleep(2)
# 2. Dim Light to 50%
controller.publish_command("ON", brightness=50)
time.sleep(2)
# 3. Turn Light OFF
controller.publish_command("OFF")
time.sleep(2)
print("\nScript finished. Press CTRL+C to exit or wait for incoming messages.")
# Keep the script running to listen for messages (simulating a daemon)
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nExiting...")
controller.stop()
mqtt.Client(...) creates the object that manages the TCP connection.loop_start() creates a separate background thread. This is crucial. It allows the script to listen for incoming messages (like a light turning on) while your main code is free to do other things (like user input or logic)..../set): You publish JSON here to change the device..../state): The device publishes here when its state changes. The script listens (subscribes) to this topic via the on_message callback.qos=1 in the publish method. This ensures the message is delivered at least once to the broker.Run the script: Run the python file in a terminal.
python smart_home.py
Simulate a response: Since you likely don't have a physical device listening to "home/living_room/light/set", the script will send commands, but nothing will reply.
To verify the Listening capability works:
broker.emqx.io.home/living_room/light/state with the payload {"state": "ON", "brightness": 100}.[MSG RECEIVED] log immediately.