Profiting from the Azure IoT Hub? Starters' guide for developers

Collecting and analysing data on a large scale is a priority for more and more software-driven organisations. They want to provide new or improved services. You'll come across a lot of IT buzzwords in this, such as 'big data', 'cloud', 'security', 'artificial intelligence', 'machine learning', and 'business intelligence (BI)'.  And also the 'Internet of Things'.

Are you interested in getting data in the cloud and improving your services?  Do you use a lot of devices, or 'things'? If so, it's advisable to use the Internet of Things (IoT).

With the 'Azure IoT Hub', Microsoft offers a central point in the Azure cloud environment to which you can send from many devices. You can also send commands to individual devices. In addition, you can place files in Azure Blob Storage through the Azure IoT Hub.

What kind of devices are we talking about? It could be anything:

Devices IoT (Visual).png

Choosing the Microsoft Azure IoT Hub offers many advantages:

  • secure communication with the hub, as standard
  • device management 'out of the box'
  • it can cope with large amounts of data
  • it's scaleable
  • sample code and software development kit (SDK) is available for multiple programming languages.

How do you set up the Azure IoT Hub? What things do you have to take into account? And how do you communicate with the Hub? Follow the steps below and you'll be able to benefit fully from the advantages of the Hub.


What is the Azure IoT Hub?

The Azure Internet of Things is a component in the Azure cloud environment that takes over messaging data and device management for you. It's a central point on the Internet where messages of no more than 256 kB can be sent through the HTTP or AMQP protocol.

Sending messages and receiving commands can be done in the following ways:

  • REST service
  • .NET SDK
  • Python SDK
  • Java SDK
  • C SDK
  • Node.js SDK

The messages from your devices arrive in the Azure Event Hub, which is in the IoT Hub. From here, they can subsequently be read.

When setting up the Azure IoT Hub, you can use the following handy tooling:

  • the Azure Portal
  • the Device Explorer
  • the Service Bus Explorer

The Azure Portal

You can set up and configure the IoT Hub In the Azure Portal. You can also create devices here and check to see if they're active. In addition, you can collect the keys necessary for communicating through code with the Azure IoT Hub.

You need an Azure account to access the Azure Portal. If you have what's known as an MSDN subscription, you already have the credit of 130 euros a month.

Azure Portal (Text Image [c]).png

The Device Explorer

With the Device Explorer, you can view the Hub aspect of the IoT Hub.

You see incoming messages and you can send commands to the devices. You can also create and remove devices.

Device explorer IoT Hub (Text Image).png

The Service Bus Explorer

With the Service Bus Explorer, you can read messages from an Event Hub. These are the messages that are sent to the IoT Hub.

You do this by creating a listener on a consumer group. You can also read out an 'Azure Service Bus' here.

Service bus explorer IoT hub.PNG

Setting up your IoT Hub in the Azure Portal

Log on to the Azure Portal and set up the IoT Hub in the following steps:

Create IoT hub (1) (Visual1).png

  1. Select + Create a resource
  2. Select Internet of Things
  3. Select IoT Hub
  4. Enter the name of your IoT Hub.
  5. Enter the price and scale (the free version can receive up to 8,000 messages a day).
  6. Leave the number of units at 1.
  7. Leave the number of partitions at 2.
  8. Select your Azure Resource Group for your IoT Hub. If you don't yet have one, create one.
  9. Leave the subscription as it is.
  10. Select your location for the IoT Hub.
  11. Press Create and wait.
Create IoT hub (2) (Text Image).png

Creating storage and linking to the IoT Hub in Azure

Create storage IoT Hub (1) (Visual1).png
  1. Select File upload and then Azure storage container in the IoT Hub
  2. Select + Storage account, enter the name and confirm with OK
  3. Select your storage account and then + Container. Enter the name for the container and confirm with OK
  4. Click Select
Create storage IoT Hub (2) (Visual2).png

Creating device

You can then add devices in the Azure IoT Hub. To do so, select 'IoT Devices' in the Hub, enter a name for your device (Device ID) through 'Add'. And lastly, save your addition.

Create device IoT hub.png

You can now start setting up the connection between the various components. You need four different 'connection strings' for the Azure IoT Hub:

  1. Device connection string
  2. Event Hub connection string
  3. Device management connection string
  4. Storage connection string

Device connection string

You need this connection string to send messages to the IoT Hub.

  1. In the IoT Hub, select IoT Devices
  2. Select your device
  3. Press the copy icon.
Device connectionstring IoT hub (Text Image).png

Event Hub connection string

This connection string is necessary for receiving messages from the Event Hub linked to the IoT Hub.

  1. In the IoT Hub, select Endpoints
  2. Select Events
  3. Press copy icon for the Event Hub name
  4. Press copy icon for the connection string
Eventhub connectionstring IoT hub (Text Image).png

Device management connection string

This connection string is necessary for sending commandos to a device by way of the IoT Hub.

  1. Select Share access policies
  2. Select service
  3. Press copy icon
Device management connectionstring IoT hub (1).png

Storage connection string

You need this connection string if you're using a WebJob trigger to read out the Event Hub.

  1. In the storage, select Access keys
  2. Press copy icon at connection string
Storage connectionstring IoT Hub (Text Image).png

Sending messages to the IoT Hub

To send messages to the IoT Hub, you use a command-line application in combination with the .NET SDK. That lets you run software simply on both Windows and Linux through 'Mono' or '.NET Core Standard'.

