Click the Azure IoT Button – Part 1

Microsoft Azure offers great features for IoT devices. A simple device is the Azure IoT button. This button is – using a wireless network – connected to the Azure IoT hub. Clicking the button allows to trigger any Azure service. I’ve created an application to call back into a .NET Core client application. Using multiple buttons, this application gets the information about which button was clicked – which is described in this article series.

The first article of this series gets into the configuration of the IoT button using the Azure IoT Hub and an Azure Function. The Function is invoked when the button is clicked. In later articles, the application is extended using a custom SignalR Service, and the consumption-based service Azure SignalR Services.

Button

Solution

The button is connected to Microsoft Azure using the MQTT over HTTP. The Azure IoT Hub contains a twin device representing the button. As the button is clicked, data is sent to the Azure Service Bus. I’ve created an Azure Function app that is connected to the Service Bus. The Azure Function App has an outbound binding to an Azure SignalR Service. This in turn sends messages to all connected clients.

Application Architecture

Azure IoT Hub

Let’s start with the IoT hub. Creating the hub in the Azure Portal, the name, region, and resource group needs to be specified. On configuration you can choose the size and scale, and thus define the price to pay. The standard tier starting at a price of USD 25,- per month gives you all the options up to 400,000 messages a day, and you can scale it up to any number of messages. The basic tier (starting at USD 10,-) is limited in functionality as you can’t send cloud-to-device messages, there’s no support for IoT Edge devices. With the button these features are not needed. There’s also a free scale with all features but limited to 8,000 messages per day. Clicking the IoT button, that’s enough for a start.

To configure a twin device, the connection string of the hub is needed to configure a twin device. Let’s remember that configuration from the Shared Access Policies for the next step.

Create a Twin Device

In the Azure IoT hub, a twin device needs to be created for the button. This twin receives events from the button. With more advanced devices, it’s also possible to send commands from the twin to the device, e.g. to change the configuration or to update the software of the device. To create a twin device, you can use the Device Explorer. The Device Explorer application can be downloaded from Device Explorer. Get the source code for the Device Explorer from GitHub.

With Device Explorer, first the connection string to the Azure IoT Hub needs to be configured. This string can be copied from the Shared Access Policies in the IoT hub. After supplying the connection, a new device can be created:

Device Explorer

As you configure the twin in the Device Explorer, you can get the status of the device in the Azure Portal. It’s listed there in the Azure IoT Hub in the category IoT devices.

From the Device Explorer, the id you configured for the button, the key for the button, as well as the URL for the Azure IoT hub is required. The physical device is configured with the next step. It’s best to copy the information from the device explorer locally as with the next step to configure the device, the WLAN service from the button is used, and thus Internet access is not available.

Configure the Device

Next, you need to configure the physical button. The button needs to be configured to map to connect to an available wireless network, to connect to the twin, and what information should be sent when clicking the button. You can start the configuration by pressing the button for about five seconds. After five seconds, the button light starts flashing yellow, and then shows a red light. Now, the button is ready for configuration. You can connect to the wireless network of the button. The network name starts with ESP_. After connecting to its network, the button is accessible from the IP address 192.168.4.1.

Using a browser, access the IP address 192.168.4.1 to configure the link of the Azure IoT Hub, the name of the device, and the key of the device. This maps the device to the Azure device twin. The wireless network that should be used to connect from the button to Microsoft Azure needs to be configured as well.

Configure Azure Settings

Another configuration is the JSON data that should be sent to Azure. You can use this information to check what button was clicked.

Configure JSON

With every configuration change that is done, the Save button needs to be clicked. After all the configuration is done, another dialog should be used to shutdown the button. This restarts the button with the new configuration.

Shutdown

In case you don’t have a physical Azure IoT Button yet, you can also use the Azure IoT Button Simulator to simulate button clicks – but this is half the fun.

Events in the Azure IoT Hub

With the Azure IoT Hub, the device twin, and the configuration of the physical device you can already click the button. If the button can successfully send the information, it flashes green after it was clicked, and ends with a green light. If it ends with a red light, sending the information was not successful, e.g. because the wireless network cannot be reached.

You can monitor events send from the button to the Azure IoT hub using the Device Explorer. Here you can see the JSON received:

Monitoring with the *Device Explorer*

With the Azure Portal, you can also see information about all devices in the Azure IoT Hub with the IoT devices section. Clicking on a specific device allows to check the Device twin which reveals the status of the device and the last times the device sent messages – with the button e.g. the last key press.

Checking the *Device twin*

To programmatically receive information from a device, there are two major options with the Azure IoT Hub. You can use the Events section and create event subscriptions (using the Event Grid), and Message Routing which can be used for telemetry data.

With the Event Grid (in the Events section), it’s easy to create subscriptions to events of devices. Azure Functions, Logic Apps, Web Hooks, and more services can be easily connected to non-telemetry data such as when devices are created, deleted, connected, and disconnected. The maximum size of the message is 64 KB.

