azure - 如何在 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();
};
谢谢!
解决方案
在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)
推荐阅读
- html - 背景图片在H1之上
- php - 如何使用 POST 处理在 php 中动态生成的多个输入字段
- vb.net - 如何将 Word.Range 保存到文档中
- json - 解组嵌套 json 会导致空值
- json - 将 UTF 字符处理为 JSON 时出现 ApacheCamel 异常。(无效的 UTF-8 中间字节)
- flutter - 在 Flutter 的列中使用 ListView
- python - RuntimeError:在应用程序上下文之外工作。烧瓶 - 邮件
- logging - SSAS 表格扩展事件会话随机删除
- docker - Windows 上 dockerfile 中本地映像的路径
- laravel - SQLite 数据库的 Laravel Tinker 错误