.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官網(國內): ofollow,noindex">https://www.azure.cn/zh-cn/home/features/iot-hub/
準備
在著手開始實現之前咱們需準備一些必要的環境,如下:
1、在Azure上建立一個名為“myHub”的Iot-Hub服務,並將其的“連線字串”獲取,以備後用。
2、在”myHub”服務控制檯內建立一個名為“myDevice”的裝置,並將其的“連線字串”獲取,以備後用。
3、用VS2017開發工具建立兩個基於.NET Core2的控制檯程式,分別為:“Production”、“Consume”。其中“Production”用來模擬Iot裝置產生資料,並將資料傳送到Iot-Hub服務中,需在專案中通過Nuget管理器引用由微軟提供的sdk類庫“Microsoft.Azure.Devices.Client”。“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 { 8class Program 9{ 10//宣告一個DeviceClient物件 11private static DeviceClient deviceClient = null; 12//建立一個定時器 13private static System.Timers.Timer timer = new System.Timers.Timer(); 14 15static void Main(string[] args) 16{ 17//裝置連線字串,從裝置控制檯中獲取 18var conn = "HostName=myHub.azure-devices.cn;DeviceId=myDevice;SharedAccessKey=sReB225545Jl4Gw="; 19//建立DeviceClient物件的例項 20deviceClient = DeviceClient.CreateFromConnectionString(conn, TransportType.Mqtt); 21timer.Interval = 5000; 22timer.Elapsed += Timer_Elapsed; 23timer.AutoReset = true; 24timer.Start(); 25var request = ""; 26Console.WriteLine("輸入exit則退出,並結束當前程式"); 27do 28{ 29request = Console.ReadLine(); 30if (request.Equals("exit")) 31{ 32Environment.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> 42private static async void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 43{ 44//建立一條資料 45var model = new Info(); 46model.Timestamp = DateTime.Now; 47model.Val = new Random().Next(0, 2000); 48 49var dataBuffer = JsonConvert.SerializeObject(model); 50//將資料封裝到Message物件 51var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer)); 52//通過DeviceClient將資料傳送到雲端 53await deviceClient.SendEventAsync(eventMessage).ConfigureAwait(false); 54} 55 56} 57 58/// <summary> 59/// 實體物件 60/// </summary> 61class Info 62{ 63public int Val { get; set; } 64 65public 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 { 9class Program 10{ 11static void Main(string[] args) 12{ 13ReceiveCommands().Wait(); 14} 15 16static async Task ReceiveCommands() 17{ 18//iot-hub服務連線字串 19var conn = "HostName=myHub.azure-devices.cn;SharedAccessKeyName=iothubowner;SharedAccessKey=km7jjceOUr+98865="; 20//iot-hub服務內的裝置名稱 21var device = "myDevice"; 22//建立一個EventHubClient物件 23var eventHubClient = EventHubClient.CreateFromConnectionString(conn, "messages/events"); 24var eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount; 25//從指定的裝置中獲取資料 26var partition = EventHubPartitionKeyResolver.ResolveToPartition(device, eventHubPartitionsCount); 27var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.Now); 28 29while (true) 30{ 31try 32{ 33//從Iot-Hub雲端獲取資料 34var receivedMessage = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)); 35if (receivedMessage != null) 36{ 37var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); 38if (!string.IsNullOrEmpty(messageData)) 39{ 40Console.WriteLine(messageData); 41} 42} 43} 44catch 45{ 46} 47} 48} 49 50} 51 } 52
3、分別執行“Production”與“Consume”端後,也可在Azure的Iot-Hub控制檯檢視實時報表,如下:
總結
1、通過Azure雲端的Iot-Hub服務可以非常高效的實現Iot裝置的管理與資料採集。
2、在.NetCore2程式中使用由微軟提供的“Microsoft.Azure.Devices.Client”、“Microsoft.Azure.Devices”、“Microsoft.ServiceBus”類庫,可以非常簡便的在程式中整合Iot-Hub。
宣告
本文為作者原創,轉載請備註出處與保留原文地址,謝謝。如文章能給您帶來幫助,請點下推薦或關注,感謝您的支援!