Azure IoT technology research series 3-device-to-cloud, cloud-to-device communications, azureiot

Source: Internet
Author: User

Azure IoT technology research series 3-device-to-cloud, cloud-to-device communications, azureiot

In the previous blog, we registered the simulated device to Azure IoT Hub: We got the unique identifier of the device.

Azure IoT technology research series 2-device registration to Azure IoT Hub

In this article, we will continue to conduct in-depth research on device-to-cloud and cloud-to-device communication.

1. receive messages from analog devices in Azure IoT Hub

The Event Hub compatible endpoint for reading messages from devices to the cloud. The AMQP protocol is used.

Create a Console project: IoTServer and add Nuget reference: WindowsAzure. ServiceBus

Core namespace: using Microsoft. ServiceBus. Messaging;

Core class: EventHubClient

Use EventHubClient to create an EventHubReceiver to continuously receive messages from the device side.

1         static string connectionString = "HostName=IoTTest.*******;SharedAccessKeyName=iothubowner;SharedAccessKey=***";2         static string iotHubD2cEndpoint = "messages/events";3         static EventHubClient eventHubClient;

The ReceiveMessagesFromDeviceAsync method is as follows:

1 /// <summary> 2 // receive messages from the device side 3 /// </summary> 4 /// <param name = "partition"> partition </param> 5 // <param name = "ct"> unmark </param> 6 // <returns> Task </returns> 7 private static async Task ReceiveMessagesFromDeviceAsync (string partition, cancellationToken ct) 8 {9 var eventHubReceiver = eventHubClient. getdefaconconsumergroup ().CreateReceiver(Partition, DateTime. utcNow); 10 while (true) 11 {12 if (ct. isCancellationRequested) break; 13 EventData eventData = await eventHubReceiver. receiveAsync (); 14 if (eventData = null) continue; 15 16 string data = Encoding. UTF8.GetString (eventData. getBytes (); 17 Console. writeLine ("Message received ed. partition: {0} Data: '{1}' ", partition, data); 18 19 // prevent the CPU from occupying 20 tasks. delay (1 ). wait (); 21} 22}

In the Main function, we Run the entire IoTServer:

1 static void Main (string [] args) 2 {3 Console. writeLine ("Azure IoT Hub receives messages ..., press Ctrl-C to exit. \ n "); 4 eventHubClient = EventHubClient.CreateFromConnectionString(ConnectionString,IotHubD2cEndpoint); 5 6 var d2cPartitions = eventHubClient. getRuntimeInformation (). partitionIds; 7 8 CancellationTokenSource cts = new CancellationTokenSource (); 9 10 System. console. cancelKeyPress + = (s, e) => 11 {12 e. cancel = true; 13 cts. cancel (); 14 Console. writeLine ("Exiting... "); 15}; 16 17 var tasks = new List <Task> (); 18 foreach (string partition in d2cPartitions) 19 {20 tasks. add (ReceiveMessagesFromDeviceAsync (partition, cts. token); 21} 22 23 Task. waitAll (tasks. toArray (); 24}

2. simulate a device to send messages to Azure IoT Hub

We also created a Console project: Device to simulate sending messages to Azure IoT Hub.

Add Nuget reference: Microsoft. Azure. Devices. Client. This Nuget depends on a lot of Nuget. Don't worry, Install it slowly

Core namespaces:

Using Microsoft. Azure. Devices. Client;
Using Newtonsoft. Json;

Core category:

Microsoft. Azure. Devices. Client. DeviceClient

When a simulated device sends messages to the Azure IoT Hub, it uses the device Key (unique identifier) and IoT Hub HostName. The host name mentioned in the previous blog: azure IoT technology research series 2-device registration to Azure IoT Hub

1         static DeviceClient deviceClient;2         static string iotHubUri = "IoTTest.******";          //iot hub hostname3         static string deviceKey = "+jDqO+Nu2g************="; //device key

Add a method to send messages cyclically to Azure IoT Hub: SendDeviceToCloudMessagesAsync, one message per second

1 /// <summary> 2 // send messages cyclically to Azure IoT Hub 3 /// </summary> 4 private static async void SendDeviceToCloudMessagesAsync () 5 {6 double avgWindSpeed = 10; // m/s 7 Random rand = new Random (); 8 9 while (true) 10 {11 // send telemetry data 12 double currentWindSpeed = avgWindSpeed + rand. nextDouble () * 4-2; 13 var telemetryDataPoint = new14 {15 deviceId = "TeldPile001", 16 windSpeed = currentWindSpeed17}; 18 var messageString = JsonConvert. serializeObject (telemetryDataPoint); 19 var message = new Message (Encoding. ASCII. getBytes (messageString); 20 21 await deviceClient. sendEventAsync (message); 22 Console. writeLine ("{0}> Sending message: {1}", DateTime. now, messageString); 23 24 // 1 s a 25 await Task. delay (1000); 26} 27}

Then, start the simulated device in the Main function to send messages:

1 static void Main (string [] args) 2 {3 Console. writeLine ("Analog Device communication... \ n "); 4 deviceClient = DeviceClient. create (iotHubUri, new deviceauthenticationwithregistrypolicrickey ("TeldPile001", deviceKey), TransportType. mqtt); 5 6 SendDeviceToCloudMessagesAsync (); 7 Console. readLine (); 8}

3. Start the run test

Set a dual-startup project in the solution: Device and IoTServer

F5 Run:

It can be found that device-side message sending and Azure IoT Hub receiving are synchronous.

View the statistics in the Azure Portal:

 

Conclusion: through these two blog posts, we have verified the registration of devices, devices, and cloud communications between Azure IoT Hub. We feel that the entire Azure IoT Hub is still very easy to use and use, it is easy to understand and operate. Based on the PaaS-layer IoT Hub, you can do a lot of valuable designs and solutions.

 

Zhou Guoqing

2017/4/18

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.