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. This quickstart involves two C# applications that take advantage of device streams to send data back and forth (echo).

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

Prerequisites

  • 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
  • The two sample applications that you run in this quickstart are written in C#. You need the .NET Core SDK 2.1.0 or later on your development machine.

    Download the .NET Core SDK for multiple platforms from .NET.

    Verify the current version of C# on your development machine by using the following command:

    dotnet --version
    
  • Download the Azure IoT C# samples and extract the ZIP archive. You need it on both the device side and the service side.

  • Use the Bash environment in Azure Cloud Shell.

    Launch Cloud Shell in a new window

  • If you prefer, install the Azure CLI to run CLI reference commands.

    • If you're using a local installation, sign in to the Azure CLI by using the az login command. To finish the authentication process, follow the steps displayed in your terminal. For additional sign-in options, see Sign in with the Azure CLI.

    • When you're prompted, install Azure CLI extensions on first use. For more information about extensions, see Use extensions with the Azure CLI.

    • Run az version to find the version and dependent libraries that are installed. To upgrade to the latest version, run az upgrade.

Note

This article uses the newest version of the Azure IoT extension, called azure-iot. The legacy version is called azure-cli-iot-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.

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.

    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: Networking to continue creating your hub.

    Choose the endpoints that can connect to your IoT Hub. You can select the default setting Public endpoint (all networks), or choose Public endpoint (selected IP ranges), or Private endpoint. Accept the default setting for this example.

    Choose the endpoints that can connect.

  6. Select Next: Management 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.

    • Defender for IoT: 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.

  7. 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.

  8. 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.

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

Register a device

A device must be registered with your IoT hub before it can connect. In this section, you use Azure Cloud Shell 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 connection-string show --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}

  3. You also need the service connection string from your IoT hub to enable the service-side application to connect to your IoT hub and establish a device stream. The following command retrieves this value for your IoT hub:

    Note

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

    az iot hub show-connection-string --policy-name service --name {YourIoTHubName} --output table
    

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

    "HostName={YourIoTHubName}.azure-devices.net;SharedAccessKeyName=service;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 service-side application

In a local terminal window, navigate to the iot-hub/Quickstarts/device-streams-echo/service directory in your unzipped project folder. Keep the following information handy:

Parameter name Parameter value
ServiceConnectionString The service connection string of your IoT hub.
MyDevice The identifier of the device you created earlier.

Compile and run the code with the following commands:

cd ./iot-hub/Quickstarts/device-streams-echo/service/

# Build the application
dotnet build

# Run the application
# In Linux or macOS
dotnet run "{ServiceConnectionString}" "MyDevice"

# In Windows
dotnet run {ServiceConnectionString} MyDevice

The application will wait for the device application to become available.

Note

A timeout occurs if the device-side application doesn't respond in time.

Run the device-side application

In another local terminal window, navigate to the iot-hub/Quickstarts/device-streams-echo/device directory in your unzipped project folder. Keep the following information handy:

Parameter name Parameter value
DeviceConnectionString The device connection string of your IoT Hub.

Compile and run the code with the following commands:

cd ./iot-hub/Quickstarts/device-streams-echo/device/

# Build the application
dotnet build

# Run the application
# In Linux or macOS
dotnet run "{DeviceConnectionString}"

# In Windows
dotnet run {DeviceConnectionString}

At the end of the last step, the service-side application initiates a stream to your device. After the stream is established, the application sends a string buffer to the service over the stream. In this sample, the service-side application simply echoes back the same data to the device, which demonstrates a successful bidirectional communication between the two applications.

Console output on the device side:

Console output on the device side

Console output on the service side:

Console output on the service side

The traffic being sent over the stream is tunneled through the IoT hub rather than sent directly. The benefits provided are detailed in Device streams benefits.

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 C# applications on the device and service sides, and used the stream to send data back and forth between the applications.

To learn more about device streams, see: