规则引擎入门
规则引擎数据结构
规则引擎接受以下数据结构
source: source_uuid
metric: {}
source_meta: {}
target: target_uuid
target_meta: {}
code: ""
- source 为源设备的 UUID
- metric 为源设备的实时数据或者实时属性
- source_meta 为源设备的属性
- target 为目标设备的 UUID (可选)
- target_meta 为目标设备的属性 (可选)
- code 为规则的 lisp 代码
规则测试工具
使用 rule-engine test rule.yaml
来测试规则是否可以用。
测试有输出需要执行的异步任务。
示例
示例1
用于场景,在手机上点击场景按钮,然后打开电灯。
source: source_uuid
metric: {}
code: |
; {"method": "set", "state": "ON"}
(cmd_set :open_led "method" "set")
(cmd_set :open_led "state" "ON")
; 给源设备发指令 (source_rpc :open_led)
- 保存为
open_led.yaml
, - 然后执行
rule-engine test open_led.yaml
输出结果如下:
- uuid: source_uuid
data:
state: 'ON'
method: set
func_name: send_rpc
示例2
用于两个设备进行联动,如按下按钮后开灯。
source: source_uuid
metric:
click: single
target: target_uuid
code: |
; {"method": "set", "state": "ON"}
(cmd_set :open_led "method" "set")
(cmd_set :open_led "state" "ON")
(if (= (metric "click") "single") (target_rpc :open_led))
- 保存为
open_led_scene.yaml
, - 然后执行
rule-engine test open_led_scene.yaml
输出结果如下:
- uuid: target_uuid
data:
state: 'ON'
method: set
func_name: send_rpc
示例3
用于消息通过,当温度超过 30 度的时候高温报警,低于 20 度的时候低温报警。
source: source_uuid
metric:
temperature: 10
code: |
; {"title": "高温报警", "content": "设备温度太高了"}
(cmd_set :high_temp "title" "高温报警")
(cmd_set :high_temp "content" "设备温度太高了")
; {"title": "低温报警", "content": "设备温度太低了"}
(cmd_set :low_temp "title" "低温报警")
(cmd_set :low_temp "content" "设备温度太低了")
(if (>= (metric "temperature") 30) (message :high_temp)) (if (<= (metric "temperature") 20) (message :low_temp))
- 保存为
temperature_alarm.yaml
, - 然后执行
rule-engine test temperature_alarm.yaml
输出结果如下:
- uuid: source_uuid
data:
content: 设备温度太低了
title: 低温报警
func_name: send_message
示例4
用于温度异常检测,并发消息通知
source: source_uuid
metric:
temperature: 10
timestamp: 1592463384
code: |
; {"title": "温度异常", "content": ""}
(cmd_set :anomaly_temp "title" "温度异常")
(cmd_set :anomaly_temp "content" "")
(anomaly "temperature" 0.8 :anomaly_temp)
- 保存为
anomaly.yaml
, - 然后执行
rule-engine test anomaly.yaml
输出结果如下:
- uuid: source_uuid
data:
with_timestamp: false
value: 10
action_name: anomaly
name: temperature
threshold: 0.8
message:
content: ''
title: 温度异常
timestamp: 1592463384
func_name: anomaly_detect