ThingsBoard 模板化
正文来自原稿,并结合官方规则引擎模板说明整理。
1、模板化概念
模板化是使用预定义模板,在运行时把值插入或替换到文本中的过程。模板充当变量占位符,之后用实际数据填充。
在规则引擎里,模板常用于从传入消息中提取数据,并填到规则节点配置字段——把配置时的静态值换成消息里的实时值,使处理更灵活、可自动化。
2、语法规则
模板以美元符号 $ 开头,后跟括号和键名:
| 语法 | 含义 |
|---|---|
$[messageKey] | 从消息 data(JSON)取 messageKey |
${metadataKey} | 从消息 元数据 取 metadataKey |
messageKey / metadataKey 可以是消息或其元数据中任意存在的键名。
3、案例
假设消息与元数据如下:
json
{
"temperature": 26.5,
"humidity": 75.2,
"soilMoisture": 28.9,
"windSpeed": 26.2,
"location": "riverside"
}json
{
"deviceType": "weather_sensor",
"deviceName": "weather1",
"ts": "1685379440000"
}检测到异常风速后,要把读数报到外部 REST API,URL 里需要设备与位置(仅运行时可知)。可用模板拼 URL:
text
http://example-base-url.com/report-reading?location=$[location]&deviceName=${deviceName}解析结果:
text
http://example-base-url.com/report-reading?location=riverside&deviceName=weather1模板特别适合「配置时未知、运行时才有」的字段。
4、注意
- 模板可与普通文本混用,例如:
油箱已加满$[fuelLevel]%。 - 嵌套键用点号:
$[object.key]。 - 若键不存在,或值是 对象 / 数组,模板字符串会 原样返回(不展开)。
示例消息:
json
{
"number": 123.45,
"string": "text",
"boolean": true,
"array": [1, 2, 3],
"object": {
"property": "propertyValue"
},
"null": null
}| 模板 | 提取值 |
|---|---|
$[number] | 123.45 |
$[string] | text |
$[boolean] | true |
$[array] | $[array](原样) |
$[object] | $[object](原样) |
$[object.property] | propertyValue |
$[null] | null |
$[doesNotExist] | $[doesNotExist](原样) |
5、小结
规则链里凡支持模板的输入框(REST URL、主题、RPC 参数等),优先用 $[] / ${},少写死设备名与动态字段。
