Azure IoT Hub sample application

The Azure IoT Hub sample application shows how to connect to and communicate with an Azure IoT Hub. It also demonstrates a feature of the Azure Sphere WifiConfig API.

This sample uses the Connected Service for Azure Sphere, which is installed with the Azure Sphere SDK. This Visual Studio extension provides a template for connecting your device to an IoT Hub and communicating with the hub. It is similar to the Visual Studio Connected Service for Azure IoT Hub but provides Azure Sphere-specific features. Applications that use the Connected Service functionality can send messages to and receive messages from an IoT Hub, maintain a device twin, and respond to direct method calls from cloud service applications.

This sample does the following:

  • Displays the currently connected Wi-Fi network.

  • Blinks LED 1 constantly. Pressing button A changes the rate between three values. The rate is also stored in the device twin, where a cloud service program can change it.

  • Sends a message to the IoT Hub when you press button B.

  • Lights LED 3 green after start-up to indicate that the device has connected to the IoT Hub and the application has successfully authenticated with the hub.

  • Changes the color of LED 1 in response to a direct method call.

Prerequisites

You must complete these steps before you run this sample:

Set up Microsoft Azure credentials

To run this sample, you must have a Microsoft Azure subscription. If your organization does not already have one, follow these instructions to set up a free trial subscription to Microsoft Azure.

After you set up the subscription, you can create a hub. Log into the Azure Portal and follow these instructions to set up your hub and DPS and to link them together. If you already have a hub that is linked to DPS, you can skip step 1 in those instructions but you must still perform steps 2 through 5 to enable authentication and automatic enrollment.

Add your device to the IoT Hub

To add your Azure Sphere device to an IoT hub, you use the IoT Hub Device Provisioning Service. The Connected Service helps you do this by adding code to your Azure Sphere application:

  • Adds azure_iot_utilites.c and azure_iot_utilities.h to your application. The files contain sample code that demonstrates how to use the Azure IoT SDK. You can adapt it to fit your needs. It includes an important Azure Sphere SDK function call to IoTHubDeviceClient_LL_CreateWithAzureSphereDeviceAuthProvisioning. This call configures the IoT Hub SDK to connect to the Device Provisioning Service and your IoT Hub using the device certificate issued during Azure Sphere device authentication and attestation.

  • Gets the hostnames of the IoT Hubs that are linked to your Device Provisioning Service instance and adds them to the AllowedConnections field in app_manifest.json. This ensures that the Azure Sphere OS firewall allows outbound connections from the application to these URLs.

  • Adds the global Device Provisioning Service hostname ("global.azure-devices-provisioning.net") to the AllowedConnections field in app_manifest.json. This ensures that the Azure Sphere OS firewall allows outbound connections from the application to this URL.

  • Adds the scope ID of the Device Provisioning Service to the IoTHubDeviceClient_LL_CreateWithAzureSphereDeviceAuthProvisioning function call mentioned above. The scope ID uniquely identifies your Device Provisioning Service instance.

  • Adds the Azure Sphere tenant ID to the Capabilities/DeviceAuthentication field in app_manifest.json.

To add your device to the IoT hub

  1. Start Visual Studio 2017 and go to File>New>Project. The templates for Azure Sphere are available in Visual C++>Cross Platform>Azure Sphere. Select Azure IoT Hub Sample for MT3620 RDB (Azure Sphere), specify a name and location, and select OK.

  2. In Solution Explorer, right-click References and then select Add Connected Service.

    Add Connected Service pop-up

  3. Select Device Connectivity with Azure IoT from the list of connected services.

    Add Connected Service to code

  4. If prompted, log in to the account you're using with your Azure Sphere tenant.

  5. In the Device Connectivity with Azure IoT menu, select your Azure subscription from the Subscription dropdown.

    Add Device Provisioning Service

  6. Select Device Provisioning Service from the Connection Type dropdown.

  7. Select your Device Provisioning Service instance from the Device Provisioning Service dropdown.

  8. Click Add.

  9. In Solution Explorer, you should now see azure_iot_utilities.h and azure_iot_utilities.c in your solution.

    Azure IoT Hub files in solution

    In addition, the host name for the Azure IoT Hub has been added to the Capabilities section of the app_manifest.json file. An application can connect only to the internet hosts that are specified in the AllowedConnections field.

Prepare the sample

Now you can build the application and use the Azure IoT Hub. In this walkthrough, we will use existing IoT Hub tools to monitor and communicate with your device.

To prepare the sample code

  1. Open main.c in the sample application.

  2. Press F5 to build, load, and start the sample.

    The sample opens handles to the buttons and RGB LEDs on the board, and displays the currently connected Wi-Fi network.

    It then starts the main loop. You should see LED 1 start to blink and see output like the following in the Device Output window:

    Device Output window for Azure IoT Hub sample

