trphoenix
2025-07-15 3191826fdef076c67ed56b0ff5f821f6033bf45c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 生成唯一的消息ID
const messageId = "temp_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
const timestamp = Date.now();
//nameSpace:命名空间,需要改改为正确的命名空间代码
const nameSpace ="Environment"
//此处需要改为正确的客户代码
const clientCode = "Data-It_XzOffice";
//此片 从topic中提取传感器实体ID 无需更改
const topicParts = msg.topic.split('/');
const deviceId = topicParts.length >= 3 ? topicParts[2] : msg.topic;
const deviceType = "sensor";
 
// 解析温度值
let temperature = parseFloat(msg.payload);
if (isNaN(temperature)) {
    node.warn("接收到无效的温度值: " + msg.payload);
    return null;
}
 
// 按照胜透物联网通信协议格式化数据
const protocolMessage = {
    "messageId": messageId,
    "timestamp": timestamp,
    "clientCode": clientCode,
    "deviceId": deviceId,
    "deviceType": deviceType,
    "version": "1.0",
    "data": {
        "properties": {
            "temperature": {
                "value": temperature,
                "unit": "°C",
                "quality": "good",
                "timestamp": timestamp
            }
        }
    }
};
 
// 设置输出消息
msg.payload = JSON.stringify(protocolMessage);
msg.topic = `${nameSpace}/sensor/${deviceId}/properties`;
msg.qos = 0;
 
node.log("温度数据已处理: " + temperature + "°C");
 
return msg;