At the time of this writing, using Event Grid for telemetry data is in preview. This article uses message routing, but using the Event Grid can be in a future article.

Using Message Routing it’s possible to filter messages based on application properties and the message body, send messages to Event Hubs, Azure Storage, and the Service Bus. Here, the maximum message size has a limit of 256 KB with a device-to-cloud message. The probably most important difference with the Event Grid is that using Message Routing allows sending of telemetry data.

With the application created, telemetry data is used to send information from the button to the Azure IoT Hub. It would be possible to create a custom endpoint to e.g. route button clicks from different tenants to different endpoints. However, pay attention that the maximum number of additional endpoints for S1, S2, and S3 tiers is 10. Based on the usage plans it might not be useful to route messages for different tenants to different endpoints. With the scenario here, messages from all tenants are sent to a single Azure SignalR Service, and the routing to different tenants can happen here. If no new endpoint is created, by default all the messages are routed to messages/events.

With the Built-in endpoints you can access the endpoint configuration needed by the Azure Function.

Endpoint configuration for the Service Bus Endpoint

Azure Functions

Azure Functions are an Azure consumption-based offering where the cost is calculated based on the number of executions and the execution time calculated in GB-seconds. A free grant is available with 1 million executions and 400,000 GB-s. Using the same C# code, it’s also possible to switch to an app-service based pricing model with the same app-services used with Web apps.

A great feature of Azure Functions is how they are triggered to start. They can be triggered from an HTTP request, a message to a Microsoft Azure Storage queue, a timer, and many other different bindings. A trigger that is used here is the IoT Hub trigger.

With the sample application, the project (Azure Functions project) ClickToSignalRApp project is created. Selecting the project type Azure Functions gives the option to trigger the function based on an IoT Hub trigger. Here, an Azure Storage account can be configured to send diagnostic information from the Azure Function. The name of the configuration key that references the Azure Service Bus needs to be defined with the Connection String setting. The default setting of the path is messages/events, which is the path of the default endpoint with the Message Routing functionality described earlier.

Azure Functions Template

The endpoint to the Azure IoT Hub service bus needs to be configured in the configuration file of the Azure Function. For local testing, this is done in the file local.settings.json. The name of configuration key configured in the project template is used with the IOTHubTrigger attribute.

With the sample source code in the first step only the name of the function is changed. The attribute IotHubTrigger is just an alias to the EventHubTrigger attribute as you can see with the using directive on top. The property Connection references the Azure Service Bus from the Azure IoT Hub defined in local.settings.json.

using IoTHubTrigger = Microsoft.Azure.WebJobs.EventHubTriggerAttribute;

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.EventHubs;
using System.Text;
using System.Net.Http;
using Microsoft.Extensions.Logging;

namespace ClickToSignalRApp
{
  public class ClickToSignalRFunction
  {
    [FunctionName("ClickToSignalRFunction")]
    public void Run(
      [IoTHubTrigger("messages/events", Connection = "IOTButtonConnectionString")]
        EventData message, ILogger log)
    {
      string json = Encoding.UTF8.GetString(message.Body.Array);
      log.LogInformation($"C# IoT Hub trigger function processed a message: {json}");
    }
  }
}

This is all what’s needed to test the application locally. You can start the Azure Function in the debugger and set a breakpoint to the Run method. Clicking the button triggers an invocation of this method. With the EventData parameter, information from the button is received. Accessing the Body property, you can read the time of the click and the JSON data configured with the button.

Debugging the Azure Function

Summary

Communication with devices can easily be done using twins in the Azure IoT Hub. Information about button clicks can be read from the device twin. Azure Functions allows for triggering on events from IoT devices. The Function just needs to be bound to the Service Bus available with the IoT Hub to react on button events.

In the next article of this series, the app is extended using a SignalR Service to invoke a .NET Core client application.

If you’ve read this far, consider buying me a coffee which helps me staying up longer and writing more articles.

Buy Me A Coffee

Interesting Links for this article:

Communicate with your IoT hub using the MQTT protocol

Azure IoT Button

Azure IoT Button Simulator

Device Explorer

Source Code for the Azure IoT Button

Complete code sample

Bonus Chapter 3 – SignalR and WebHooks

More information on C# and programming .NET Core applications is in my book Professional C# 7 and .NET Core 2.0, and in my workshops.

Enjoy learning and programming!

Christian

Button Image © 350jb

4 thoughts on “Click the Azure IoT Button – Part 1

  1. Hi Christian,

    thanks for the great post! Any experience/recommendations for hardware buttons? Also, the screenshots are not linked to the original picture and very small 😉 On the other hand, I should get glasses anyway…

    cheers,
    Stefan

    Like

  2. Hi Stefan,

    “Open image in new tab” should give you the full picture size.
    I can’t give you a recommendation on a really good button yet. For “normal users” it’s too hard to click the Azure IoT button – it needs to be pressed for about 1 second, and then pay attention after the light flashes if it’s then green or red for a short amount of time. I’m sure there are better ones.

    Thanks,
    Christian

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.