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.
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.
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:
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.
Another configuration is the JSON data that should be sent to Azure. You can use this information to check what button was clicked.
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.
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:
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.
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.
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.
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.
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.
Interesting Links for this article:
Communicate with your IoT hub using the MQTT protocol
Source Code for the Azure IoT Button
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
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
LikeLike
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
LikeLiked by 1 person
from where to buy these button?
LikeLiked by 1 person
The button I’ve written about in this article: https://www.texxmo-shop.de/, recently I bought a different button with more functionality: https://www.seeedstudio.com/ReButton-p-2930.html
LikeLike
Do you any button with cellular(SIM)?
Thanks for help. I already order couple seeed button but also looking for with SIM.
Regards
LikeLike
Do you know if these buttons can do following :
– can these buttons send http requests?
– or is there an API to access the button data?
– I want to be able to send data from this button a database (MongoDB) let me know if you think this is possible
LikeLike
There’s no need to directly make API requests. You can do these from the backend on trigger of the button click. Using my sample, you can change the Azure Function to send data into MongoDB.
LikeLike