Quickstart: Connect a sample IoT Plug and Play device application running on Linux or Windows to IoT Hub

This quickstart shows you how to build a sample IoT Plug and Play device application, connect it to your IoT hub, and use the Azure IoT explorer tool to view the telemetry it sends. The sample application is written in C and is included in the Azure IoT device SDK for C. A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

Prerequisites

Make sure you've setup your environment, including your IoT hub, before continuing.

You can run this quickstart on Linux or Windows. The shell commands in this quickstart follow the Linux convention for path separators '/', if you're following along on Windows be sure to swap these separators for '\'.

The prerequisites differ by operating system:

Linux

This quickstart assumes you're using Ubuntu Linux. The steps in this quickstart were tested using Ubuntu 18.04.

To complete this quickstart on Linux, install the following software on your local Linux environment:

Install GCC, Git, cmake, and all the required dependencies using the apt-get command:

sudo apt-get update
sudo apt-get install -y git cmake build-essential curl libcurl4-openssl-dev libssl-dev uuid-dev

Verify the version of cmake is above 2.8.12 and the version of GCC is above 4.4.7.

cmake --version
gcc --version

Windows

To complete this quickstart on Windows, install the following software on your local Windows environment:

Download the code

In this quickstart, you prepare a development environment you can use to clone and build the Azure IoT Hub Device C SDK.

Open a command prompt in the directory of your choice. Execute the following command to clone the Azure IoT C SDKs and Libraries GitHub repository into this location:

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

Expect this operation to take several minutes to complete.

Build the code

You use the device SDK to build the included sample code:

  1. Create a cmake subdirectory in the root folder of the device SDK, and navigate to that folder:

    cd azure-iot-sdk-c
    mkdir cmake
    cd cmake
    
  2. Run the following commands to build the SDK and samples:

    cmake -Duse_prov_client=ON -Dhsm_type_symm_key=ON -Drun_e2e_tests=OFF ..
    cmake --build .
    

Tip

On Windows, you can open the solution generated by the cmake command in Visual Studio 2019. Open the azure_iot_sdks.sln project file in the cmake directory and set the pnp_simple_thermostat project as the startup project in the solution. You can now build the sample in Visual Studio and run it in debug mode.

Run the device sample

In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • IOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

To learn more about the sample configuration, see the sample readme.

To run the sample application in the SDK that simulates an IoT Plug and Play device sending telemetry to your IoT hub:

From the cmake folder, navigate to the folder that contains the executable file and run it:

# Bash
cd iothub_client/samples/pnp/pnp_simple_thermostat/
./pnp_simple_thermostat
REM Windows
cd iothub_client\samples\pnp\pnp_simple_thermostat\Debug
.\pnp_simple_thermostat.exe

Tip

To trace the code execution in Visual Studio on Windows, add a break point to the main function in the pnp_simple_thermostat.c file.

The device is now ready to receive commands and property updates, and has started sending telemetry data to the hub. Keep the sample running as you complete the next steps.

Use Azure IoT explorer to validate the code

After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  1. Open Azure IoT explorer.

  2. On the IoT hubs page, if you haven't already added a connection to your IoT hub, select + Add connection. Enter the connection string for the IoT hub you created previously and select Save.

  3. On the IoT Plug and Play Settings page, select + Add > Local folder and select the local models folder where you saved your model files.

  4. On the IoT hubs page, click on the name of the hub you want to work with. You see a list of devices registered to the IoT hub.

  5. Click on the Device ID of the device you created previously.

  6. The menu on the left shows the different types of information available for the device.

  7. Select IoT Plug and Play components to view the model information for your device.

  8. You can view the different components of the device. The default component and any additional ones. Select a component to work with.

  9. Select the Telemetry page and then select Start to view the telemetry data the device is sending for this component.

  10. Select the Properties (read-only) page to view the read-only properties reported for this component.

  11. Select the Properties (writable) page to view the writable properties you can update for this component.

  12. Select a property by it's name, enter a new value for it, and select Update desired value.

  13. To see the new value show up select the Refresh button.

  14. Select the Commands page to view all the commands for this component.

  15. Select the command you want to test set the parameter if any. Select Send command to call the command on the device. You can see your device respond to the command in the command prompt window where the sample code is running.

Review the code

This sample implements a simple IoT Plug and Play thermostat device. The model this sample implements doesn't use IoT Plug and Play components. The DTDL model file for the thermostat device defines the telemetry, properties, and commands the device implements.

The device code uses the standard function to connect to your IoT hub:

deviceHandle = IoTHubDeviceClient_CreateFromConnectionString(connectionString, MQTT_Protocol)

The device sends the model ID of the DTDL model it implements in the connection request. A device that sends a model ID is an IoT Plug and Play device:

static const char g_ModelId[] = "dtmi:com:example:Thermostat;1";

...

IoTHubDeviceClient_SetOption(deviceHandle, OPTION_MODEL_ID, modelId)

The code that updates properties, handles commands, and sends telemetry is identical to the code for a device that doesn't use the IoT Plug and Play conventions.

The code uses the Parson library to parse JSON objects in the payloads sent from your IoT hub:

// JSON parser
#include "parson.h"

This quickstart shows you how to build a sample IoT Plug and Play device application, connect it to your IoT hub, and use the Azure IoT explorer tool to view the telemetry it sends. The sample application is written in C# and is included in the Azure IoT Samples for C#. A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

Prerequisites

Make sure you've setup your environment, including your IoT hub, before continuing.

To complete this quickstart on Windows, you need the following software installed on your development machine:

Download the code

In this quickstart, you prepare a development environment you can use to clone and build the Azure IoT Samples for C# repository.

Open a command prompt in a folder of your choice. Run the following command to clone the Microsoft Azure IoT Samples for C# (.NET) GitHub repository into this location:

git clone  https://github.com/Azure-Samples/azure-iot-samples-csharp.git

Build the code

You can now build the sample in Visual Studio and run it in debug mode.

  1. Open the azure-iot-samples-csharp\iot-hub\Samples\device\PnpDeviceSamples\Thermostat\Thermostat.csproj project file in Visual Studio 2019.

  2. In Visual Studio, navigate to Project > Thermostat Properties > Debug. Then add the following environment variables to the project:

    Name Value
    IOTHUB_DEVICE_SECURITY_TYPE DPS
    IOTHUB_DEVICE_DPS_ENDPOINT global.azure-devices-provisioning.net
    IOTHUB_DEVICE_DPS_ID_SCOPE The value you made a note of when you completed Set up your environment
    IOTHUB_DEVICE_DPS_DEVICE_ID my-pnp-device
    IOTHUB_DEVICE_DPS_DEVICE_KEY The value you made a note of when you completed Set up your environment

You can now build the sample in Visual Studio and run it in debug mode.

Run the device sample

To trace the code execution in Visual Studio on Windows, add a break point to the main function in the program.cs file.

The device is now ready to receive commands and property updates, and has started sending telemetry data to the hub. Keep the sample running as you complete the next steps.

Use Azure IoT explorer to validate the code

After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  1. Open Azure IoT explorer.

  2. On the IoT hubs page, if you haven't already added a connection to your IoT hub, select + Add connection. Enter the connection string for the IoT hub you created previously and select Save.

  3. On the IoT Plug and Play Settings page, select + Add > Local folder and select the local models folder where you saved your model files.

  4. On the IoT hubs page, click on the name of the hub you want to work with. You see a list of devices registered to the IoT hub.

  5. Click on the Device ID of the device you created previously.

  6. The menu on the left shows the different types of information available for the device.

  7. Select IoT Plug and Play components to view the model information for your device.

  8. You can view the different components of the device. The default component and any additional ones. Select a component to work with.

  9. Select the Telemetry page and then select Start to view the telemetry data the device is sending for this component.

  10. Select the Properties (read-only) page to view the read-only properties reported for this component.

  11. Select the Properties (writable) page to view the writable properties you can update for this component.

  12. Select a property by it's name, enter a new value for it, and select Update desired value.

  13. To see the new value show up select the Refresh button.

  14. Select the Commands page to view all the commands for this component.

  15. Select the command you want to test set the parameter if any. Select Send command to call the command on the device. You can see your device respond to the command in the command prompt window where the sample code is running.

Review the code

This sample implements a simple IoT Plug and Play thermostat device. The model this sample implements doesn't use IoT Plug and Play components. The Digital Twins definition language (DTDL) model file for the thermostat device defines the telemetry, properties, and commands the device implements.

The device code connects to your IoT hub using the standard CreateFromConnectionString method. The device sends the model ID of the DTDL model it implements in the connection request. A device that sends a model ID is an IoT Plug and Play device:

