Azure IoT Edge模块间转发消息丢失属性(Node-RED接收)已解决
Azure IoT Edge模块间路由传递消息属性至Node-RED的解决方案
问题背景
部署了一台Azure IoT Edge设备,包含两个官方模块:Simulated Temperature Sensor(模拟温度传感器)和Node-RED。已配置路由将传感器消息转发到Node-RED输入,但Node-RED仅能接收到消息payload,无法获取任何系统属性(如iothub-connection-device-id)或自定义属性。
当前路由配置
- NoderedToIotHub:
FROM /messages/modules/nodered/outputs/* INTO $upstream - SimulatedTemperatureSensorToNodered:
FROM /messages/modules/SimulatedTemperatureSensor/* INTO BrokeredEndpoint("/modules/nodered/inputs/input1")
Node-RED接收的无属性消息示例
{ "payload": { "machine": { "temperature": 78.45809454307097, "pressure": 7.545858871995427 }, "ambient": { "temperature": 21.225943549765738, "humidity": 26 }, "timeCreated": "2024-05-10T12:40:41.4387644Z" }, "topic": "input", "input": "input1", "_msgid": "ac58dc85f99232e7" }
已尝试在路由末尾添加WITH $includeProperties或WITH $systemProperties,但问题未解决。使用的Node-RED模块为node-red-contrib-azure-iot-edge-module(1.0.4),查看其源码发现ModuleInput监听事件后仅解析payload,未处理属性;但直接将消息发往IoT Hub时,Azure IoT Explorer能正常看到属性。
解决方法
通过调整路由配置并适配Node-RED模块的消息处理逻辑,成功实现属性传递,更新后的消息示例如下:
{ "payload": { "machine": { "temperature": 107.36094975136817, "pressure": 10.838589212181184 }, "ambient": { "temperature": 21.03510694838928, "humidity": 25 }, "timeCreated": "2024-05-15T13:58:58.0540963Z" }, "properties": { "propertyList": [ { "key": "sequenceNumber", "value": "464" }, { "key": "batchId", "value": "56554fbc-4a74-4dc3-81fa-834d46bc232b" }, { "key": "$.cdid", "value": "my-edge-device-1" }, { "key": "$.cmid", "value": "SimulatedTemperatureSensor" } ] }, "topic": "input", "input": "input1", "_msgid": "36c79982b8df928e" }
具体操作步骤
更新路由配置
将第二条路由修改为同时包含属性传递指令:SimulatedTemperatureSensorToNodered = FROM /messages/modules/SimulatedTemperatureSensor/* INTO BrokeredEndpoint("/modules/nodered/inputs/input1") WITH $includeProperties, $systemProperties适配Node-RED消息处理
由于node-red-contrib-azure-iot-edge-module默认仅解析payload,需添加自定义函数节点提取属性:- 在Node-RED的输入节点后添加一个函数节点
- 在函数中添加代码,将消息携带的属性挂载到
msg对象(示例代码需根据模块实际传递的变量调整):// 提取消息属性并挂载到msg.properties msg.properties = { propertyList: Object.entries(msg.messageProperties || {}).map(([key, value]) => ({ key, value })) }; return msg; - 输出处理后的消息,后续节点即可访问属性内容
内容的提问来源于stack exchange,提问作者user3214726
相关产品推荐
相关产品推荐

