.NET Core2使用Azure云上的Iot-Hub服务

基于工业4.0大背景下的工业物联网是近几年内热门的话题,依靠信息化技术企业可以实现数字化转型,生产可以实现智能化制造,设备可以实现自动化运作。然而,海量的数据采集是整个建设过程的基础环节,如何处理与利用这海量的数据是信息化技术中最重要的开发工作。那么,基于Azure国内云端的Iot-Hub服务是提供给开发人员另一个高效的数据处理方案,这里将通过代码的方式介绍如何将Iot-Hub服务集成到咱们的程序中来。

 

Azure云的Iot-Hub服务

Internet of things(简称Iot)物联网是新一代信息技术的重要组成部分。Iot-Hub是一个由微软提供的基于Azure云上的工业物联网解决方案,它可以大规模的管理Iot设备,可以与数百万的 IoT 设备建立双向通信,且支持各种操作系统和通信协议,另外它还能利用边缘计算实现更多的开发需要。如下是跟Iot-Hub相关的网址:

Iot-Hub官网(国内):https://www.azure.cn/zh-cn/home/features/iot-hub/

 

准备

这里将模拟一个iot设备上行到云端的demo,所以在着手开始实现之前咱们需准备一些必要的环境,如下:

1、在Azure上创建一个名为“myHub”的Iot-Hub服务,并将其的“连接字符串”获取,以备后用。

2、在”myHub”服务控制台内创建一个名为“myDevice”的设备,并将其的“连接字符串”获取,以备后用。

3、用VS2017开发工具创建两个基于.NET Core2的控制台程序,分别为:“Production”、“Consume”:

3.1、“Production”用来模拟Iot设备产生数据(运行于设备本地端),并将数据发送到Iot-Hub服务中,需在项目中通过Nuget管理器引用由微软提供的sdk类库“Microsoft.Azure.Devices.Client”。

3.2、“Consume”用来从Iot-Hub服务实时获取数据(运行于服务器云端),需在项目中通过Nuget管理器引用由微软提供的sdk类库“Microsoft.Azure.Devices”、“Microsoft.ServiceBus”。

 

实现

通过上述的准备后,咱们就可以进入具体的发布与集成工作了,如下:

1、“Production”端(运行在本地设备端)用于模拟设备产生数据的代码如下:

  1 using Microsoft.Azure.Devices.Client;
  2 using Newtonsoft.Json;
  3 using System;
  4 using System.Text;
  5 
  6 namespace Production
  7 {
  8     class Program
  9     {
 10         //声明一个DeviceClient对象
 11         private static DeviceClient deviceClient = null;
 12         //创建一个定时器
 13         private static System.Timers.Timer timer = new System.Timers.Timer();
 14 
 15         static void Main(string[] args)
 16         {
 17             //设备连接字符串,从设备控制台中获取
 18             var conn = "HostName=myHub.azure-devices.cn;DeviceId=myDevice;SharedAccessKey=sReB225545Jl4Gw=";
 19             //创建DeviceClient对象的实例
 20             deviceClient = DeviceClient.CreateFromConnectionString(conn, TransportType.Mqtt);
 21             timer.Interval = 5000;
 22             timer.Elapsed += Timer_Elapsed;
 23             timer.AutoReset = true;
 24             timer.Start();
 25             var request = "";
 26             Console.WriteLine("输入exit则退出,并结束当前程序");
 27             do
 28             {
 29                 request = Console.ReadLine();
 30                 if (request.Equals("exit"))
 31                 {
 32                     Environment.Exit(0);
 33                 }
 34             } while (true);
 35         }
 36 
 37         /// <summary>
 38         /// 定时任务,模拟向Iot-Hub发送设备数据
 39         /// </summary>
 40         /// <param name="sender"></param>
 41         /// <param name="e"></param>
 42         private static async void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 43         {
 44             //创建一条数据
 45             var model = new Info();
 46             model.Timestamp = DateTime.Now;
 47             model.Val = new Random().Next(0, 2000);
 48 
 49             var dataBuffer = JsonConvert.SerializeObject(model);
 50             //将数据封装到Message对象
 51             var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
 52             //通过DeviceClient将数据发送到云端
 53             await deviceClient.SendEventAsync(eventMessage).ConfigureAwait(false);
 54         }
 55 
 56     }
 57 
 58     /// <summary>
 59     /// 实体对象
 60     /// </summary>
 61     class Info
 62     {
 63         public int Val { get; set; }
 64 
 65         public DateTime Timestamp { get; set; }
 66     }
 67 }
 68 

 

2、“Consume”端(运行在服务器云端)用于消费来自Iot-Hub的代码如下:

  1 using Microsoft.Azure.Devices.Common;
  2 using Microsoft.ServiceBus.Messaging;
  3 using System;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 
  7 namespace Consume
  8 {
  9     class Program
 10     {
 11         static void Main(string[] args)
 12         {
 13             ReceiveCommands().Wait();
 14         }
 15 
 16         static async Task ReceiveCommands()
 17         {
 18             //iot-hub服务连接字符串
 19             var conn = "HostName=myHub.azure-devices.cn;SharedAccessKeyName=iothubowner;SharedAccessKey=km7jjceOUr+98865=";
 20             //iot-hub服务内的设备名称
 21             var device = "myDevice";
 22             //创建一个EventHubClient对象
 23             var eventHubClient = EventHubClient.CreateFromConnectionString(conn, "messages/events");
 24             var eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
 25             //从指定的设备中获取数据
 26             var partition = EventHubPartitionKeyResolver.ResolveToPartition(device, eventHubPartitionsCount);
 27             var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.Now);
 28 
 29             while (true)
 30             {
 31                 try
 32                 {
 33                     //从Iot-Hub云端获取数据
 34                     var receivedMessage = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));
 35                     if (receivedMessage != null)
 36                     {
 37                         var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
 38                         if (!string.IsNullOrEmpty(messageData))
 39                         {
 40                             Console.WriteLine(messageData);
 41                         }
 42                     }
 43                 }
 44                 catch
 45                 {
 46                 }
 47             }
 48         }
 49 
 50     }
 51 }
 52 

 

3、分别运行“Production”与“Consume”端后,也可在Azure的Iot-Hub控制台查看实时报表,如下:

image

image

 

总结

1、通过Azure云端的Iot-Hub服务可以非常高效的实现Iot设备的管理与数据采集。

2、在.NetCore2程序中使用由微软提供的“Microsoft.Azure.Devices.Client”、“Microsoft.Azure.Devices”、“Microsoft.ServiceBus”类库,可以非常简便的在程序中集成Iot-Hub。

 

声明

本文为作者原创,转载请备注出处与保留原文地址,谢谢。如文章能给您带来帮助,请点下推荐或关注,感谢您的支持!

 

posted @ 2018-11-06 16:10  Miidy  阅读(775)  评论(3编辑  收藏  举报