private static void InitializeDeviceClientAsync()
{
  var options = new ClientOptions
  {
    ModelId = ModelId,
  };
  s_deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, TransportType.Mqtt, options);
  s_deviceClient.SetConnectionStatusChangesHandler((status, reason) =>
  {
     s_logger.LogDebug($"Connection status change registered - status={status}, reason={reason}.");
  });
}

The model ID is stored in the code as shown in the following snippet:

private const string ModelId = "dtmi:com:example:Thermostat;1";

The code that updates properties, handles commands, and sends telemetry is identical to the code for a device that doesn't use the IoT Plug and Play conventions.

The sample uses a JSON library to parse JSON objects in the payloads sent from your IoT hub:

using Newtonsoft.Json;

...

DateTime since = JsonConvert.DeserializeObject<DateTime>(request.DataAsJson);

This quickstart shows you how to build a sample IoT Plug and Play device application, connect it to your IoT hub, and use the Azure IoT explorer tool to view the telemetry it sends. The sample application is written in Java and is included in the Azure IoT device SDK for Java. A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

Prerequisites

Make sure you've setup your environment, including your IoT hub, before continuing.

To complete this quickstart on Windows, install the following software on your local Windows environment:

Download the code

In this quickstart, you prepare a development environment you can use to clone and build the Azure IoT Hub Device Java SDK.

Open a command prompt in the directory of your choice. Execute the following command to clone the Azure IoT Java SDKs and Libraries GitHub repository into this location:

git clone https://github.com/Azure/azure-iot-sdk-java.git

Build the code

On Windows, navigate to the root folder of the cloned Java SDK repository.

Run the following command to build the sample application:

mvn install -T 2C -DskipTests

Run the device sample

In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • IOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

To learn more about the sample configuration, see the sample readme.

Navigate to the \device\iot-device-samples\pnp-device-sample\thermostat-device-sample folder.

To run the sample application, run the following command:

mvn exec:java -Dexec.mainClass="samples.com.microsoft.azure.sdk.iot.device.Thermostat"

The device is now ready to receive commands and property updates, and has started sending telemetry data to the hub. Keep the sample running as you complete the next steps.

Use Azure IoT explorer to validate the code

After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  1. Open Azure IoT explorer.

  2. On the IoT hubs page, if you haven't already added a connection to your IoT hub, select + Add connection. Enter the connection string for the IoT hub you created previously and select Save.

  3. On the IoT Plug and Play Settings page, select + Add > Local folder and select the local models folder where you saved your model files.

  4. On the IoT hubs page, click on the name of the hub you want to work with. You see a list of devices registered to the IoT hub.

  5. Click on the Device ID of the device you created previously.

  6. The menu on the left shows the different types of information available for the device.

  7. Select IoT Plug and Play components to view the model information for your device.

  8. You can view the different components of the device. The default component and any additional ones. Select a component to work with.

  9. Select the Telemetry page and then select Start to view the telemetry data the device is sending for this component.

  10. Select the Properties (read-only) page to view the read-only properties reported for this component.

  11. Select the Properties (writable) page to view the writable properties you can update for this component.

  12. Select a property by it's name, enter a new value for it, and select Update desired value.

  13. To see the new value show up select the Refresh button.

  14. Select the Commands page to view all the commands for this component.

  15. Select the command you want to test set the parameter if any. Select Send command to call the command on the device. You can see your device respond to the command in the command prompt window where the sample code is running.

Review the code

This sample implements a simple IoT Plug and Play thermostat device. The model this sample implements doesn't use IoT Plug and Play components. The DTDL model file for the thermostat device defines the telemetry, properties, and commands the device implements.

The device code uses the standard DeviceClient class to connect to your IoT hub. The device sends the model ID of the DTDL model it implements in the connection request. A device that sends a model ID is an IoT Plug and Play device:

private static void initializeDeviceClient() throws URISyntaxException, IOException {
    ClientOptions options = new ClientOptions();
    options.setModelId(MODEL_ID);
    deviceClient = new DeviceClient(deviceConnectionString, protocol, options);

    deviceClient.registerConnectionStatusChangeCallback((status, statusChangeReason, throwable, callbackContext) -> {
        log.debug("Connection status change registered: status={}, reason={}", status, statusChangeReason);

        if (throwable != null) {
            log.debug("The connection status change was caused by the following Throwable: {}", throwable.getMessage());
            throwable.printStackTrace();
        }
    }, deviceClient);

    deviceClient.open();
}

