本文主要分享一個案例:
通過Service SDK獲取文件上傳通知;
本文的前提是《Azure IoT Hub 十分鐘入門系列 (4)- 實現從設備上傳日誌文件/圖片到 Azure Storage(Node.js示例)》。
本文主要有如下內容:
1. 在IoT Hub中打開文件上傳通知
2. 使用Node.js Service SDK 接受文件上傳通知
視頻介紹:https://www.51azure.cloud/post/2020/6/7/azure-iot-hub-10-file-upload-notification-nodejs
圖文介紹:
1. 在IoT Hub中打開文件上傳通知:
2. 使用如下示例代碼:
3.安裝SDK:
npm init
回車->回車確認,直到出現如下的package.json界面:
執行
npm install azure-iothub --save
4.修改Service 側代碼中的連接字符串:
修改後的Service 側代碼如下:
'use strict';
var Client = require('azure-iothub').Client;
//var connectionString = process.env.IOTHUB_CONNECTION_STRING;
var connectionString = "your iot hub connection string";
if (!connectionString) {
console.log('Please set the IOTHUB_CONNECTION_STRING environment variable.');
process.exit(-1);
}
var client = Client.fromConnectionString(connectionString);
client.open(function (err) {
if (err) {
console.error('Could not connect: ' + err.message);
process.exit(-1);
} else {
console.log('Client connected');
client.getFileNotificationReceiver(function(err, receiver) {
if(err) {
console.error('Could not get file notification receiver: ' + err.message);
process.exit(-1);
} else {
receiver.on('message', function(msg) {
console.log('File uploaded: ');
console.log(msg.data.toString());
receiver.complete(msg, function(err) {
if (err) {
console.error('Could not complete the message: ' + err.message);
process.exit(-1);
} else {
console.log('Message completed');
process.exit(0);
}
});
});
}
});
}
});
5.運行Service 側代碼:
node receive_file_notifications.js
6.運行Device 側代碼,上傳文件,從Service 側接收文件上傳通知:
注意,device側代碼運行參照文檔《Azure IoT Hub 十分鐘入門系列 (4)- 實現從設備上傳日誌文件/圖片到 Azure Storage(Node.js示例)》
執行:
node upload_to_blob.js
Service 側立刻收到通知: