Azure IoT 技术研究系列3-设备到云、云到设备通信
上篇博文中我们将模拟设备注册到Azure IoT Hub中:我们得到了设备的唯一标识。
Azure IoT 技术研究系列2-设备注册到Azure IoT Hub
本文中我们继续深入研究,设备到云、云到设备通信。
1. 在Azure IoT Hub中接收模拟设备的消息
读取设备到云消息的Event Hub兼容终结点,使用 AMQP 协议。
我们新建一个Console控制台工程:IoTServer,添加Nuget引用:WindowsAzure.ServiceBus

核心的命名空间:using Microsoft.ServiceBus.Messaging;
核心类:EventHubClient
通过EventHubClient创建一个EventHubReceiver,不间断的接收设备侧的消息。
static string connectionString = "HostName=IoTTest.*******;SharedAccessKeyName=iothubowner;SharedAccessKey=***";
static string iotHubD2cEndpoint = "messages/events";
static EventHubClient eventHubClient;
ReceiveMessagesFromDeviceAsync方法:
/// <summary>
/// 接收设备侧的消息
/// </summary>
/// <param name="partition">分区</param>
/// <param name="ct">取消标识</param>
/// <returns>Task</returns>
private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
{
var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
while (true)
{
if (ct.IsCancellationRequested) break;
EventData eventData = await eventHubReceiver.ReceiveAsync();
if (eventData == null) continue; string data = Encoding.UTF8.GetString(eventData.GetBytes());
Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data); //防止CPU被占满
Task.Delay().Wait();
}
}
Main函数中我们将整个IoTServer Run起来:
static void Main(string[] args)
{
Console.WriteLine("Azure IoT Hub 接收消息..., Press Ctrl-C to exit.\n");
eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint); var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds; CancellationTokenSource cts = new CancellationTokenSource(); System.Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
Console.WriteLine("Exiting...");
}; var tasks = new List<Task>();
foreach (string partition in d2cPartitions)
{
tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
} Task.WaitAll(tasks.ToArray());
}
2. 模拟设备发送消息到Azure IoT Hub
我们同样新建一个Console控制台工程:Device,用于模拟向Azure IoT Hub 发送消息。
首先添加Nuget引用:Microsoft.Azure.Devices.Client,这个Nuget依赖的Nuget很多,不要着急,慢慢Install吧

核心的命名空间:
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
核心类:
Microsoft.Azure.Devices.Client.DeviceClient
模拟设备往Azure IoT Hub发消息时,用到了设备的Key(唯一标识)和IoT Hub HostName, 上篇博文中提到的主机名:Azure IoT 技术研究系列2-设备注册到Azure IoT Hub
static DeviceClient deviceClient;
static string iotHubUri = "IoTTest.******"; //iot hub hostname
static string deviceKey = "+jDqO+Nu2g************="; //device key
添加一个循环向Azure IoT Hub发送消息的方法:SendDeviceToCloudMessagesAsync,1s 一条消息
/// <summary>
/// 循环向Azure IoT Hub发送消息
/// </summary>
private static async void SendDeviceToCloudMessagesAsync()
{
double avgWindSpeed = ; // m/s
Random rand = new Random(); while (true)
{
//发送遥测数据
double currentWindSpeed = avgWindSpeed + rand.NextDouble() * - ;
var telemetryDataPoint = new
{
deviceId = "TeldPile001",
windSpeed = currentWindSpeed
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message);
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); //1s 一条
await Task.Delay();
}
}
然后,在Main函数中启动模拟设备发送消息:
static void Main(string[] args)
{
Console.WriteLine("模拟设备通信...\n");
deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("TeldPile001", deviceKey), TransportType.Mqtt); SendDeviceToCloudMessagesAsync();
Console.ReadLine();
}
3. 启动运行测试
在解决方案上设置双启动项目:Device和IoTServer

F5 Run:


可以发现,设备侧消息发送、Azure IoT Hub接收是同步的
我们查看Azure Portal中的统计:

