Providing MQTT smart home control example
I'm producing concise Python code using paho-mqtt that implements a simple state machine to turn on lights when motion is detected between 6 PM and 6 AM with low ambient light, publishing the appropriate MQTT commands.
Below is a minimal example in Python using the paho-mqtt library. It listens on a motion-sensor topic and, when motion is detected between 6 PM and 6 AM with lux under 50, it publishes a command to turn on the lights. You can adjust topics, payload formats, and broker details as needed.
import json
import time
from datetime import datetime
import paho.mqtt.client as mqtt
# MQTT broker settings
BROKER_HOST = "localhost"
BROKER_PORT = 1883
MOTION_TOPIC = "home/sensors/motion" # Example motion topic
LIGHT_CMD_TOPIC = "home/lights/command" # Example command topic to control lights
# State machine states
STATE_IDLE = "IDLE"
STATE_LIGHT_ON = "LIGHT_ON"
current_state = STATE_IDLE
def is_nighttime():
"""Return True if current time is between 6 PM and 6 AM."""
hour = datetime.now().hour
return hour >= 18 or hour < 6
def on_connect(client, userdata, flags, rc):
print("Connected with result code", rc)
client.subscribe(MOTION_TOPIC)
def on_message(client, userdata, msg):
global current_state
# Expecting JSON payload like: {"motion": true, "lux": 20}
try:
data = json.loads(msg.payload.decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError):
print("Invalid payload on motion topic")
return
motion = data.get("motion", False)
lux = data.get("lux", 999)
# Simple state machine transitions
if motion and is_nighttime() and lux < 50:
if current_state != STATE_LIGHT_ON:
# Publish ON command to lights
client.publish(LIGHT_CMD_TOPIC, json.dumps({"state": "ON"}), qos=1)
current_state = STATE_LIGHT_ON
print("Motion detected at night with low lux -> Lights ON")
else:
# If needed, transition back to idle; not strictly required unless you
# want to handle turning them off via this script.
current_state = STATE_IDLE
# Set up MQTT client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER_HOST, BROKER_PORT, 60)
client.loop_forever()
How it works:
- The script subscribes to
home/sensors/motion.
- Each incoming message is parsed for
motion (Boolean) and lux (numeric).
- If motion is detected, the time is between 18:00 and 06:00, and
lux < 50, it publishes a JSON payload {"state": "ON"} to home/lights/command.
- A simple state variable (
current_state) prevents sending repeated ON commands, but you can extend it to handle OFF states or more complex logic.
Adjust the topics and payload structure to match your devices, and ensure your broker’s host/port and authentication settings are correct.