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和 ...
随机推荐
- Yii里model验证的小技巧
例如:需要判断,字符长度在12-20之间,最大长度的提示语用tooLong,最小提示语言用tooShort array('pay_order', 'length', 'max' => 20, ' ...
- 关于使用mybatis中mapper instrances,通过session另一种操作方式
String resource = "mybatis-config.xml"; InputStream inputStream = null; try { // 获取SqlSess ...
- Java设计模式之《享元模式》及应用场景
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6542449.html 享元模式:"享"就是分享之意,指一物被众人共享, ...
- 基于 Koa平台Node.js开发的KoaHub.js的控制器,模型,帮助方法自动加载
koahub-loader koahub-loader是基于 Koa平台Node.js开发的KoaHub.js的koahub-loader控制器,模型,帮助方法自动加载 koahub loader I ...
- 我的第一个webapiDemo
最近在面试,总是被问到有没有接触过webapi 或者问webapi和MVC 的区别,今天看了看,原来如此,自己理解感觉webapi和webservice一样像是实现soa 的一种形式,也可以理解为服务 ...
- freemodbus移植讲解 ZZ
一 为什么要移植Freemodbus 为什么要移植Freemodbus,这个问题需要从两个方面来回答.第一,modbus是一个非常好的应用层协议,它很简洁也相对完善.对于还没有接触过modbus的 ...
- JavaWeb之JSP技术总结
刚接触JSP技术的时候让我想起了在大学学的Asp+VBScript,记得当时我还用aspstudy做了一个小的新闻发布系统作为期末作品,也正是在那时候在卢哥卢老师的指导下走向编程的道路,对编程越来越感 ...
- scrapy学习笔记
1.scrapy用哪条命令行重新编辑已有的项目?cd projectname 2.如何在pycharm中开启scrapy?先在终端创建一个项目(即文件夹),再在pycharm中打开.
- Chapter 4. Working with Key/Value Pairs
Chapter4 working with key/value pairs key/values pairs键值对是Spark中非常常见的一种数据类型(type),RDD有时经常操作键值对数据类型.第 ...
- java学习笔记 --- 面向对象2
一.匿名对象 (1)没有名字的对象 (2)应用场景 A:调用方法,仅仅只调用一次的时候. class Car { //描述属性.颜色,轮胎数. String color; int number; ...