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/
图文介绍:
重点步骤:
准备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,观察结果: