Quickstart: Interact with an IoT Plug and Play Preview device that's connected to your solution (Node.js)

IoT Plug and Play Preview simplifies IoT by enabling you to interact with a device's capabilities without knowledge of the underlying device implementation. This quickstart shows you how to use Node.js to connect to and control an IoT Plug and Play device that's connected to your solution.

Prerequisites

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

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.

Prepare an IoT hub

You also need an Azure IoT hub in your Azure subscription to complete this quickstart. If you don't have an Azure subscription, create a free account before you begin. If you don't have an IoT hub, follow these instructions to create one.

Important

During public preview, IoT Plug and Play features are only available on IoT hubs created in the Central US, North Europe, and Japan East regions.

If you're using the Azure CLI locally, first sign in to your Azure subscription using az login. If you're running these commands in the Azure Cloud Shell, you're signed in automatically.

If you're using the Azure CLI locally, the az version should be 2.0.73 or later; the Azure Cloud Shell uses the latest version. Use the az --version command to check the version installed on your machine.

Run the following command to add the Microsoft Azure IoT Extension for Azure CLI to your instance:

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

Run the following command to create the device identity in your IoT hub. Replace the YourIoTHubName and YourDeviceID placeholders with your own IoT Hub name and a device ID of your choice.

az iot hub device-identity create --hub-name <YourIoTHubName> --device-id <YourDeviceID>

Run the following command to get the device connection string for the device you just registered (note for use later):

az iot hub device-identity show-connection-string --hub-name <YourIoTHubName> --device-id <YourDeviceID> --output table

Run the following command to get the IoT hub connection string for your hub (note for use later):

az iot hub show-connection-string --hub-name <YourIoTHubName> --output table

Run the sample device

In this quickstart, you use a sample environmental sensor that's written in Node.js as the IoT Plug and Play device. The following instructions show you how to install and run the device:

  1. Open a terminal window in the directory of your choice. Execute the following command to clone the Azure IoT Samples for Node.js GitHub repository into this location:

    git clone https://github.com/azure-samples/azure-iot-samples-node
    
  2. This terminal window will now be used as your device terminal. Go to the folder of your cloned repository, and navigate to the /azure-iot-samples-node/digital-twins/Quickstarts/Device folder. Install all the dependencies by running the following command:

    npm install
    
  3. Configure the device connection string:

    set DEVICE_CONNECTION_STRING=<YourDeviceConnectionString>
    
  4. Run the sample with the following command:

    node sample_device.js
    
  5. You see messages saying that the device has sent some information and reported itself online. This indicates that the device has begun sending telemetry data to the hub, and is now ready to receive commands and property updates. Don't close this terminal, you'll need it later to confirm the service samples also worked.

Run the sample solution

In this quickstart, you use a sample IoT solution in Node.js to interact with the sample device.

  1. Open another terminal window (this will be your service terminal). Go to the folder of your cloned repository, and navigate to the /azure-iot-samples-node/digital-twins/Quickstarts/Service folder. Install all the dependencies by running the following command:

    npm install
    
  2. Configure the IoT hub connection string to allow the service to connect to it:

    set IOTHUB_CONNECTION_STRING=<YourIoTHubConnectionString>
    

Read a property

  1. When you connected the device in its terminal, you saw the following message indicating its online status:

    reported state property as online
    
  2. In the /azure-iot-samples-node/digital-twins/Quickstarts/Service folder, open the file get_digital_twin.js. Replace the <DEVICE_ID_GOES_HERE> placeholder with your device ID and save the file.

  3. Go to the service terminal and use the following command to run the sample for reading device information:

    node get_digital_twin.js
    
  4. In the service terminal output, scroll to the environmentalSensor component. You see that the state property has been reported as online:

    "environmentalSensor": {
      "name": "environmentalSensor",
      "properties": {
        "state": {
          "reported": {
            "value": "online"
          }
        }
      }
    }
    

Update a writable property

  1. Open the file update_digital_twin_property.js.

  2. At the beginning of the file, there's a set of constants defined with uppercase placeholders. Replace the <DEVICE_ID_GOES_HERE> placeholder with your actual device ID, update the remaining constants with the following values, and save the file:

    const interfaceInstanceName = 'environmentalSensor';
    const propertyName = 'brightness';
    const propertyValue = 42;
    
  3. Go to the service terminal and use the following command to run the sample for updating the property:

    node update_digital_twin_property.js
    
  4. The service terminal output shows the updated device information. Scroll to the environmentalSensor component to see the new brightness value of 42.

    "environmentalSensor": {
      "name": "environmentalSensor",
      "properties": {
        "brightness": {
          "desired": {
            "value": "42"
          }
        },
        "state": {
          "reported": {
            "value": "online"
          }
        }
      }
    }
    
  5. Go to your device terminal, you see the device has received the update:

    Received an update for brightness: 42
    updated the property
    
  6. Go back to your service terminal and run the below command to get the device information again, to confirm the property has been updated.

    node get_digital_twin.js
    
  7. In the service terminal output, under the environmentalSensor component, you see the updated brightness value has been reported. Note: it might take a while for the device to finish the update. You can repeat this step until the device has actually processed the property update.

    "environmentalSensor": {
      "name": "environmentalSensor",
      "properties": {
        "brightness": {
          "reported": {
            "value": "42",
            "desiredState": {
              "code": 200,
              "version": 2,
              "description": "helpful descriptive text"
            }
          },
          "desired": {
            "value": "42"
          }
        },
        "state": {
          "reported": {
            "value": "online"
          }
        }
      }
    }
    

Invoke a command

  1. Open the file invoke_command.js.

  2. At the beginning of the file, replace the <DEVICE_ID_GOES_HERE> placeholder with your actual device ID. Update the remaining constants with the following values, and then save the file:

    const interfaceInstanceName = 'environmentalSensor';
    const commandName = 'blink';
    const commandArgument = '<For the environmental sensor, this value does not matter. Any string will do.>'; 
    
  3. Go to the service terminal. Use the following command to run the sample for invoking the command:

    node invoke_command.js
    
  4. Output in the service terminal should show the following confirmation:

    invoking command blink on interface instanceenvironmentalSensor for device <device ID>...
    {
      "result": "helpful response text",
      "statusCode": 200,
      "requestId": "<some ID value>",
      "_response": "helpful response text"
    }
    
  5. Go to the device terminal, you see the command has been acknowledged:

    received command: blink for interfaceInstance: environmentalSensor
    acknowledgement succeeded.
    

Clean up resources

If you plan to continue with additional IoT Plug and Play articles, you can keep and reuse the resources you used in this quickstart. Otherwise, you can delete the resources you created in this quickstart to avoid additional charges.

You can delete both the hub and registered device at once by deleting the entire resource group with the following command for Azure CLI. (Don't use this, however, if these resources are sharing a resource group with other resources you have for different purposes.)

az group delete --name <YourResourceGroupName>

To delete just the IoT hub, run the following command using Azure CLI:

az iot hub delete --name <YourIoTHubName>

To delete just the device identity you registered with your IoT hub, run the following command using Azure CLI:

az iot hub device-identity delete --hub-name <YourIoTHubName> --device-id <YourDeviceID>

You may also want to remove the cloned sample files from your development machine.

Next steps

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