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
Prerequisites
Use the Bash environment in Azure Cloud Shell. For more information, see Azure Cloud Shell Quickstart - Bash.
If you prefer to run CLI reference commands locally, install the Azure CLI. If you're running on Windows or macOS, consider running Azure CLI in a Docker container. For more information, see How to run the Azure CLI in a Docker container.
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 other sign-in options, see Sign in with the Azure CLI.
When you're prompted, install the Azure CLI extension 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.
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.
Make sure that port 8883 is open in your firewall. The device sample in this tutorial uses MQTT protocol, which communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).
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:
Sign in to the Azure portal.
From the Azure homepage, select Create a resource, and then enter IoT Hub in Search the Marketplace.
Select IoT Hub from the search results, and then select Create.
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. This tutorial uses the name tutorials-iot-hub-rg.
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. This tutorial uses the West US region.
IoT Hub Name: Enter a name for your hub. This name must be globally unique. This tutorial uses tutorials-iot-hub. You must choose your own unique name when you create your hub.
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.
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 tutorial.
Select Next: Management to continue creating your hub.
You can accept the default settings here. If desired, you can modify any of the following fields:
Pricing and scale tier: Your selected tier. Choose the free tier. 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. Each Azure subscription can create one IoT hub in the free tier. 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 Microsoft Defender 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. A free tier hub is limited to two partitions.
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.
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.
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:
To register a new device, click + New, set Device ID to MyTestDevice, and click Save.
To retrieve the connection string for MyTestDevice, click on it in the list of devices and then copy the Primary Connection String value. The connection string includes the shared access key for the device.
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:

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-iot
# 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:

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:

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:

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 connection-string show --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:

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

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

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.

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:

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.
Povratne informacije
Pošalјite i prikažite povratne informacije za