总结: 通过这两篇博文,我们研究验证了Azure IoT Hub 注册设备、设备和云之间的通信,感觉整个Azure 的 IoT Hub还是非常好用、易用,比较容易理解和操作,基于PaaS层的IoT Hub,可以做很多有价值的设计和方案。
周国庆
2017/4/18
Azure IoT 技术研究系列3-设备到云、云到设备通信的更多相关文章
- Azure IoT 技术研究系列2-起步示例之设备注册到Azure IoT Hub
上篇博文中,我们主要介绍了Azure IoT Hub的基本概念.架构.特性: Azure IoT 技术研究系列1-入门篇 本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到Azure IoT ...
- Azure IoT 技术研究系列4-Azure IoT Hub的配额及缩放级别
上两篇博文中,我们介绍了将设备注册到Azure IoT Hub,设备到云.云到设备之间的通信: Azure IoT 技术研究系列2-设备注册到Azure IoT Hub Azure IoT 技术研究系 ...
- Azure IoT 技术研究系列5-Azure IoT Hub与Event Hub比较
上篇博文中,我们介绍了Azure IoT Hub的使用配额和缩放级别: Azure IoT 技术研究系列4-Azure IoT Hub的配额及缩放级别 本文中,我们比较一下Azure IoT Hub和 ...
- Azure IoT 技术研究系列2-设备注册到Azure IoT Hub
上篇博文中,我们主要介绍了Azure IoT Hub的基本概念.架构.特性: Azure IoT 技术研究系列1-入门篇 本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到Azure IoT ...
- Azure IoT 技术研究系列2
上篇博文中,我们主要介绍了Azure IoT Hub的基本概念.架构.特性: Azure IoT 技术研究系列1-入门篇 本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到Azure IoT ...
- Azure IoT 技术研究系列3
上篇博文中我们将模拟设备注册到Azure IoT Hub中:我们得到了设备的唯一标识. Azure IoT 技术研究系列2-设备注册到Azure IoT Hub 本文中我们继续深入研究,设备到云.云到 ...
- Azure IoT 技术研究系列4
上两篇博文中,我们介绍了将设备注册到Azure IoT Hub,设备到云.云到设备之间的通信: Azure IoT 技术研究系列2-设备注册到Azure IoT Hub Azure IoT 技术研究系 ...
- Azure IoT 技术研究系列1-入门篇
物联网技术已经火了很多年了,业界各大厂商都有各自成熟的解决方案.我们公司主要搞新能源汽车充电,充电桩就是我们物联网技术的最大应用,车联网.物联网. 互联网三网合一.作为Azure重要的Partner和 ...
- Azure IoT 技术研究系列1
物联网技术已经火了很多年了,业界各大厂商都有各自成熟的解决方案.我们公司主要搞新能源汽车充电,充电桩就是我们物联网技术的最大应用,车联网.物联网. 互联网三网合一.作为Azure重要的Partner和 ...
随机推荐
- LeetCode 2. Add Two Numbers 解题报告
题意: 有两个链表,它们表示逆序的两个非负数.例 (2 -> 4 -> 3)表示342,求两个数字的和,并用同样的方式逆序输出.如342+465 = 807,你需要把结果表达为(7 -&g ...
- ACM 阶乘数位数
描述 N!阶乘是一个非常大的数,大家都知道计算公式是N!=N*(N-1)······*2*1.现在你的任务是计算出N!的位数有多少(十进制)? 输入 首行输入n,表示有多少组测试数据(n<1 ...
- Effective Modern C++ Item 27:重载universal references
假设有一个接收universal references的模板函数foo,定义如下: template<typename T> void foo(T&& t) { cout ...
- python + selenium <一>
python 安装 python 下载地址: http://python.org/getit/ ez_setup.py 下载地址: https://pypi.python.org/packages/s ...
- velocity中使用枚举
版权声明:本文为博主原创文章,转载请注明出处,欢迎使劲喷 一.为什么要在velocity中使用枚举 1.目前接触到的系统,枚举通常用来在程序中定义数据字典. 举个支付的例子,比如一个字段用来标识一条记 ...
- HTML5 移动页面自适应手机屏幕四类方法
1.使用meta标签:viewport H5移动端页面自适应普遍使用的方法,理论上讲使用这个标签是可以适应所有尺寸的屏幕的,但是各设备对该标签的解释方式及支持程度不同造成了不能兼容所有浏览器或系统. ...
- JAVA基础知识(2)--堆栈和递归的操作
2015-07-26 18:16:21/***该应用程序对堆栈和递归方法进行实例操作: *1.堆栈操作:先进后出,*2.递归方法:直接或者调用自己的方法:*@author lhm *Email:912 ...
- yii2.0框架where条件的使用
在yii框架中,where条件的使用多种多样,下面就和大家介绍几种常用有效的使用方法 1. ['type' => 1, 'status' => 2] //等于 (type = 1) AND ...
- 对于用div+css随心所欲布局的思考
在div+css取代Table成为主流的时代,学会用其进行随心所欲的布局是一个不可回避的技能.那么,重点掌握哪几个要点呢? 整体布局:从整体到局部的顺序进行布局,逐步定义div集css样式: 灵活运用 ...
- iOS开发之Info.plist文件
建立一个工程后,会在Supporting files文件夹下看到一个“工程名-Info.plist”的文件,该文件对工程做一些运行期的配置,非常重要,不能删除 在旧版本Xcode创建的工程中,这个配置 ...