首页 > 解决方案 > 如何在 azure function app 中过滤来自不同设备的 IOT 消息?

问题描述

我在 Azure 中创建了一个IOT Hub,并在其中添加了两台设备。我从两个设备发送相同的消息。我还在Azure 中创建了一个函数应用程序。该功能由 Azure IoT Hub 触发,并将数据保存到 azure 存储表。一切都按预期工作。现在我想使用设备 ID 过滤消息。我的意思是我的天蓝色功能应用程序应该识别消息来自哪个设备。

这是我的函数应用程序 java 脚本代码

module.exports = function (context, iotHubMessage) {

context.log(iotHubMessage.length + ' Message received');

var date = Date.now();
var partitionKey = Math.floor(date / (24 * 60 * 60 * 1000)) + '';
var rowKey = date;

context.bindings.messageLog1 = {
    "partitionKey": partitionKey,
    "rowKey": rowKey + '',
    "MsgCount": iotHubMessage.length,
    "data": JSON.stringify(iotHubMessage)
};

var defaultData = [];

for (var i = 0; i < iotHubMessage.length; i++) {

    var iotMsgObj = iotHubMessage[i];

    iotMsgObj.CreatedDate = new Date();

    defaultData.push({ "partitionKey": partitionKey, "rowKey": (rowKey+i) + '', "data": JSON.stringify(iotMsgObj) });
}

context.bindings.pbDefaultPara1 = defaultData;

context.done();
};

谢谢!

标签: azureazure-functionsazure-iot-hub

解决方案


JavaScript中,您可以使用以下方法获取设备 ID:

context.bindingData.systemProperties["iothub-connection-device-id"]

index.js 看起来像这样:

    module.exports = function (context, IoTHubMessages) {
    context.log('systemProperties', context.bindingData.systemProperties, 'of type', (typeof context.bindingData.systemProperties));
    context.log('DeviceId: ', context.bindingData.systemProperties["iothub-connection-device-id"]);
    context.done();
};

日志是:

2018-07-18T08:55:17.122 [Info] systemProperties { 'iothub-connection-device-id': 'device1',
  'iothub-connection-auth-method': '{"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}',
  'iothub-connection-auth-generation-id': '636627421237258770',
  'iothub-enqueuedtime': 2018-07-18T08:55:16.193Z,
  'iothub-message-source': 'Telemetry',
  'x-opt-sequence-number': 48574,
  'x-opt-offset': '28334352',
  'x-opt-enqueued-time': 2018-07-18T08:55:17.100Z,
  enqueuedTimeUtc: 2018-07-18T08:55:17.100Z,
  sequenceNumber: 48574,
  offset: '28334352',
  'content-type': 'JSON' } of type object
2018-07-18T08:55:17.122 [Info] DeviceId:  device1
2018-07-18T08:55:17.122 [Info] Function completed (Success, Id=709739ed-7b14-4ac2-821f-df2a68c601ef, Duration=2ms)

推荐阅读