Quickstart: Communicate to a device application in C via IoT Hub device streams (preview)

Azure IoT Hub currently supports device streams as a preview feature.

IoT Hub device streams allow service and device applications to communicate in a secure and firewall-friendly manner. During public preview, the C SDK supports device streams on the device side only. As a result, this quickstart covers instructions to run only the device-side application. To run a corresponding service-side application, see these articles:

The device-side C application in this quickstart has the following functionality:

  • Establish a device stream to an IoT device.

  • Receive data that's sent from the service-side application and echo it back.

The code demonstrates the initiation process of a device stream, as well as how to use it to send and receive data.

Use Azure Cloud Shell

Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can use either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

To start Azure Cloud Shell:

Option Example/Link
Select Try It in the upper-right corner of a code block. Selecting Try It doesn't automatically copy the code to Cloud Shell. Example of Try It for Azure Cloud Shell
Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. Launch Cloud Shell in a new window
Select the Cloud Shell button on the menu bar at the upper right in the Azure portal. Cloud Shell button in the Azure portal

To run the code in this article in Azure Cloud Shell:

  1. Start Cloud Shell.

  2. Select the Copy button on a code block to copy the code.

  3. Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. Select Enter to run the code.

If you don’t have an Azure subscription, create a free account before you begin.

Prerequisites

You need the following prerequisites:

  • Install Visual Studio 2019 with the Desktop development with C++ workload enabled.

  • Install the latest version of Git.

  • Run the following command to add the Azure IoT Extension for Azure CLI to your Cloud Shell instance. The IOT Extension adds IoT Hub, IoT Edge, and IoT Device Provisioning Service (DPS)-specific commands to the Azure CLI.

    az extension add --name azure-iot
    

    Note

    This article uses the newest version of the Azure IoT extension, called azure-iot. The legacy version is called azure-iot-cli-ext.You should only have one version installed at a time. You can use the command az extension list to validate the currently installed extensions.

    Use az extension remove --name azure-cli-iot-ext to remove the legacy version of the extension.

    Use az extension add --name azure-iot to add the new version of the extension.

    To see what extensions you have installed, use az extension list.

The preview of device streams is currently supported only for IoT hubs that are created in the following regions:

  • Central US
  • Central US EUAP
  • North Europe
  • Southeast Asia

Prepare the development environment

For this quickstart, you use the Azure IoT device SDK for C. You prepare a development environment used to clone and build the Azure IoT C SDK from GitHub. The SDK on GitHub includes the sample code that's used in this quickstart.

Note

Before you begin this procedure, be sure that Visual Studio is installed with the Desktop development with C++ workload.

  1. Install the CMake build system as described on the download page.

  2. Open a command prompt or Git Bash shell. Run the following commands to clone the Azure IoT C SDK GitHub repository:

    git clone -b public-preview https://github.com/Azure/azure-iot-sdk-c.git
    cd azure-iot-sdk-c
    git submodule update --init
    

    This operation should take a few minutes.

  3. Create a cmake subdirectory in the root directory of the git repository, and navigate to that folder. Run the following commands from the azure-iot-sdk-c directory:

    mkdir cmake
    cd cmake
    
  4. Run the following commands from the cmake directory to build a version of the SDK that's specific to your development client platform.

    • In Linux:

      cmake ..
      make -j
      
    • In Windows, open a Developer Command Prompt for Visual Studio. Run the command for your version of Visual Studio. This quickstart uses Visual Studio 2019. These commands create a Visual Studio solution for the simulated device in the cmake directory.

      rem For VS2015
      cmake .. -G "Visual Studio 14 2015"
      
      rem Or for VS2017
      cmake .. -G "Visual Studio 15 2017"
      
      rem Or for VS2019
      cmake .. -G "Visual Studio 16 2019"
      
      rem Then build the project
      cmake --build . -- /m /p:Configuration=Release
      

Create an IoT hub

