Update IoT Device ID To Device Twin Via Azure Function When Azure IoT Hub Device Created

本文介紹如下案例:

需求,設備註冊後,自動的將設備ID寫入到Device Twin中

技術點:

1. 通過消息路由獲取設備生命週期事件中的設備註冊事件(opType = 'createDeviceIdentity')並將該事件路由到其他終結點,比如Service Bus Queue;

2.通過IoT Hub service SDK 中的iothub.Registry 更新Device Twin;

3.進階,可以將步驟2部署成Function,完成自動修改Device Twin;

 

 

視頻介紹:

您可以通過B站觀看本文視頻講解:https://www.bilibili.com/video/BV1KK411s7G2/

 

 

圖文介紹:

 

重點步驟:

  1. 準備Service Bus Queue:

2. 配置設備生命週期消息路由:

使用如下路由:

opType = 'createDeviceIdentity'

 

3. 創建Function,創建過程請參照本文視頻,配置代碼如下:

引入IoT Hub Service SDK:

在package.json 中添加如下依賴:

"azure-iothub": "^1.7.1"

 

編寫處理Device Twin的業務代碼,修改index.js, 可直接用下方代碼進行替換:

module.exports = async function(context, mySbMsg) {
    context.log('JavaScript ServiceBus queue trigger function processed message', mySbMsg);

    'use strict';
    var iothub = require('azure-iothub');
    //todo: iot hub connectionstring should get from config, in this demo, we hardcode here
    var connectionString = ' your iot hub connection string';
    var registry = iothub.Registry.fromConnectionString(connectionString);
    
    registry.getTwin(mySbMsg.deviceId, function(err, twin){
        if (err) {
            console.error(err.constructor.name + ': ' + err.message);
        } else {
            var patch = {
                tags: {                    
                        DeviceID: mySbMsg.deviceId,                      
                      }
            };
    
            twin.update(patch, function(err) {
              if (err) {
                console.error('Could not update twin: ' + err.constructor.name + ': ' + err.message);
              } else {
                console.log(twin.deviceId + ' twin updated successfully');
                queryTwins();
              }
            });
        }
    });



};

 

4. 本地測試Function: 創建一個IoT Device,打開Device Twin,觀察設備ID 會更新到Tag中:

 

5. 發佈Function到雲端,修改配置文件,再次測試雲端的Function是否正常工作:

修改如下配置文件:

將service bus 的連接字符串寫入配置中,IoT Hub的連接字符串理論上也建議寫入配置文件,本例中hardcode了。

 

再次新建一個IoT Device,觀察結果:

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章