上篇博文中我们将模拟设备注册到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-设备到云、云到设备通信的更多相关文章

  1. Azure IoT 技术研究系列2-起步示例之设备注册到Azure IoT Hub

    上篇博文中,我们主要介绍了Azure IoT Hub的基本概念.架构.特性: Azure IoT 技术研究系列1-入门篇 本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到Azure IoT ...

  2. Azure IoT 技术研究系列4-Azure IoT Hub的配额及缩放级别

    上两篇博文中,我们介绍了将设备注册到Azure IoT Hub,设备到云.云到设备之间的通信: Azure IoT 技术研究系列2-设备注册到Azure IoT Hub Azure IoT 技术研究系 ...

  3. Azure IoT 技术研究系列5-Azure IoT Hub与Event Hub比较

    上篇博文中,我们介绍了Azure IoT Hub的使用配额和缩放级别: Azure IoT 技术研究系列4-Azure IoT Hub的配额及缩放级别 本文中,我们比较一下Azure IoT Hub和 ...

  4. Azure IoT 技术研究系列2-设备注册到Azure IoT Hub

    上篇博文中,我们主要介绍了Azure IoT Hub的基本概念.架构.特性: Azure IoT 技术研究系列1-入门篇 本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到Azure IoT ...

  5. Azure IoT 技术研究系列2

    上篇博文中,我们主要介绍了Azure IoT Hub的基本概念.架构.特性: Azure IoT 技术研究系列1-入门篇 本文中,我们继续深入研究,做一个起步示例程序:模拟设备注册到Azure IoT ...

  6. Azure IoT 技术研究系列3

    上篇博文中我们将模拟设备注册到Azure IoT Hub中:我们得到了设备的唯一标识. Azure IoT 技术研究系列2-设备注册到Azure IoT Hub 本文中我们继续深入研究,设备到云.云到 ...

  7. Azure IoT 技术研究系列4

    上两篇博文中,我们介绍了将设备注册到Azure IoT Hub,设备到云.云到设备之间的通信: Azure IoT 技术研究系列2-设备注册到Azure IoT Hub Azure IoT 技术研究系 ...

  8. Azure IoT 技术研究系列1-入门篇

    物联网技术已经火了很多年了,业界各大厂商都有各自成熟的解决方案.我们公司主要搞新能源汽车充电,充电桩就是我们物联网技术的最大应用,车联网.物联网. 互联网三网合一.作为Azure重要的Partner和 ...

  9. Azure IoT 技术研究系列1

    物联网技术已经火了很多年了,业界各大厂商都有各自成熟的解决方案.我们公司主要搞新能源汽车充电,充电桩就是我们物联网技术的最大应用,车联网.物联网. 互联网三网合一.作为Azure重要的Partner和 ...

随机推荐

  1. Scalatra--Introduction And Quick start

    Introduction Scalatra是一款轻易级Scala web框架,通过Scalatra可以很轻易创建web Application,由Linkedln开源并遵循了Ruby Web框架的Si ...

  2. ERP项目案例:澳科利辊业科技有限公司

    企业简介: 上海澳科利公司成立于1995年,在主要股东LASERLIFE的支持下,创始人归霆先生带领他的精英团队--一支陶瓷网纹辊专业制造队伍和资深专业的柔版印刷服务机构,致力于发展中国包装印刷业,服 ...

  3. java基础:数组查询,同一数组一个元素最多出现两次

  4. 自定义cell设置现价,原价(加横线)

    原价,现价分别是连个label.这两个label不能直接限制死他们的宽度,因为他们的宽度不确定,而由于lable的特殊性,不设置它的宽度约束时,宽度取决于文字的内容,所以两个lable的约束设置好一些 ...

  5. DAX/PowerBI系列 - 参数表(Parameter Table)

    DAX/PowerBI系列 - 参数表(Parameter Table) 难度: ★☆☆☆☆(1星) 适用范围: ★★★★☆(4星) 概况: 这个模式比较简单灵活,而且很实用.所用的DAX语句也比较简 ...

  6. Maven工具的使用总结

    Maven作为构建工具,现在项目开发使用的越来越多,相对于ant和gradle,我更喜欢使用maven,先总结maven使用的一系列知识: 一.maven相关的网址: 名称 地址 其他 maven官网 ...

  7. 企业架构(TOGAF)学习

    自从听了公司内部的一堂<企业架构设计>培训,顿时觉得如获至宝. 先说下笔者,笔者是一名二流本科毕业,工作三年,基层的软件开发工程师,梦想着有朝一日成长成一名架构师.可是笔者对于如何成长成一 ...

  8. Docker 使用指南 (四)—— 数据卷的使用

    一.数据卷的使用 有时候需要使用数据库,但是又希望它的数据能保存在本地,Docker中提供了数据卷可以供你方便的操作数据.数据卷是一个可供一个或多个容器使用的特殊目录,它绕过 UFS,可以提供很多有用 ...

  9. struts2(二) 表单参数自动封装和参数类型自动转换

    前篇文章对struts2的一个入门,重点是对struts2的架构图有一个大概的了解即可,之后的几篇文章,就是细化struts2,将struts2中的各种功能进行梳理,其实学完之后,对struts2的使 ...

  10. 深入浅出数据结构C语言版(5)——链表的操作

    上一次我们从什么是表一直讲到了链表该怎么实现的想法上:http://www.cnblogs.com/mm93/p/6574912.html 而这一次我们就要实现所说的承诺,即实现链表应有的操作(至于游 ...