Update IoT Device ID To Device Twin Via Azure Func

Update IoT Device ID To Device Twin Via Azure Function When Azure IoT Hub Device Created- IoT設備創建後使用Function更新設備ID到Device Twin


本文介紹如下案例:

需求,設備註冊後,自動的將設備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:

img-fd303b91-e989-46ab-b88f-d54ec39e45fe.png

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

使用如下路由:

opType = 'createDeviceIdentity'

 

img-5b05301c-b352-433f-9c49-3a55e9cfe879.png

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

引入IoT Hub Service SDK:

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

"azure-iothub": "^1.7.1"

img-8ab98074-bbd4-445a-8d8a-8e6d24d865f8.png

 

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

img-00a59b83-f5a3-40c4-8e65-9ae0cd4b497a.png

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中:

img-366ebdbd-bae8-4c5f-9e59-8247bc29be6e.png

 

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

img-1b7dbf49-5309-4eb5-8ad0-6e020612429c.png

修改如下配置文件:

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

img-d19d5a40-d2ce-4032-b3d4-18319d7e8e12.png

 

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

img-65ff78ff-f263-45cb-b355-baeec56e7672.png

 



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