The model ID is stored in the code as shown in the following snippet:

private static final String MODEL_ID = "dtmi:com:example:Thermostat;1";

The code that updates properties, handles commands, and sends telemetry is identical to the code for a device that doesn't use the IoT Plug and Play conventions.

The sample uses a JSON library to parse JSON objects in the payloads sent from your IoT hub:

import com.google.gson.Gson;

...

Date since = new Gson().fromJson(jsonRequest, Date.class);

This quickstart shows you how to build a sample IoT Plug and Play device application, connect it to your IoT hub, and use the Azure IoT explorer tool to view the telemetry it sends. The sample application is written in Node.js and is included in the Azure IoT device SDK for Node.js. A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

Prerequisites

Make sure you've setup your environment, including your IoT hub, before continuing.

To complete this quickstart, you need Node.js on your development machine. You can download the latest recommended version 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 code

In this quickstart, you prepare a development environment you can use to clone and build the Azure IoT Hub Device SDK for Node.js.

Open a command prompt in the directory of your choice. Execute the following command to clone the Microsoft Azure IoT SDK for Node.js GitHub repository into this location:

git clone https://github.com/Azure/azure-iot-sdk-node

Install required libraries

You use the device SDK to build the included sample code. The application you build simulates a device that connects to an IoT hub. The application sends telemetry and properties and receives commands.

  1. In a local terminal window, go to the folder of your cloned repository and navigate to the /azure-iot-sdk-node/device/samples/pnp folder. Then run the following command to install the required libraries:

    npm install
    
  2. Configure the environment variable with the device connection string you made a note of previously:

    set IOTHUB_DEVICE_CONNECTION_STRING=<YourDeviceConnectionString>
    

Run the sample device

This sample implements a simple IoT Plug and Play thermostat device. The model this sample implements doesn't use IoT Plug and Play components. The DTDL model file for the thermostat device defines the telemetry, properties, and commands the device implements.

Open the simple_thermostat.js file. In this file, you can see how to:

  1. Import the required interfaces.
  2. Write a property update handler and a command handler.
  3. Handle desired property patches and send telemetry.
  4. Optionally, provision your device using the Azure Device Provisioning Service (DPS).

In the main function, you can see how it all comes together:

  1. Create the device from your connection string or provision it using DPS.)
  2. Use the modelID option to specify the IoT Plug and Play device model.
  3. Enable the command handler.
  4. Send telemetry from the device to your hub.
  5. Get the devices twin and update the reported properties.
  6. Enable the desired property update handler.

In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • IOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

To learn more about the sample configuration, see the sample readme.

Run the sample application to simulate an IoT Plug and Play device that sends telemetry to your IoT hub. To run the sample application, use the following command:

node simple_thermostat.js

You see the following output, indicating the device has begun sending telemetry data to the hub, and is now ready to receive commands and property updates.

Device confirmation messages

Keep the sample running as you complete the next steps.

Use Azure IoT explorer to validate the code

After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  1. Open Azure IoT explorer.

  2. On the IoT hubs page, if you haven't already added a connection to your IoT hub, select + Add connection. Enter the connection string for the IoT hub you created previously and select Save.

  3. On the IoT Plug and Play Settings page, select + Add > Local folder and select the local models folder where you saved your model files.

  4. On the IoT hubs page, click on the name of the hub you want to work with. You see a list of devices registered to the IoT hub.

  5. Click on the Device ID of the device you created previously.

  6. The menu on the left shows the different types of information available for the device.

  7. Select IoT Plug and Play components to view the model information for your device.

  8. You can view the different components of the device. The default component and any additional ones. Select a component to work with.

  9. Select the Telemetry page and then select Start to view the telemetry data the device is sending for this component.

  10. Select the Properties (read-only) page to view the read-only properties reported for this component.

  11. Select the Properties (writable) page to view the writable properties you can update for this component.

  12. Select a property by it's name, enter a new value for it, and select Update desired value.

  13. To see the new value show up select the Refresh button.

  14. Select the Commands page to view all the commands for this component.

  15. Select the command you want to test set the parameter if any. Select Send command to call the command on the device. You can see your device respond to the command in the command prompt window where the sample code is running.

This quickstart shows you how to build a sample IoT Plug and Play device application, connect it to your IoT hub, and use the Azure IoT explorer tool to view the telemetry it sends. The sample application is written for Python and is included in the Azure IoT Hub Device SDK for Python. A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