Set up Device Explorer

The following sections describe how to see device-to-cloud messages, send cloud-to-device messages, request changes to the device twin, and make direct method calls. This walkthrough uses Device Explorer, a utility that is the easiest way to interact with your device from an IoT Hub. Azure Portal and IoT Hub Explorer provide many of the same capabilities.

Note

The direct method calls made from the Azure Portal do not work with this Azure Sphere sample because they use escaped strings, which aren't compatible with this sample.

To install Device Explorer

Note

This tool is called Device Explorer Twin in its window banner. Some versions of the tool may return an epoch error at random times during use. In most cases, you can close the error notification pop-up and continue using the tool. If the tool fails to operate properly after the error, quit the tool and restart it.

Send and receive messages

Device Explorer is an interactive application that lets you see messages from your device to the cloud and send messages from the cloud to your device.

To get your IoT Hub Connection String

Before you can configure Device Explorer, you need to get your IoT Hub Connection String:

  • Go to the Azure Portal.

  • Click on your IoT Hub.

  • Under Settings, click Shared access policies.

  • Click iothubowner.

  • Copy the text under Connection string—primary key.

To send and receive messages

  1. Run Device Explorer. You can find it on the Start menu under Azure IoT Hub.

  2. On the Configuration tab, paste the IoT Hub Connection String that you copied from above and click update.

  3. On the Data tab, select your device from the Device ID dropdown menu and press Monitor.

  4. Press button B on your Azure Sphere device to send a message to the cloud. If Device Explorer displays an error box describing an endpoint epoch error, restart Device Explorer.

  5. In Device Explorer, check the Data tab to see the message from your device. In some situations, a delay may occur before the messages appear, and you’ll sometimes see a batch of device-to-cloud messages at once.

  6. In Device Explorer, open the Messages to Device tab and select your device from the Device ID dropdown menu. Type a message in the Message box, add a timestamp if you want, and press Send.

  7. In Visual Studio, your message should appear in the Output window for Device Output.

Call a direct method on the device

Applications that use an IoT Hub can respond to direct method calls from applications that run in the cloud. For example, a cloud-service application might collect data from the IoT Hub and then call the application on the device to reset a counter.

The example registers the DirectMethodCall() function to handle direct method calls. When a cloud service application calls a method on the device, this callback parses the method name and payload and responds appropriately.

To call a method on the device

  1. Make sure that the application is running, and is not stopped at a breakpoint.

  2. In Device Explorer, open the Call Method on Device tab. Ensure that the IoT Hub and Device ID are correct.

  3. In the Method name box, type LedColorControlMethod, and in the Method payload box type {"color":"green"}. Then press Call Method. The sample is hardcoded to check for calls to LedColorControlMethod. When you call LedColorControlMethod with this payload, LED 1 should start blinking green.

    Call method dialog box in Device Explorer

  4. In Visual Studio, check the Output window for Device Output. You should see:

    [Azure IoT Hub client]:INFO: Trying to invoke method LedColorControlMethod
    INFO: color set to: 'green'.

  5. In Device Explorer, check the Return status and Return payload boxes. The Return status should be 200 and the return payload should be:

    {"success":true,"message":"led color set to green”}

Manage a device twin

A device twin is a JSON document in the cloud that stores information about a device. Use the device twin to synchronize status information and maintain device properties that should be accessible to cloud service applications as well as to applications that run on the device.

To view and change the device twin

  1. While the sample program runs, open the Management tab in Device Explorer and then click Twin Props. Select your device from the drop-down menu in the bar and click Refresh. You should see the Entire Twin tab open on the left and an editable window on the right. Note that the twin for your device may have different properties and metadata than the one in the figure.

    Entire device twin

  2. When you press button A on the board, the sample changes the blink rate and reports the new rate to the device twin as LedBlinkRateProperty in the "reported" section. To see the new rate in Device Explorer, click Refresh. Note that the "reported" version number in the twin also changes.

  3. You can also change the blink rate by setting the value of LedBlinkRateProperty in the device twin. Edit the JSON in the window on the right and then press Send (use JSON format). You can set the value to 0, 1, or 2 for different blink rates.

     {
        "properties": {
           "desired": {"LedBlinkRateProperty":0}
        }
     }
    

    When you change the value of LedBlinkRateProperty, the sample updates the LED 1 blink rate and reports the new value to the twin in the "reported" section. You should see the LED blink at a different rate.

  4. In Visual Studio, check the Output window for Device Output. You should see:

    Property LedBlinkRateProperty changed, new value is "0"
    [Azure IoT Hub client]:INFO: Reported state set
    [Azure IoT Hub client]:INFO: Reported state accepted by IoT Hub. Result is: 204