将遥测数据发送到iotDevice的Azure函数

问题描述 投票:0回答:1

我正在尝试开发一种azure函数,该函数从一个内置的eventhub接收消息并对其进行处理,并将结果发送到Azure IoT中心中配置的另一个IoT设备。下面是代码:

module.exports =函数(上下文,IoTHubMessages){

var Mqtt = require('azure-iot-device-mqtt').Mqtt;
var DeviceClient = require('azure-iot-device').Client
var Message = require('azure-iot-device').Message

var connectionString = '{connectionstring of the target device}';
var acRoom1 = DeviceClient.fromConnectionString(connectionString, Mqtt);


var totalPerson = 0;
var events = IoTHubMessages.length;

context.log(JSON.stringify(IoTHubMessages));
context.log(Array.isArray(IoTHubMessages));

context.log(`Number of entries: ${IoTHubMessages.length}`);
IoTHubMessages.forEach(message => {
    context.log(`Processed message: ${JSON.stringify(message)}`);
    totalPerson = totalPerson + message.personCount;
    context.log(`Total count: ${totalPerson}`);

});

var avgPersonCount = Math.round( totalPerson / events );
context.log(`Average person count: ${avgPersonCount}`);

var temp = 24;
if ( avgPersonCount > 5){
    temp = 20;
}
else if ((avgPersonCount>2) && (avgPersonCount <= 5)){
    temp = 22;
}
else {
    temp = 24;
} 
var msg = new Message(`Setting temperature to ${temp} C`);
context.log('Sending message: ' + msg.getData());
context.log(`Temeperature set to ${temp} C`);
acRoom1.sendEvent(msg);

context.done();

};

我遇到的问题是,我发送给设备的事件又回到了这种天蓝色的功能。我相信,我需要在“消息路由”中做一些事情,但是不确定需要做什么。

整个解决方案(我想要实现)的流程如下

相机-> Azure IOT集线器-> Azure功能-> AC

node.js azure-functions azure-iot-hub
1个回答
0
投票

您可以通过设备ID过滤事件,但是更具扩展性的方法是添加appProperty。如果要将所有AC事件发送到其他端点,则可以在AC发送的消息中添加一个appProperty。示例:

var msg = new Message(`Setting temperature to ${temp} C`);
msg .properties.add('eventType', 'AC');
context.log('Sending message: ' + msg.getData());
context.log(`Temeperature set to ${temp} C`);
acRoom1.sendEvent(msg);

之后,您可以转到IoT中心并添加新路线。您可以将这些事件路由到另一个端点,如下所示:Adding a new route

由于您的相机未发送此appProperty,它将依赖于后备路由,并且您的Azure函数仍将处理这些事件。另一个也许更可靠的选择是仅将摄像机消息发送到特定路由。但是任何一个都行!

© www.soinside.com 2019 - 2024. All rights reserved.