上篇博文中,我们主要介绍了 Azure IoT Hub 的基本概念、架构、特性:
Azure IoT 技术研究系列 1 - 入门篇
本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到 Azure IoT Hub, 设备到云通信,云到设备通信。
整体篇幅较大,我们先来第一步:将模拟设备注册到 Azure IoT Hub。
首先,我们需要有一个联网的设备,例如树莓派、Win10 IoT 设备等等,只要能联网,Azure IoT Hub 有编程 SDK 即可,为了方便演示,本篇中我们做了一个模拟设备:
TeldPile001,即 001 号充电桩。
然后,在正式编码前,需要我们在 Azure New Portal 中,添加自己的 IoT Hub.
输入名称后,选择定价和缩放级别,这里我们做测试,使用免费的 F1 即可,同时新建资源组。
创建完成后,IoTTest 即可使用了。
使用前,我们需要确定两个重要的连接配置:主机名和连接字符串,我们选择 "概述",右侧有个主机名,先复制下来备用。
然后选择共享访问策略:
将连接字符串 - 主秘钥,复制保存下来备用。
开始编码吧,我们创建一个 Console 工程叫做 "RegisterDevice",用于设备注册到 Azure IoT Hub。同时添加重要的 Nuget 引用:
Microsoft.Azure.Devices
本文测试用的:<package id="Microsoft.Azure.Devices"version="1.2.4"targetFramework="net451"/>
两个核心的 Namespace:
using Microsoft.Azure.Devices; using Microsoft.Azure.Devices.Common.Exceptions;
核心类:Microsoft.Azure.Devices.RegistryManager:设备注册管理器
我们设计一个方法,添加或者获取设备信息:
- 1 /// <summary>
- 2 /// 添加或获取设备信息
- 3 /// </summary>
- 4 /// <returns>Task</returns>
- 5 private static async Task AddOrGetDeviceAsync() 6 {
- 7 string deviceId = "TeldPile001";
- 8 Device device;
- 9
- try 10 {
- 11 device = await registryManager.AddDeviceAsync(new Device(deviceId));
- 12
- }
- 13
- catch(DeviceAlreadyExistsException) 14 {
- 15 device = await registryManager.GetDeviceAsync(deviceId);
- 16
- }
- 17 18 Console.WriteLine("生成设备标识: {0}", device.Authentication.SymmetricKey.PrimaryKey);
- 19
- }
Main 函数:
- 1 static void Main(string[] args) 2 {
- 3
- var connectionString = "HostName=IoTTest.***-***;SharedAccessKeyName=iothubowner;SharedAccessKey=******";
- 4
- var registryManager = RegistryManager.CreateFromConnectionString(connectionString);
- 5 AddOrGetDeviceAsync().Wait();
- 6 Console.ReadLine();
- 7
- }
Run,
可以看到,TeldPile001 这个设备已经注册到我们自己的 Azure IoT Hub 中了。
以上便是,将设备注册到 Azure IoT Hub 的介绍,不复杂,微软的设计还是比较赞的,简单、快速、易用。
下一篇我们继续研究设备到云、云到设备的通信。
周国庆
2014/4/16
来源: http://www.cnblogs.com/tianqing/p/6719607.html