上篇博文中我们将模拟设备注册到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

最新文章

  1. Only Link: Inheritance — private and protected inheritance in c++
  2. CSS3选择器的研究,案例
  3. WIN7 64位如何添加网络打印机
  4. 如何在Oracle中导入dmp文件
  5. ubuntu下eclipse无法启动问题
  6. 学习资料 50个常用的sql语句
  7. objective-C常量与变量
  8. 如何使用Git——(二)
  9. Linux内核Radix Tree(三):API介绍
  10. configure脚本参数介绍
  11. session问题和JSP
  12. http验证CertificateValidation
  13. 用for循环筛选奇偶表格栏
  14. P4178 Tree(点分治)
  15. LEDAPS1.3.0版本移植到windows平台----HuPm参数初始化模块
  16. MAC下 mySQL及workbench安装
  17. Linux查看当前目录下文件名中包含指定字符的文件
  18. 使用feign出现 java.lang.IllegalStateException: Service id not legal hostname
  19. hibernate框架学习之二级缓存
  20. sublime text3 安装package control 出现问题解决过程记录

热门文章

  1. jquery.datetimepicker.js 当鼠标离开时,不选中当前时间,以达到清空的目的
  2. spring exception
  3. Jquery 客户端生成验证码
  4. IE浏览器img不显示解决
  5. 二级C考点汇总
  6. Java中的函数对象
  7. 时间相关库&lt;ctime&gt;解析
  8. 2017年3月23日 坚果性能测试Loadrunner 免费公开课
  9. eclipse中代码格式化组合键失效了
  10. webStorm在Node.js平台下服务器配置及Express配置