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

 



猜你喜欢

转载自blog.51cto.com/10117438/2496210