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和 ...
随机推荐
- Java版本
Java版本 Java版本分为J2SE(Java 2 Standard Edition,Java标准版).J2ME(Java 2 Micro Edition,Java微型版本)和J2EE(Java 2 ...
- iOS基础之顺传逆传传值(delegate、block)
写给iOS新手的福利! 在项目中经常会用到传值,根据传值的方向分为顺传(从根控制器到子控制器)和逆传(从子控制器到根控制器).在这里写了个Demo简单演示了效果,创建了两个控制器: 一个为根控制器,一 ...
- Linux i2c子系统(三) _解决probe无法执行
如果你也遇到了填充了id_match_table,compitible怎么看都一样,但probe就是不执行(让我哭一会),你可以回头看一下上一篇的模板,我们这里虽然使用的是设备树匹配,但和platfo ...
- 徒手用Java来写个Web服务器和框架吧<第二章:Request和Response>
徒手用Java来写个Web服务器和框架吧<第一章:NIO篇> 接上一篇,说到接受了请求,接下来就是解析请求构建Request对象,以及创建Response对象返回. 多有纰漏还请指出.省略 ...
- 查看iis对应w3wp.exe显示的进程ID号(转载)
管理员身份运行cmd,跳转到C:\Windows\System32\inetsrv目录,然后运行appcmd list wp即可查看
- Java面试15|网络
1.TCP(Transmission Control Protocol)三次握手与四次分手 TCP在不可靠的传输信道上提供了可靠传输的抽象,隐藏了我们的应用程序大部分的复杂性功能:丢包重传,按序传送, ...
- 使用python landport库快速实现排行榜
背景介绍 排行榜业务使用的频率实在太高了,各种活动都会使用排行榜.经过多次开发后我觉得实现一个简单的排行榜库,它能够完成当前我遇到的所有业务逻辑问题,也希望能够帮助到想要快速开发排行榜业务的同行. 我 ...
- rip路由协议 细节分析及实例配置【完整版】
rip路由协议 细节分析及实例配置[完整版] RIP呢,这是一个比较重要的知识点,所以它的知识覆盖面很广泛:但是呢,我将会对碰到的问题进行一些分析解刨(主要是为了帮助自己理清思维):也希望能够从中发现 ...
- 2017Java技术预备作业1501黄学超
阅读邹欣老师的博客,谈谈你期望的师生关系是什么样的? 我觉得师生关系应当是亲密无间,课上老师讲解学生配合,课下师生交流启发思考. 你有什么技能(学习,棋类,球类,乐器,艺术,游戏,......)比大多 ...
- C++ Primer 5 CH4 表达式
4.1 基础 函数调用也是一种特殊的运算符,它对运算对象的数量没有限制. C++ 的表达式要么是左值,要么是右值.左值可以位于赋值语句的左边,右值则不可以. 当一个对象被用作右值的时候,用的是对象的值 ...