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:
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.
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.
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.
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:
- Select + Create a resource
- Select Internet of Things
- Select IoT Hub
- Enter the name of your IoT Hub.
- Enter the price and scale (the free version can receive up to 8,000 messages a day).
- Leave the number of units at 1.
- Leave the number of partitions at 2.
- Select your Azure Resource Group for your IoT Hub. If you don't yet have one, create one.
- Leave the subscription as it is.
- Select your location for the IoT Hub.
- Press Create and wait.
Creating storage and linking to the IoT Hub in Azure
- Select File upload and then Azure storage container in the IoT Hub
- Select + Storage account, enter the name and confirm with OK
- Select your storage account and then + Container. Enter the name for the container and confirm with OK
- Click Select
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.
You can now start setting up the connection between the various components. You need four different 'connection strings' for the Azure IoT Hub:
- Device connection string
- Event Hub connection string
- Device management connection string
- Storage connection string
Device connection string
You need this connection string to send messages to the IoT Hub.
- In the IoT Hub, select IoT Devices
- Select your device
- Press the copy icon.
Event Hub connection string
This connection string is necessary for receiving messages from the Event Hub linked to the IoT Hub.
- In the IoT Hub, select Endpoints
- Select Events
- Press copy icon for the Event Hub name
- Press copy icon for the connection string
Device management connection string
This connection string is necessary for sending commandos to a device by way of the IoT Hub.
- Select Share access policies
- Select service
- Press copy icon
Storage connection string
You need this connection string if you're using a WebJob trigger to read out the Event Hub.
- In the storage, select Access keys
- Press copy icon at connection string
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'
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:
- Select Cloud (you may have to install the Azure SDK)
- Select Azure WebJob
- Give your WebJob a name
- Click on OK
After this, it's necessary that you add some NuGet packages.
- Search in the NuGet package manager for 'Microsoft.Azure.WebJobs.Extensions' and click on Install
- Search in the NuGet package manager for 'Microsoft.Azure.WebJobs.ServiceBus' and click on Install
Then add your storage connection string in the app.config at 'AzureWebJobsDashboard' and 'AzureWebJobsStorage'.
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'.
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
Profiting from the Azure IoT Hub? Starters' guide for developers