You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ThingsBoard规则链中调用设备共享属性并进行条件判断?

在ThingsBoard规则链中调用设备共享属性的正确方法

你之前代码里用的global.getSharedAttributeValue是错误的,在ThingsBoard规则链的脚本节点中,不能通过这种方式获取设备共享属性,下面是两种可行的实现方式:

方法一:脚本节点中用异步API直接获取

在JavaScript脚本节点中,通过设备的entityId调用异步API拉取共享属性,处理回调后做条件判断。如果是触发当前规则的设备,直接用metadata.entityId作为目标设备ID即可:

// 目标设备ID,当前触发规则的设备用metadata.entityId,其他设备需传入对应ID
var targetDeviceId = metadata.entityId;

// 拉取指定共享属性
getEntitySharedAttributes(targetDeviceId, ["threshold"], function(attributes) {
    var threshold = attributes.threshold;
    // 先判断属性存在再做比较,避免undefined报错
    if (threshold && parseFloat(threshold) > 50) {
        var alarm = {
            type: "Temperature",
            severity: "Critical",
            description: "Temperature has exceeded the threshold of 50 degrees.",
            status: "Active",
            originator: targetDeviceId,
            ts: Date.now()
        };
        // 发送告警到规则链后续节点
        sendAlarms([alarm]);
    }
});

注意:

  • 如果要获取其他设备的属性,需提前知道该设备的entityId,也可以通过getEntityByName方法先根据设备名称查询ID
  • 确保脚本节点允许使用异步API(默认开启,若修改过规则链配置需检查)

方法二:用「获取属性」节点配合脚本节点

这种方法更直观,无需处理异步逻辑:

  1. 在规则链中添加获取属性节点,配置为「共享属性」,选择目标设备,填写要获取的属性键(如threshold)
  2. 将该节点连接到脚本节点,在脚本中直接从msg.attributes读取已拉取的属性值:
var shared_att = msg.attributes.threshold;
// 转成数字类型再比较,避免字符串比较逻辑错误
if (shared_att && parseFloat(shared_att) > 50) {
    var alarm = {
        type: "Temperature",
        severity: "Critical",
        description: "Temperature has exceeded the threshold of 50 degrees.",
        status: "Active",
        originator: metadata.entityId,
        ts: Date.now()
    };
    sendAlarms([alarm]);
}

额外注意事项

  • 如果共享属性值是字符串格式,必须用parseFloat()或parseInt()转成数字后再做数值比较
  • 要提前确认目标设备已配置对应的共享属性,否则属性值会是undefined,需添加判断避免报错

内容的提问来源于stack exchange,提问作者Brell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:25:16