Quickstart: Control a device connected to an IoT hub (.NET)

IoT Hub is an Azure service that enables you to manage your IoT devices from the cloud, and ingest high volumes of device telemetry to the cloud for storage or processing. In this quickstart, you use a direct method to control a simulated device connected to your IoT hub. You can use direct methods to remotely change the behavior of a device connected to your IoT hub.

The quickstart uses two pre-written .NET applications:

  • A simulated device application that responds to direct methods called from a back-end application. To receive the direct method calls, this application connects to a device-specific endpoint on your IoT hub.

  • A back-end application that calls the direct methods on the simulated device. To call a direct method on a device, this application connects to service-side endpoint on your IoT hub.

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 top-right menu bar 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

The two sample applications you run in this quickstart are written using C#. You need the .NET Core SDK 2.1.0 or greater on your development machine.

You can download the .NET Core SDK for multiple platforms from .NET.

You can verify the current version of C# on your development machine using the following command:

dotnet --version

Run the following command to add the Microsoft 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 Azure CLI.

az extension add --name azure-cli-iot-ext

If you haven't already done so, download the sample C# project from https://github.com/Azure-Samples/azure-iot-samples-csharp/archive/master.zip and extract the ZIP archive.

Create an IoT hub

If you completed the previous Quickstart: Send telemetry from a device to an IoT hub, you can skip this step.

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.

    • 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

    This screen allows you to set the following values:

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

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

    • 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. For this article, accept the default choices, and then select Review + create to review your choices. You see something similar to this screen.

    Review information for creating the new hub

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

Register a device

If you completed the previous Quickstart: Send telemetry from a device to an IoT hub, you can skip this step.

A device must be registered with your IoT hub before it can connect. In this quickstart, you use the Azure Cloud Shell to register a simulated device.

  1. Run the following command in Azure Cloud Shell to create the device identity.

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

    MyDotnetDevice: This is the name of the device you're registering. It's recommended to use MyDotnetDevice as shown. If you choose a different name for your device, you also need to 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 MyDotnetDevice
    
  2. Run the following commands in Azure Cloud Shell to get the device connection string for the device you just registered:

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

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

    Make a note of the device connection string, which looks like:

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

    You use this value later in the quickstart.

Retrieve the service connection string

You also need your IoT hub service connection string to enable the back-end application to connect to the hub and retrieve the messages. The following command retrieves the service connection string for your IoT hub:

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

Make a note of the service connection string, which looks like:

HostName={YourIoTHubName}.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey={YourSharedAccessKey}

You use this value later in the quickstart. This service connection string is different from the device connection string you noted in the previous step.

Listen for direct method calls

The simulated device application connects to a device-specific endpoint on your IoT hub, sends simulated telemetry, and listens for direct method calls from your hub. In this quickstart, the direct method call from the hub tells the device to change the interval at which it sends telemetry. The simulated device sends an acknowledgment back to your hub after it executes the direct method.

  1. In a local terminal window, navigate to the root folder of the sample C# project. Then navigate to the iot-hub\Quickstarts\simulated-device-2 folder.

  2. Open the SimulatedDevice.cs file in a text editor of your choice.

    Replace the value of the s_connectionString variable with the device connection string you made a note of earlier. Then save your changes to SimulatedDevice.cs.

  3. In the local terminal window, run the following commands to install the required packages for simulated device application:

    dotnet restore
    
  4. In the local terminal window, run the following command to build and run the simulated device application:

    dotnet run
    

    The following screenshot shows the output as the simulated device application sends telemetry to your IoT hub:

    Run the simulated device

Call the direct method

The back-end application connects to a service-side endpoint on your IoT Hub. The application makes direct method calls to a device through your IoT hub and listens for acknowledgments. An IoT Hub back-end application typically runs in the cloud.

  1. In another local terminal window, navigate to the root folder of the sample C# project. Then navigate to the iot-hub\Quickstarts\back-end-application folder.

  2. Open the BackEndApplication.cs file in a text editor of your choice.

    Replace the value of the s_connectionString variable with the service connection string you made a note of earlier. Then save your changes to BackEndApplication.cs.

  3. In the local terminal window, run the following commands to install the required libraries for the back-end application:

    dotnet restore
    
  4. In the local terminal window, run the following commands to build and run the back-end application:

    dotnet run
    

    The following screenshot shows the output as the application makes a direct method call to the device and receives an acknowledgment:

    Run the back-end application

    After you run the back-end application, you see a message in the console window running the simulated device, and the rate at which it sends messages changes:

    Change in simulated client

Clean up resources

If you will be continuing to the next recommended article, you can keep the resources you've already created and reuse them.

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

Important

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

To delete a resource group by name:

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

  2. In the Filter by name textbox, type the name of the resource group containing your IoT Hub.

  3. To the right of your resource group in the result list, select ... then Delete resource group.

    Delete

  4. You will be asked to confirm the deletion of the resource group. Type the name of your resource group again to confirm, and then select Delete. After a few moments, the resource group and all of its contained resources are deleted.

Next steps

In this quickstart, you called a direct method on a device from a back-end application, and responded to the direct method call in a simulated device application.

To learn how to route device-to-cloud messages to different destinations in the cloud, continue to the next tutorial.