Create a console application in Visual Studio. Add to that references ➡ manage NuGet packages the following package 'Microsoft.Azure.Devices.Client'

NuGet Package Manager - Devices client - IoT hub (Visual).png

Once you've done this, you can send a message to the IoT Hub with the following code:

using Microsoft.Azure.Devices.Client;
using System;
using System.Text;
namespace IoTHubBlogConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionString = "YourDeviceConnectionString";
      var client = DeviceClient.CreateFromConnectionString(connectionString);
      var message = new Message(Encoding.UTF8.GetBytes($"hello @ {DateTime.Now}"));
      client.SendEventAsync(message).Wait();
    }
  }
}

Reading messages from the IoT Hub

To read messages from the Event Hub, use a WebJob with an Event Hub trigger. You usually deploy a WebJob on Azure under a WebApplication.


To create a WebJob:

  1. Select Cloud (you may have to install the Azure SDK)
  2. Select Azure WebJob
  3. Give your WebJob a name
  4. Click on OK
Create webapp webjob (Text Image).png

After this, it's necessary that you add some NuGet packages.

  1. Search in the NuGet package manager for 'Microsoft.Azure.WebJobs.Extensions' and click on Install
  2. Search in the NuGet package manager for 'Microsoft.Azure.WebJobs.ServiceBus' and click on Install
NuGet webjobs extensions & servicebus - IoT Hub (1).png

Then add your storage connection string in the app.config at 'AzureWebJobsDashboard' and 'AzureWebJobsStorage'.

Webjobconfig IoT hub (Visual).png

Go on to enter this code in the 'Program.cs':

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.ServiceBus;
namespace IotHubBlogWebappWebJob
{
  class Program
  {
    static void Main()
    {
      string eventHubName = "yourEventhubName";
      string connString = "yourEventhubConnectionstring";
      var config = new JobHostConfiguration();
      var eventHubConfig = new EventHubConfiguration();
      eventHubConfig.AddReceiver(eventHubName, connString);
      config.UseEventHub(eventHubConfig);
      JobHost host = new JobHost(config);
      host.RunAndBlock();
    }
  }
}

At 'Functions', enter the following code:

using Microsoft.Azure.WebJobs.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System.Text;
namespace IotHubBlogWebappWebJob
{
  public class Functions
  {
    public void TriggerEvents([EventHubTrigger("yourEventhubName")] EventData[] events)
    {
      foreach (var eventData in events) {
        string data = Encoding.UTF8.GetString(eventData.GetBytes());
        // doe iets met je data
      }
    }
  }
}

Sending commands to your device

Create a console application in Visual Studio. Add to that references ➡ manage NuGet packages the following package 'Microsoft.Azure.Devices'.

NuGet Package Manager - Devices services - IoT hub (Visual).png

Here is the code with which to do this, again in a command-line application. In practice, this will more likely be a service or website:

using Microsoft.Azure.Devices;
using System;
using System.Text;
namespace IoTHubBlogConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      var deviceId = "MyDevice"; //name of the device
      var text = Console.ReadLine();
      var connectionString = "YourDeviceManagementConnectionstring";
      var client = ServiceClient.CreateFromConnectionString(connectionString);
      var message = new Message(Encoding.UTF8.GetBytes(text));
      client.SendAsync(deviceId, message).Wait();
      Console.WriteLine("command send");
      Console.ReadLine();
    }
  }
}

Receiving commands on your device

To do this, you'll need the DeviceClient from the SDK. The code is as follows:

using Microsoft.Azure.Devices.Client;
using System;
using System.Text;
namespace IoTHubBlogConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionString = "YourDeviceConnectionString";
      var client = DeviceClient.CreateFromConnectionString(connectionString);
      var commando = client.ReceiveAsync().Result;
      client.CompleteAsync(commando).Wait();
      var text = Encoding.UTF8.GetString(commando.GetBytes());
      Console.WriteLine(text);
      Console.ReadLine();
    }
    }
}

You invoke the 'CompleteAsync' on the command to indicate that you have received the task.


Sending a file to Azure Blob Storage

The file will arrive in the container with the device ID in the pad. That's so that you can see which device is uploading which files. Through the DeviceClient:

using Microsoft.Azure.Devices.Client;
using System;
using System.IO;

namespace IoTHubBlogConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionString = "YourDeviceConnectionString";
      var client = DeviceClient.CreateFromConnectionString(connectionString);
      var fileInfo = new FileInfo("c:\\test\\test.png");
      if (fileInfo.Exists)
      {
        using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Open))
        {
           client.UploadToBlobAsync(fileInfo.Name, fileStream).Wait();
        }
      }
      Console.WriteLine("file send");
      Console.ReadLine();
    }
  }
}

Getting to work

You can now send messages from your device to the Azure IoT Hub. You can read out these messages from the Event Hub through a WebJob. In addition, you can send commandos from a service or website to the IoT Hub, which the devices can then pick up again.

Lastly, you've seen how to send a file from a device to the storage by way of the IoT Hub.

Lots of luck!

If you want to go into this in more detail, take a look at Azure IoT Edge. It's a new development within the Internet of Things that gives increasing functionality to the 'edge', or the devices in other words. This allows you to push functionalities, which first run in the cloud, to the devices.

If you'd like to find out more about Azure, the IoT Hub, or IoT Edge, please get in touch with us, we'd like to hear from you!


Profiting from the Azure IoT Hub? Starters' guide for developers

By Betabitter Herbert