Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Azure IoT Hub and Non-IoT Applications

DZone's Guide to

Azure IoT Hub and Non-IoT Applications

Azure's IoT Hub opens doors for communication, even using custom IoT protocols to send bi-directional messages and change states.

· IoT Zone
Free Resource

Cisco IoT makes digital transformation a reality in factories, transportation, and utilities. Learn how to start integrating with Cisco DevNet.

There are millions of API calls made to successfully execute robust applications built for web, desktop, mobile, and embedded devices. Backend communication and data transfers need to be efficient and scalable. IoT Hub from Microsoft is an excellent addition to managing application communication. It also has a lot of out-of-the-box support for communication protocols. Microsoft has gone to great lengths to help with faster and easier implementation of your custom communication protocols. In this article, we will understand the advantages of IoT Hub and how to connect non-IoT apps with it.

What Is Azure IoT Hub?

It is a fully managed service that delivers reliable and secure bi-directional communication between millions of IoT devices and works as a backend solution. You can learn more by visiting the documentation.

Why Do I Need Azure IoT Hub?

First, the IoT hub is fast, easy to implement, and provides an efficient storage mechanism. Take an example of its S2 Standard IoT Hub, which allows an unlimited number of connected devices, receiving up to 6 million messages per day, per IoT Hub unit. That's a lot of devices sending a lot of messages. If you use the standard ASP.NET WebApi using Azure SQL to store data, it would either need some serious investment in powerful hardware or require medical attention to run it successfully.

Second, if you take a typical hub, it only ingresses data, where IoT Hub utilizes bi-directional communications, making it easy to send and receive data from a specific device to other from day one.

Third, Azure IoT Hub provides multiple device-to-cloud and cloud-to-device communication options, including one-way messaging, file transfer, and request-reply methods. They also have inbuilt declarative message routing to other Azure services and delivers a queryable store for device metadata and synchronized state information.

Fourth, it follows secure communications and access control using per-device security keys or X.509 certificates and also provides extensive monitoring for device connectivity and device identity management events. It also uses device libraries for the most popular languages and platforms.

Enough talk, let’s learn how to set up IoT Hub and develop the console application.

We will use the free tier and Visual Studio 2015 Update 3 for developing the console application. To learn more about getting started with IoT Hub and C#, visit here.

Next, we will go through a scenario for two-way communication ability. You have a UWP application that is transmitting and sending messages to IoT hub, or you have a set of applications that are working together in a microservice-like setup. Based on the data being received from the applications, you need to implement a faster way of sending data back to the application: giving it instructions to do something based on what data you are receiving or simply changing a setting.

We have registered the client with the hub named 'service1' and received the required key to allow the client access the hub. Your complete client setup would look like:

static DeviceClient deviceClient;
static string _iotHubUri = "Your IoT hub's uri";
static string _deviceKey = "Enter the API key here of your IoTHub"  
static string _state = "state 0";  
static void Main(string[] args)
{
    Console.WriteLine("service1");
    deviceClient = DeviceClient.Create(_iotHubUri,
    new DeviceAuthenticationWithRegistrySymmetricKey
    ("service1", _deviceKey));  
    SendDeviceToCloudMessagesAsync();
    ReceiveMessageAsync();
    Console.ReadLine();
}


We will now append the _state string onto the output to the console using this code:

Console.WriteLine($"{ DateTime.Now } >
Sending message: { messageString } : { _state }");


We need to call the cloud-to-device receive message method with below code:

private static async void ReceiveMessageAsync()
{
    while (true)
    {
        Message receivedMessage = await
        deviceClient.ReceiveAsync();
        if (receivedMessage == null) continue;  
        Console.ForegroundColor = ConsoleColor.Yellow;  
        string message =
        Encoding.ASCII.GetString(receivedMessage.GetBytes());
        Console.WriteLine($"Received message: { message }");
        _state = message;  
        Console.ResetColor();  
        await deviceClient.CompleteAsync(receivedMessage);
    }
}


When a message is received from the cloud, it changes the _state string, which is appended to the output of the console when the client sends a message to the cloud. We need to code the client for reading the messages from IoT Hub, which sends a message to the simulated client. It looks like the following:

static async void SendMessage1()
{
    int count = 0;
    while(true)
    {
        await SendCloudToDeviceMessageAsync(count);
        count++;  
        await Task.Delay(10000);
    }
}  
private async static Task
SendCloudToDeviceMessageAsync(int count)
{
    var commandMessage = new
    Message(Encoding.ASCII.GetBytes($"state { count }"));
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Sending message to service1...");
    Console.ResetColor();
    await serviceClient.SendAsync("service1", commandMessage);
}


Let’s test drive the connection now, and you will see that the reader is showing messages from the hub in the second image.

Image title

This is a very simple way to understand application communication using IoT Hub that shows a message being sent from the hub to the simulated device client and changing its state in some small way. 

Did you face any difficulty in integrating or understanding the code? Let us know in the comments below.

Cisco is a software company. Surprised? Don’t be. Join DevNet to explore APIs, tools, and techniques that developers are using to add collaboration, IoT, security, network priority, and more!

Topics:
iot communication ,cloud communication ,azure iot hub ,iot ,tutorial

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}