zigbee2mqtt场景自动化:基于条件的智能规则引擎
痛点与解决方案概述
你是否还在为智能家居设备间的联动繁琐而困扰?当zigbee设备数量超过10个,手动控制或基础定时任务已无法满足复杂场景需求。本文将系统讲解如何利用zigbee2mqtt的事件驱动架构和条件规则引擎,构建"环境感知-逻辑判断-智能执行"的自动化系统,实现设备状态联动、异常预警、节能控制等高级场景。
读完本文你将掌握:
- 基于设备状态变化的实时触发机制
- 多条件组合逻辑(与/或/非)的配置方法
- 复杂场景的规则优先级与冲突解决策略
- 10个生产级自动化模板(含代码实现)
- 性能优化与故障排查指南
核心架构与工作原理
规则引擎核心组件
zigbee2mqtt的自动化能力基于事件总线(EventBus)和规则匹配系统构建,主要包含以下组件:
关键技术特性:
- 事件驱动:支持设备加入/离开、状态变化、网络拓扑变更等18种事件类型
- 实时处理:平均事件响应延迟<100ms,规则匹配耗时<20ms
- 分布式架构:可与Home Assistant、Node-RED等系统无缝集成
- 高可靠性:规则执行状态持久化,服务重启后自动恢复
事件处理流程
设备状态变化到规则执行的完整生命周期:
规则定义与配置
规则语法结构
一个完整的自动化规则包含以下要素:
# 规则示例:温湿度联动控制
- id: "climate_automation_001"
name: "卧室温湿度智能调节"
description: "当温度>26°C且湿度>60%时启动空调除湿模式"
triggers:
- type: "device_state"
device: "bedroom_temperature_sensor"
property: "temperature"
operator: ">"
value: 26
- type: "device_state"
device: "bedroom_humidity_sensor"
property: "humidity"
operator: ">"
value: 60
condition:
type: "and" # 支持and/or/not组合条件
actions:
- type: "device_command"
device: "bedroom_air_conditioner"
command: "set_mode"
args: ["dehumidify"]
- type: "mqtt_publish"
topic: "home/climate/alert"
payload: '{"status":"high_humidity","room":"bedroom"}'
priority: 5 # 1-10级优先级
enabled: true
tags: ["climate", "bedroom", "energy_saving"]
条件运算符支持
规则引擎支持丰富的条件判断运算符:
| 运算符类型 | 支持符号 | 适用数据类型 | 示例 |
|---|---|---|---|
| 比较运算 | =, !=, >, <, >=, <= | 数值/字符串 | temperature > 25 |
| 包含运算 | in, not_in | 数组/枚举 | mode in ["auto", "heat"] |
| 正则匹配 | matches, not_matches | 字符串 | action matches "^button_.*_press$" |
| 状态判断 | is_on, is_off, is_available | 开关/设备 | state is_on |
| 时间运算 | time_between, time_after, time_before | 时间 | time_between 08:00 and 22:00 |
动作类型与参数
支持多种动作执行方式:
| 动作类型 | 描述 | 参数示例 |
|---|---|---|
| device_command | 发送设备控制命令 | {device: "light", command: "toggle"} |
| mqtt_publish | 发布MQTT消息 | {topic: "alert", payload: '{"type":"fire"}'} |
| delay | 延迟执行后续动作 | {duration: 5, unit: "seconds"} |
| rule_enable | 启用/禁用其他规则 | {rule_id: "rule_002", enabled: false} |
| http_request | 发送HTTP请求 | {url: "https://api.example.com", method: "POST"} |
| log | 记录日志信息 | {level: "info", message: "Rule executed"} |
实战场景与代码实现
场景1:智能照明控制
需求:当检测到人体移动且环境光亮度<30lux时,自动打开客厅灯光,延迟10分钟后关闭。
规则配置:
// 外部转换器示例: external_converters/motion_light.js
const motionLightAutomation = {
id: 'motion_activated_light',
triggers: [
{
type: 'device_state',
device: 'living_room_motion_sensor',
property: 'occupancy',
operator: '=',
value: true
},
{
type: 'device_state',
device: 'living_room_light_sensor',
property: 'illuminance',
operator: '<',
value: 30
}
],
condition: { type: 'and' },
actions: [
{
type: 'device_command',
device: 'living_room_main_light',
command: 'set_state',
args: { state: 'ON', brightness: 80 }
},
{ type: 'delay', duration: 10, unit: 'minutes' },
{
type: 'device_command',
device: 'living_room_main_light',
command: 'set_state',
args: { state: 'OFF' }
}
]
};
module.exports = motionLightAutomation;
关键实现说明:
- 通过
occupancy状态变化触发检测 - 结合光照传感器实现条件判断
- 使用延迟动作实现自动关闭逻辑
- 支持亮度调节的精细化控制
场景2:环境异常监控
需求:当烟雾探测器报警或温度超过60°C时,触发声光报警并推送通知。
规则配置:
# configuration.yaml 中添加
automations:
- id: "environmental_alert"
name: "环境异常监控"
triggers:
- type: "device_state"
device: "kitchen_smoke_detector"
property: "smoke"
operator: "is_on"
- type: "device_state"
device: "living_room_thermostat"
property: "temperature"
operator: ">"
value: 60
condition: { type: "or" }
actions:
- type: "device_command"
device: "全屋警报器"
command: "set_state"
args: { state: "ON", volume: 100 }
- type: "mqtt_publish"
topic: "home/alert"
payload: |
{
"type": "emergency",
"source": "{{ trigger.device.friendly_name }}",
"value": "{{ trigger.value }}",
"timestamp": "{{ now() }}"
}
- type: "http_request"
url: "https://push.example.com/send"
method: "POST"
headers: { "Content-Type": "application/json" }
body: |
{
"title": "环境异常警报",
"message": "{{ trigger.device.friendly_name }} 检测到{{ trigger.property }}异常: {{ trigger.value }}",
"priority": "high"
}
场景3:能源管理系统
需求:当光伏发电功率超过家庭实时用电量+500W时,自动开启热水器加热;当电池储能低于20%时,切换为电网供电。
实现流程图:
核心代码片段:
// lib/extension/energyManagement.ts
class EnergyManagementExtension extends Extension {
constructor(...args) {
super(...args);
this.eventBus.onStateChange(this, this.handleStateChange);
}
async handleStateChange(data) {
// 仅处理能源相关设备
if (!['solar_inverter', 'battery', 'smart_meter'].includes(data.device.type)) {
return;
}
const solarPower = this.state.get('solar_inverter').power || 0;
const homeLoad = this.state.get('smart_meter').power || 0;
const batterySOC = this.state.get('battery').state_of_charge || 100;
// 光伏发电充足条件
if (solarPower > homeLoad + 500) {
await this.publishEntityState('water_heater', { state: 'ON', mode: 'boost' });
this.scheduleNextCheck(30 * 60 * 1000); // 30分钟后再检查
}
// 电池电量低条件
else if (batterySOC < 20) {
await this.publishEntityState('power_switch', { state: 'ON', source: 'grid' });
this.scheduleNextCheck(5 * 60 * 1000); // 5分钟后再检查
} else {
this.scheduleNextCheck(5 * 1000); // 常规5秒检查间隔
}
}
scheduleNextCheck(delay) {
clearTimeout(this.checkTimeout);
this.checkTimeout = setTimeout(() => this.handleStateChange({}), delay);
}
}
高级特性与最佳实践
规则优先级与冲突解决
当多个规则同时满足条件时,系统通过以下机制解决冲突:
- 优先级排序:规则定义的
priority字段(1-10),数值越高越优先 - 时间衰减:相同优先级规则,最近执行过的规则延迟1秒执行
- 资源锁定:对同一设备的控制命令进行合并,避免频繁状态切换
- 依赖声明:通过
depends_on字段指定规则执行顺序
# 优先级示例
- id: "security_rule"
priority: 10 # 安全规则最高优先级
triggers: [{ type: "device_state", device: "door_sensor", property: "contact", value: "open" }]
actions: [{ type: "device_command", device: "alarm", command: "siren" }]
- id: "comfort_rule"
priority: 5 # 舒适性规则优先级较低
triggers: [{ type: "time_between", start: "08:00", end: "22:00" }]
actions: [{ type: "device_command", device: "thermostat", command: "set_temp", args: [24] }]
性能优化策略
大规模部署(>50设备/20规则)时的优化建议:
-
事件过滤:仅监听必要设备的关键状态变化
// 优化前:监听所有设备事件 eventBus.onDeviceMessage(this, (data) => this.handleAllMessages(data)); // 优化后:仅监听特定设备 eventBus.onDeviceMessage(this, (data) => { if (['motion_sensor', 'door_sensor'].includes(data.device.type)) { this.handleSecurityMessages(data); } }); -
规则分组:按场景类型组织规则,减少不必要的条件判断
-
状态缓存:利用
cache_state配置减少设备状态查询开销 -
批量执行:合并短时间内对同一设备的多次控制命令
-
硬件加速:对树莓派等资源受限设备,关闭调试日志并优化Zigbee适配器参数
故障排查与监控
规则执行日志:
// log/automation.log
{
"timestamp": "2023-11-15T14:32:21+08:00",
"rule_id": "motion_activated_light",
"status": "executed",
"trigger": {
"device": "motion_sensor",
"property": "occupancy",
"old_value": false,
"new_value": true
},
"execution_time_ms": 42,
"actions": [
{ "type": "device_command", "device": "light", "status": "success" }
]
}
常见问题排查流程:
扩展与集成
与Home Assistant集成
zigbee2mqtt可通过Home Assistant的设备自动化功能实现高级规则:
# Home Assistant自动化配置示例
automation:
- alias: "Zigbee2MQTT设备联动"
trigger:
platform: mqtt
topic: "zigbee2mqtt/motion_sensor"
condition:
condition: template
value_template: "{{ trigger.payload_json.occupancy == true }}"
action:
service: mqtt.publish
data:
topic: "zigbee2mqtt/light/set"
payload: '{"state": "ON"}'
外部API与Webhook
通过HTTP请求集成第三方服务:
// 规则动作中的HTTP请求配置
{
type: "http_request",
url: "https://api.openweathermap.org/data/2.5/weather",
method: "GET",
params: {
lat: "39.9042",
lon: "116.4074",
appid: "{{ secrets.openweather_api_key }}"
},
on_success: {
type: "device_command",
device: "curtain",
command: "set_position",
args: { position: "{{ response.clouds.all > 70 ? 50 : 100 }}" }
}
}
自定义JavaScript扩展
通过外部脚本实现复杂逻辑:
// external_extensions/weather_based_automation.js
module.exports = class WeatherAutomation {
constructor(zigbee, mqtt, state) {
this.zigbee = zigbee;
this.mqtt = mqtt;
this.state = state;
this.interval = setInterval(() => this.checkWeather(), 30 * 60 * 1000);
}
async checkWeather() {
try {
const response = await fetch('https://api.weather.gov/forecast');
const weather = await response.json();
if (weather.forecast[0].probabilityOfPrecipitation.value > 70) {
await this.mqtt.publish('zigbee2mqtt/outside_light/set', JSON.stringify({ state: 'ON' }));
await this.mqtt.publish('zigbee2mqtt/garage_door/set', JSON.stringify({ state: 'CLOSED' }));
}
} catch (error) {
console.error('Weather API error:', error);
}
}
stop() {
clearInterval(this.interval);
}
};
总结与未来展望
zigbee2mqtt的条件规则引擎为智能家居自动化提供了强大而灵活的解决方案,通过事件驱动架构和丰富的条件动作库,实现了设备间的智能联动。本文介绍的核心概念包括:
- 事件驱动模型:基于设备状态变化触发规则执行
- 灵活条件组合:支持多种运算符和数据类型的条件判断
- 丰富动作类型:设备控制、MQTT消息、HTTP请求等多维度动作
- 实战场景模板:照明控制、环境监控、能源管理等生产级示例
- 性能优化策略:针对大规模部署的效率提升建议
未来发展方向:
- 可视化规则编辑器:基于Web前端的拖拽式规则配置界面
- AI辅助决策:结合机器学习实现自适应场景推荐
- 跨协议集成:与WiFi、蓝牙设备的统一自动化规则
- 边缘计算支持:在Zigbee网关本地执行规则,降低延迟
通过本文学习,你已掌握构建复杂智能家居自动化系统的核心能力。建议从简单场景入手,逐步扩展到多设备联动,同时关注社区最新扩展和最佳实践。
收藏本文,开启你的智能家居自动化之旅!关注更新,下期将带来《Zigbee网络优化与设备兼容性指南》。
附录:规则引擎API参考
核心事件类型
| 事件名称 | 触发时机 | 事件数据示例 |
|---|---|---|
| device_joined | 新设备加入网络 | { device: { ieeeAddr: "0x1234", friendly_name: "sensor" } } |
| device_leave | 设备离开网络 | { device: { ieeeAddr: "0x1234" } } |
| device_state_changed | 设备状态更新 | { device: "sensor", state: { temperature: 25 } } |
| network_map_updated | 网络拓扑变化 | { devices: [...], links: [...] } |
| bridge_state_changed | 网关状态变化 | { state: "online", reason: "startup" } |
规则配置JSON Schema
完整的规则配置JSON Schema定义可参考项目源码中的util/settings.schema.json文件,关键定义片段:
{
"definitions": {
"automation_rule": {
"type": "object",
"properties": {
"id": { "type": "string", "pattern": "^[a-z0-9_]+$" },
"name": { "type": "string" },
"description": { "type": "string" },
"triggers": {
"type": "array",
"items": { "$ref": "#/definitions/trigger" }
},
"condition": { "$ref": "#/definitions/condition" },
"actions": {
"type": "array",
"items": { "$ref": "#/definitions/action" }
},
"priority": { "type": "integer", "minimum": 1, "maximum": 10 },
"enabled": { "type": "boolean", "default": true },
"tags": { "type": "array", "items": { "type": "string" } }
},
"required": ["id", "triggers", "actions"]
}
}
}
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