This section describes how to create an IoT hub using the Azure portal.

  1. Sign in to the Azure portal.

  2. From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. Select IoT Hub from the search results, and then select Create.

  4. On the Basics tab, complete the fields as follows:

    • Subscription: Select the subscription to use for your hub.

    • Resource Group: Select a resource group or create a new one. To create a new one, select Create new and fill in the name you want to use. To use an existing resource group, select that resource group. For more information, see Manage Azure Resource Manager resource groups.

    • Region: Select the region in which you want your hub to be located. Select the location closest to you. Some features, such as IoT Hub device streams, are only available in specific regions. For these limited features, you must select one of the supported regions.

    • IoT Hub Name: Enter a name for your hub. This name must be globally unique. If the name you enter is available, a green check mark appears.

    Important

    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    Create a hub in the Azure portal

  5. Select Next: Size and scale to continue creating your hub.

    Set the size and scale for a new hub using the Azure portal

    You can accept the default settings here. If desired, you can modify any of the following fields:

    • Pricing and scale tier: Your selected tier. You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the hub and up to 8,000 messages per day. Each Azure subscription can create one IoT hub in the free tier.

      If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. For details about the other tier options, see Choosing the right IoT Hub tier.

    • Azure Security Center: Turn this on to add an extra layer of threat protection to IoT and your devices. This option is not available for hubs in the free tier. For more information about this feature, see Azure Security Center for IoT.

    • Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most hubs need only four partitions.

  6. Select Next: Tags to continue to the next screen.

    Tags are name/value pairs. You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. for more information, see Use tags to organize your Azure resources.

    Assign tags for the hub using the Azure portal

  7. Select Next: Review + create to review your choices. You see something similar to this screen, but with the values you selected when creating the hub.

    Review information for creating the new hub

  8. Select Create to create your new hub. Creating the hub takes a few minutes.

Register a device

You must register a device with your IoT hub before it can connect. In this section, you use Azure Cloud Shell with the IoT Extension to register a simulated device.

  1. To create the device identity, run the following command in Cloud Shell:

    Note

    • Replace the YourIoTHubName placeholder with the name you chose for your IoT hub.
    • For the name of the device you're registering, it's recommended to use MyDevice as shown. If you choose a different name for your device, use that name throughout this article, and update the device name in the sample applications before you run them.
    az iot hub device-identity create --hub-name {YourIoTHubName} --device-id MyDevice
    
  2. To get the device connection string for the device that you just registered, run the following command in Cloud Shell:

    Note

    Replace the YourIoTHubName placeholder with the name you chose for your IoT hub.

    az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyDevice --output table
    

    Note the returned device connection string for later use in this quickstart. It looks like the following example:

    HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyDevice;SharedAccessKey={YourSharedAccessKey}

Communicate between the device and the service via device streams

In this section, you run both the device-side application and the service-side application and communicate between the two.

Run the device-side application

To run the device-side application, follow these steps:

  1. Provide your device credentials by editing the iothub_client_c2d_streaming_sample.c source file in the iothub_client/samples/iothub_client_c2d_streaming_sample folder and adding your device connection string.

    /* Paste in your iothub connection string  */
    static const char* connectionString = "{DeviceConnectionString}";
    
  2. Compile the code with the following commands:

    # In Linux
    # Go to the sample's folder cmake/iothub_client/samples/iothub_client_c2d_streaming_sample
    make -j
    
    rem In Windows
    rem Go to the cmake folder at the root of repo
    cmake --build . -- /m /p:Configuration=Release
    
  3. Run the compiled program:

    # In Linux
    # Go to the sample's folder cmake/iothub_client/samples/iothub_client_c2d_streaming_sample
    ./iothub_client_c2d_streaming_sample
    
    rem In Windows
    rem Go to the sample's release folder cmake\iothub_client\samples\iothub_client_c2d_streaming_sample\Release
    iothub_client_c2d_streaming_sample.exe
    

Run the service-side application

As mentioned previously, the IoT Hub C SDK supports device streams on the device side only. To build and run the accompanying service-side application, follow the instructions in one of the following quickstarts:

Clean up resources

If you plan to continue to the next recommended article, you can keep and reuse the resources you've already created.

Otherwise, to avoid charges, you can delete the Azure resources that you created in this article.

Important

Deleting a resource group is irreversible. The resource group and all the resources contained in it are permanently deleted. Make sure that you don't accidentally delete the wrong resource group or resources. If you created the IoT hub inside an existing resource group that contains resources that you want to keep, delete only the IoT hub resource itself, not the resource group.

To delete a resource group by name:

  1. Sign in to the Azure portal, and then select Resource groups.

  2. In the Filter by name box, enter the name of the resource group that contains your IoT hub.

  3. In the result list, to the right of your resource group, select the ellipsis (...), and then select Delete resource group.

    The "Delete resource group" button

  4. To confirm the deletion of the resource group, reenter the resource group name, and then select Delete. After a few moments, the resource group and all its contained resources are deleted.

Next steps

In this quickstart, you set up an IoT hub, registered a device, established a device stream between a C application on the device and another application on the service side, and used the stream to send data back and forth between the applications.

To learn more about device streams, see: