.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”端(运行在本地设备端)用于模拟设备产生数据的代码如下:

 using Microsoft.Azure.Devices.Client;
 using Newtonsoft.Json;
 using System;
 using System.Text;

 namespace Production
 {
     class Program
     {
         //声明一个DeviceClient对象
         private static DeviceClient deviceClient = null;
         //创建一个定时器
         private static System.Timers.Timer timer = new System.Timers.Timer();

         static void Main(string[] args)
         {
             //设备连接字符串,从设备控制台中获取
             var conn = "HostName=myHub.azure-devices.cn;DeviceId=myDevice;SharedAccessKey=sReB225545Jl4Gw=";
             //创建DeviceClient对象的实例
             deviceClient = DeviceClient.CreateFromConnectionString(conn, TransportType.Mqtt);
             timer.Interval = 5000;
             timer.Elapsed += Timer_Elapsed;
             timer.AutoReset = true;
             timer.Start();
             var request = "";
             Console.WriteLine("输入exit则退出,并结束当前程序");
             do
             {
                 request = Console.ReadLine();
                 if (request.Equals("exit"))
                 {
                     Environment.Exit(0);
                 }
             } while (true);
         }

         /// <summary>
         /// 定时任务,模拟向Iot-Hub发送设备数据
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
         private static async void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
         {
             //创建一条数据
             var model = new Info();
             model.Timestamp = DateTime.Now;
             model.Val = new Random().Next(0, 2000);

             var dataBuffer = JsonConvert.SerializeObject(model);
             //将数据封装到Message对象
             var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
             //通过DeviceClient将数据发送到云端
             await deviceClient.SendEventAsync(eventMessage).ConfigureAwait(false);
         }

     }

     /// <summary>
     /// 实体对象
     /// </summary>
     class Info
     {
         public int Val { get; set; }

         public DateTime Timestamp { get; set; }
     }
 }
 

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

 using Microsoft.Azure.Devices.Common;
 using Microsoft.ServiceBus.Messaging;
 using System;
 using System.Text;
 using System.Threading.Tasks;

 namespace Consume
 {
     class Program
     {
         static void Main(string[] args)
         {
             ReceiveCommands().Wait();
         }

         static async Task ReceiveCommands()
         {
             //iot-hub服务连接字符串
             var conn = "HostName=myHub.azure-devices.cn;SharedAccessKeyName=iothubowner;SharedAccessKey=km7jjceOUr+98865=";
             //iot-hub服务内的设备名称
             var device = "myDevice";
             //创建一个EventHubClient对象
             var eventHubClient = EventHubClient.CreateFromConnectionString(conn, "messages/events");
             var eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
             //从指定的设备中获取数据
             var partition = EventHubPartitionKeyResolver.ResolveToPartition(device, eventHubPartitionsCount);
             var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.Now);

             while (true)
             {
                 try
                 {
                     //从Iot-Hub云端获取数据
                     var receivedMessage = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));
                     if (receivedMessage != null)
                     {
                         var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                         if (!string.IsNullOrEmpty(messageData))
                         {
                             Console.WriteLine(messageData);
                         }
                     }
                 }
                 catch
                 {
                 }
             }
         }

     }
 }
 

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

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

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

总结

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

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

声明

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

上一篇:java selenium webdriver第二讲 页面元素定位


下一篇:类调用类的protected或private的成员函数或成员变量