Prerequisites

Make sure you've setup your environment, including your IoT hub, before continuing.

To complete this quickstart, you need Python 3.7 on your development machine. You can download the latest recommended version for multiple platforms from python.org. You can check your Python version with the following command:

python --version

In your local python environment install the package as follows:

pip install azure-iot-device

Clone the Python SDK IoT repository and check out master:

git clone https://github.com/Azure/azure-iot-sdk-python

Run the sample device

The azure-iot-sdk-python\azure-iot-device\samples\pnp folder contains the sample code for the IoT Plug and Play device. This quickstart uses the simple_thermostat.py file. This sample code implements an IoT Plug and Play compatible device and uses the Azure IoT Python Device Client Library.

Open the simple_thermostat.py file in a text editor. Notice how it:

  1. Defines a single device twin model identifier (DTMI) that uniquely represents the Thermostat. A DTMI must be known to the user and varies dependent on the scenario of device implementation. For the current sample, the model represents a thermostat that has telemetry, properties, and commands associated with monitoring temperature.

  2. Has functions to define command handler implementations. You write these handlers to define how the device responds to command requests.

  3. Has a function to define a command response. You create command response functions to send a response back to your IoT hub.

  4. Defines an input keyboard listener function to let you quit the application.

  5. Has a main function. The main function:

    1. Uses the device SDK to create a device client and connect to your IoT hub.

    2. Updates properties. The model we are using, Thermostat, defines targetTemperature and maxTempSinceLastReboot as the two properties for our Thermostat, so that is what we will be using. Properties are updated using the patch_twin_reported_properties method defined on the device_client.

    3. Starts listening for command requests using the execute_command_listener function. The function sets up a 'listener' to listen for commands coming from the service. When you set up the listener you provide a method_name, user_command_handler, and create_user_response_handler.

      • The user_command_handler function defines what the device should do when it receives a command. For instance, if your alarm goes off, the effect of receiving this command is you wake up. Think of this as the 'effect' of the command being invoked.
      • The create_user_response_handler function creates a response to be sent to your IoT hub when a command executes successfully. For instance, if your alarm goes off, you respond by hitting snooze, which is feedback to the service. Think of this as the reply you give to the service. You can view this response in the portal.
    4. Starts sending telemetry. The pnp_send_telemetry is defined in the pnp_methods.py file. The sample code uses a loop to call this function every eight seconds.

    5. Disables all the listeners and tasks, and exist the loop when you press Q or q.

In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • IOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

To learn more about the sample configuration, see the sample readme.

Now that you've seen the code, use the following command to run the sample:

python simple_thermostat.py

You see the following output, which indicates the device is sending telemetry data to the hub, and is now ready to receive commands and property updates:

Listening for command requests and property updates
Press Q to quit
Sending telemetry for temperature
Sent message

Keep the sample running as you complete the next steps.

Use Azure IoT explorer to validate the code

After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  1. Open Azure IoT explorer.

  2. On the IoT hubs page, if you haven't already added a connection to your IoT hub, select + Add connection. Enter the connection string for the IoT hub you created previously and select Save.

  3. On the IoT Plug and Play Settings page, select + Add > Local folder and select the local models folder where you saved your model files.

  4. On the IoT hubs page, click on the name of the hub you want to work with. You see a list of devices registered to the IoT hub.

  5. Click on the Device ID of the device you created previously.

  6. The menu on the left shows the different types of information available for the device.

  7. Select IoT Plug and Play components to view the model information for your device.

  8. You can view the different components of the device. The default component and any additional ones. Select a component to work with.

  9. Select the Telemetry page and then select Start to view the telemetry data the device is sending for this component.

  10. Select the Properties (read-only) page to view the read-only properties reported for this component.

  11. Select the Properties (writable) page to view the writable properties you can update for this component.

  12. Select a property by it's name, enter a new value for it, and select Update desired value.

  13. To see the new value show up select the Refresh button.

  14. Select the Commands page to view all the commands for this component.

  15. Select the command you want to test set the parameter if any. Select Send command to call the command on the device. You can see your device respond to the command in the command prompt window where the sample code is running.

Next steps

In this quickstart, you've learned how to connect an IoT Plug and Play device to an IoT hub. To learn more about how to build a solution that interacts with your IoT Plug and Play devices, see: