Get started with device twins (Node)

Introduction

Device twins are JSON documents that store device state information (metadata, configurations, and conditions). IoT Hub persists a device twin for each device that connects to it.

Use device twins to:

  • Store device metadata from your solution back end.
  • Report current state information such as available capabilities and conditions (for example, the connectivity method used) from your device app.
  • Synchronize the state of long-running workflows (such as firmware and configuration updates) between a device app and a back-end app.
  • Query your device metadata, configuration, or state.
Note

Device twins are designed for synchronization and for querying device configurations and conditions. More informations on when to use device twins can be found in Understand device twins.

Device twins are stored in an IoT hub and contain:

  • tags, device metadata accessible only by the solution back end;
  • desired properties, JSON objects modifiable by the solution back end and observable by the device app; and
  • reported properties, JSON objects modifiable by the device app and readable by the solution back end. Tags and properties cannot contain arrays, but objects can be nested.

Additionally, the solution back end can query device twins based on all the above data. Refer to Understand device twins for more information about device twins, and to the IoT Hub query language reference for querying.

Note

At this time, device twins are accessible only from devices that connect to IoT Hub using the MQTT protocol. Please refer to the MQTT support article for instructions on how to convert existing device app to use MQTT.

This tutorial shows you how to:

  • Create a back-end app that adds tags to a device twin, and a simulated device app that reports its connectivity channel as a reported property on the device twin.
  • Query devices from your back-end app using filters on the tags and properties previously created.

At the end of this tutorial, you will have two Node.js console apps:

  • AddTagsAndQuery.js, a Node.js back-end app, which adds tags and queries device twins.
  • TwinSimulatedDevice.js, a Node.js app which simulates a device that connects to your IoT hub with the device identity created earlier, and reports its connectivity condition.
Note

The article Azure IoT SDKs provides information about the Azure IoT SDKs that you can use to build both device and back-end apps.

To complete this tutorial you need the following:

  • Node.js version 0.10.x or later.
  • An active Azure account. (If you don't have an account, you can create a free account in just a couple of minutes.)

Create an IoT hub

Create an IoT hub for your simulated device app to connect to. The following steps show you how to complete this task by using the Azure portal.

  1. Sign in to the Azure portal.
  2. In the Jumpbar, click New > Internet of Things > IoT Hub.

    Azure portal Jumpbar

  3. In the IoT hub blade, choose the configuration for your IoT hub.

    IoT hub blade

    1. In the Name box, enter a name for your IoT hub. If the Name is valid and available, a green check mark appears in the Name box.
    2. Select a pricing and scale tier. This tutorial does not require a specific tier. For this tutorial, use the free F1 tier.
    3. In Resource group, either create a resource group, or select an existing one. For more information, see Using resource groups to manage your Azure resources.
    4. In Location, select the location to host your IoT hub. For this tutorial, choose your nearest location.
  4. When you have chosen your IoT hub configuration options, click Create. It can take a few minutes for Azure to create your IoT hub. To check the status, you can monitor the progress on the Startboard or in the Notifications panel.

    New IoT hub status

  5. When the IoT hub has been created successfully, click the new tile for your IoT hub in the Azure portal to open the blade for the new IoT hub. Make a note of the Hostname, and then click Shared access policies.

    New IoT hub blade

  6. In the Shared access policies blade, click the iothubowner policy, and then copy and make note of the IoT Hub connection string in the iothubowner blade. For more information, see Access control in the "IoT Hub developer guide."

    Shared access policies blade

Create a device identity

In this section, you use a Node.js tool called iothub-explorer to create a device identity for this tutorial. Device IDs are case sensitive.

  1. Run the following in your command-line environment:

    npm install -g iothub-explorer@latest

  2. Then, run the following command to login to your hub. Substitute {iot hub connection string} with the IoT Hub connection string you previously copied:

    iothub-explorer login "{iot hub connection string}"

  3. Finally, create a new device identity called myDeviceId with the command:

    iothub-explorer create myDeviceId --connection-string

Make a note of the device connection string from the result. This device connection string is used by the device app to connect to your IoT Hub as a device.

Refer to Getting started with IoT Hub to programmatically create device identities.

Create the service app

In this section, you create a Node.js console app that adds location metadata to the device twin associated with myDeviceId. It then queries the device twins stored in the IoT hub selecting the devices located in the US, and then the ones that reporting a cellular connection.

  1. Create a new empty folder called addtagsandqueryapp. In the addtagsandqueryapp folder, create a new package.json file using the following command at your command prompt. Accept all the defaults:

    npm init
    
  2. At your command prompt in the addtagsandqueryapp folder, run the following command to install the azure-iothub package:

    npm install azure-iothub --save
    
  3. Using a text editor, create a new AddTagsAndQuery.js file in the addtagsandqueryapp folder.
  4. Add the following code to the AddTagsAndQuery.js file, and substitute the {iot hub connection string} placeholder with the IoT Hub connection string you copied when you created your hub:

     'use strict';
     var iothub = require('azure-iothub');
     var connectionString = '{iot hub connection string}';
     var registry = iothub.Registry.fromConnectionString(connectionString);
    
     registry.getTwin('myDeviceId', function(err, twin){
         if (err) {
             console.error(err.constructor.name + ': ' + err.message);
         } else {
             var patch = {
                 tags: {
                     location: {
                         region: 'US',
                         plant: 'Redmond43'
                   }
                 }
             };
    
             twin.update(patch, function(err) {
               if (err) {
                 console.error('Could not update twin: ' + err.constructor.name + ': ' + err.message);
               } else {
                 console.log(twin.deviceId + ' twin updated successfully');
                 queryTwins();
               }
             });
         }
     });
    

    The Registry object exposes all the methods required to interact with device twins from the service. The previous code first initializes the Registry object, then retrieves the device twin for myDeviceId, and finally updates its tags with the desired location information.

    After the updating the tags it calls the queryTwins function.

  5. Add the following code at the end of AddTagsAndQuery.js to implement the queryTwins function:

     var queryTwins = function() {
         var query = registry.createQuery("SELECT * FROM devices WHERE tags.location.plant = 'Redmond43'", 100);
         query.nextAsTwin(function(err, results) {
             if (err) {
                 console.error('Failed to fetch the results: ' + err.message);
             } else {
                 console.log("Devices in Redmond43: " + results.map(function(twin) {return twin.deviceId}).join(','));
             }
         });
    
         query = registry.createQuery("SELECT * FROM devices WHERE tags.location.plant = 'Redmond43' AND properties.reported.connectivity.type = 'cellular'", 100);
         query.nextAsTwin(function(err, results) {
             if (err) {
                 console.error('Failed to fetch the results: ' + err.message);
             } else {
                 console.log("Devices in Redmond43 using cellular network: " + results.map(function(twin) {return twin.deviceId}).join(','));
             }
         });
     };
    

    The previous code executes two queries: the first selects only the device twins of devices located in the Redmond43 plant, and the second refines the query to select only the devices that are also connected through cellular network.

    Note that the previous code, when it creates the query object, specifies a maximum number of returned documents. The query object contains a hasMoreResults boolean property that you can use to invoke the nextAsTwin methods multiple times to retrieve all results. A method called next is available for results that are not device twins for example, results of aggregation queries.

  6. Run the application with:

     node AddTagsAndQuery.js
    

    You should see one device in the results for the query asking for all devices located in Redmond43 and none for the query that restricts the results to devices that use a cellular network.

In the next section you create a device app that reports the connectivity information and changes the result of the query in the previous section.

Create the device app

In this section, you create a Node.js console app that connects to your hub as myDeviceId, and then updates its device twin's reported properties to contain the information that it is connected using a cellular network.

Note

At this time, device twins are accessible only from devices that connect to IoT Hub using the MQTT protocol. Please refer to the MQTT support article for instructions on how to convert existing device app to use MQTT.

  1. Create a new empty folder called reportconnectivity. In the reportconnectivity folder, create a new package.json file using the following command at your command prompt. Accept all the defaults:

    npm init
    
  2. At your command prompt in the reportconnectivity folder, run the following command to install the azure-iot-device, and azure-iot-device-mqtt package:

    npm install azure-iot-device azure-iot-device-mqtt --save
    
  3. Using a text editor, create a new ReportConnectivity.js file in the reportconnectivity folder.
  4. Add the following code to the ReportConnectivity.js file, and substitute the {device connection string} placeholder with the device connection string you copied when you created the myDeviceId device identity:

     'use strict';
     var Client = require('azure-iot-device').Client;
     var Protocol = require('azure-iot-device-mqtt').Mqtt;
    
     var connectionString = '{device connection string}';
     var client = Client.fromConnectionString(connectionString, Protocol);
    
     client.open(function(err) {
     if (err) {
         console.error('could not open IotHub client');
     }  else {
         console.log('client opened');
    
         client.getTwin(function(err, twin) {
         if (err) {
             console.error('could not get twin');
         } else {
             var patch = {
                 connectivity: {
                     type: 'cellular'
                 }
             };
    
             twin.properties.reported.update(patch, function(err) {
                 if (err) {
                     console.error('could not update twin');
                 } else {
                     console.log('twin state reported');
                     process.exit();
                 }
             });
         }
         });
     }
     });
    

    The Client object exposes all the methods you require to interact with device twins from the device. The previous code, after it initializes the Client object, retrieves the device twin for myDeviceId and updates its reported property with the connectivity information.

  5. Run the device app

     node ReportConnectivity.js
    

    You should see the message twin state reported.

  6. Now that the device reported its connectivity information, it should appear in both queries. Go back in the addtagsandqueryapp folder and run the queries again:

     node AddTagsAndQuery.js
    

    This time myDeviceId should appear in both query results.

Next steps

In this tutorial, you configured a new IoT hub in the Azure portal, and then created a device identity in the IoT hub's identity registry. You added device metadata as tags from a back-end app, and wrote a simulated device app to report device connectivity information in the device twin. You also learned how to query this information using the SQL-like IoT Hub query language.

Use the following resources to learn how to: