Tutorial: Use a simulated device to test connectivity with your IoT hub

In this tutorial, you use Azure IoT Hub portal tools and Azure CLI commands to test device connectivity. This tutorial also uses a simple device simulator that you run on your desktop machine.

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

In this tutorial, you learn how to:

  • Check your device authentication
  • Check device-to-cloud connectivity
  • Check cloud-to-device connectivity
  • Check device twin synchronization

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.

Prerequisites

The CLI scripts you run in this tutorial use the Microsoft Azure IoT Extension for Azure CLI. To install this extension, run the following CLI command:

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

The device simulator application you run in this tutorial is written using Node.js. You need Node.js v10.x.x or later on your development machine.

You can download Node.js for multiple platforms from nodejs.org.

You can verify the current version of Node.js on your development machine using the following command:

node --version

Download the sample device simulator Node.js project from https://github.com/Azure-Samples/azure-iot-samples-node/archive/master.zip and extract the ZIP archive.

Create an IoT hub

If you created a free or standard tier IoT hub in a previous quickstart or tutorial, you can skip this step.

To create an IoT Hub using the Azure portal:

  1. Sign in to the Azure portal.

  2. Select Create a resource > Internet of Things > IoT Hub.

    Select to install IoT Hub

  3. To create your free-tier IoT hub, use the values in the following tables:

    Setting Value
    Subscription Select your Azure subscription in the drop-down.
    Resource group Create new. This tutorial uses the name tutorials-iot-hub-rg.
    Region This tutorial uses West US. You can choose the region closest to you.
    Name The following screenshot uses the name tutorials-iot-hub. You must choose your own unique name when you create your hub.

    Hub settings 1

    Setting Value
    Pricing and scale tier F1 Free. You can only have one free tier hub in a subscription.
    IoT Hub units 1

    Hub settings 2

  4. Click Create. It can take several minutes for the hub to be created.

    Hub settings 3

  5. Make a note of the IoT hub name you chose. You use this value later in the tutorial.

Check device authentication

A device must authenticate with your hub before it can exchange any data with the hub. You can use the IoT Devices tool in the Device Management section of the portal to manage your devices and check the authentication keys they're using. In this section of the tutorial, you add a new test device, retrieve its key, and check that the test device can connect to the hub. Later you reset the authentication key to observe what happens when a device tries to use an outdated key. This section of the tutorial uses the Azure portal to create, manage, and monitor a device, and the sample Node.js device simulator.

Sign in to the portal and navigate to your IoT hub. Then navigate to the IoT Devices tool:

IoT Devices tool

To register a new device, click + Add, set Device ID to MyTestDevice, and click Save:

Add new device

To retrieve the connection string for MyTestDevice, click on it in the list of devices and then copy the Connection string-primary key value. The connection string includes the shared access key for the device.

Retrieve device connection string

To simulate MyTestDevice sending telemetry to your IoT hub, run the Node.js simulated device application you downloaded previously.

In a terminal window on your development machine, navigate to the root folder of the sample Node.js project you downloaded. Then navigate to the iot-hub\Tutorials\ConnectivityTests folder.

In the terminal window, run the following commands to install the required libraries and run the simulated device application. Use the device connection string you made a note of when you added the device in the portal.

npm install
node SimulatedDevice-1.js "{your device connection string}"

The terminal window displays information as it tries to connect to your hub:

Simulated device connecting

You've now successfully authenticated from a device using a device key generated by your IoT hub.

Reset keys

In this section, you reset the device key and observe the error when the simulated device tries to connect.

To reset the primary device key for MyTestDevice, run the following commands:

# Generate a new Base64 encoded key using the current date
read key < <(date +%s | sha256sum | base64 | head -c 32)

# Requires the IoT Extension for Azure CLI
# az extension add --name azure-cli-iot-ext

# Reset the primary device key for MyTestDevice
az iot hub device-identity update --device-id MyTestDevice --set authentication.symmetricKey.primaryKey=$key --hub-name {YourIoTHubName}

In the terminal window on your development machine, run the simulated device application again:

npm install
node SimulatedDevice-1.js "{your device connection string}"

This time you see an authentication error when the application tries to connect:

Connection error

Generate shared access signature (SAS) token

If your device uses one of the IoT Hub device SDKs, the SDK library code generates the SAS token used to authenticate with the hub. A SAS token is generated from the name of your hub, the name of your device, and the device key.

In some scenarios, such as in a cloud protocol gateway or as part of a custom authentication scheme, you may need to generate the SAS token yourself. To troubleshoot issues with your SAS generation code, it's useful to generate a known-good SAS token to use during testing.

Note

The SimulatedDevice-2.js sample includes examples of generating a SAS token both with and without the SDK.

To generate a known-good SAS token using the CLI, run the following command:

az iot hub generate-sas-token --device-id MyTestDevice --hub-name {YourIoTHubName}

Make a note of the full text of the generated SAS token. A SAS token looks like the following: SharedAccessSignature sr=tutorials-iot-hub.azure-devices.net%2Fdevices%2FMyTestDevice&sig=....&se=1524155307

In a terminal window on your development machine, navigate to the root folder of the sample Node.js project you downloaded. Then navigate to the iot-hub\Tutorials\ConnectivityTests folder.

In the terminal window, run the following commands to install the required libraries and run the simulated device application:

npm install
node SimulatedDevice-2.js "{Your SAS token}"

The terminal window displays information as it tries to connect to your hub using the SAS token:

Simulated device connecting with token

You've now successfully authenticated from a device using a test SAS token generated by a CLI command. The SimulatedDevice-2.js file includes sample code that shows you how to generate a SAS token in code.

Protocols

A device can use any of the following protocols to connect to your IoT hub:

Protocol Outbound port
MQTT 8883
MQTT over WebSockets 443
AMQP 5671
AMQP over WebSockets 443
HTTPS 443

If the outbound port is blocked by a firewall, the device can't connect:

Port blocked

Check device-to-cloud connectivity

After a device connects, it typically tries to send telemetry to your IoT hub. This section shows you how you can verify that the telemetry sent by the device reaches your hub.

First, retrieve the current connection string for your simulated device using the following command:

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

To run a simulated device that sends messages, navigate to the iot-hub\Tutorials\ConnectivityTests folder in the code you downloaded.

In the terminal window, run the following commands to install the required libraries and run the simulated device application:

npm install
node SimulatedDevice-3.js "{your device connection string}"

The terminal window displays information as it sends telemetry to your hub:

Simulated device sending messages

You can use Metrics in the portal to verify that the telemetry messages are reaching your IoT hub. Select your IoT hub in the Resource drop-down, select Telemetry messages sent as the metric, and set the time range to Past hour. The chart shows the aggregate count of messages sent by the simulated device:

Show IoT Hub metrics

It takes a few minutes for the metrics to become available after you start the simulated device.

Check cloud-to-device connectivity

This section shows how you can make a test direct method call to a device to check cloud-to-device connectivity. You run a simulated device on your development machine to listen for direct method calls from your hub.

In a terminal window, use the following command to run the simulated device application:

node SimulatedDevice-3.js "{your device connection string}"

Use a CLI command to call a direct method on the device:

az iot hub invoke-device-method --device-id MyTestDevice --method-name TestMethod --timeout 10 --method-payload '{"key":"value"}' --hub-name {YourIoTHubName}

The simulated device prints a message to the console when it receives a direct method call:

Simulated device receives direct method call

When the simulated device successfully receives the direct method call, it sends an acknowledgement back to the hub:

Receive direct method acknowledgement

Check twin synchronization

Devices use twins to synchronize state between the device and the hub. In this section, you use CLI commands to send desired properties to a device and read the reported properties sent by the device.

The simulated device you use in this section sends reported properties to the hub whenever it starts up, and prints desired properties to the console whenever it receives them.

In a terminal window, use the following command to run the simulated device application:

node SimulatedDevice-3.js "{your device connection string}"

To verify that the hub received the reported properties from the device, use the following CLI command:

az iot hub device-twin show --device-id MyTestDevice --hub-name {YourIoTHubName}

In the output from the command, you can see the devicelaststarted property in the reported properties section. This property shows the date and time you last started the simulated device.

View reported properties

To verify that the hub can send desired property values to the device, use the following CLI command:

az iot hub device-twin update --set properties.desired='{"mydesiredproperty":"propertyvalue"}' --device-id MyTestDevice --hub-name {YourIoTHubName}

The simulated device prints a message when it receives a desired property update from the hub:

Receive desired properties

In addition to receiving desired property changes as they're made, the simulated device automatically checks for desired properties when it starts up.

Clean up resources

If you don't need the IoT hub any longer, delete it and the resource group in the portal. To do so, select the tutorials-iot-hub-rg resource group that contains your IoT hub and click Delete.

Next steps

In this tutorial, you've seen how to check your device keys, check device-to-cloud connectivity, check cloud-to-device connectivity, and check device twin synchronization. To learn more about how to monitor your IoT hub, visit the how-to article for IoT Hub monitoring.