規則引擎入門
規則引擎數據結構
規則引擎接受以下數據結構
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