Tutorial: Add a real device to your Azure IoT Central application

Note

You're currently viewing the IoT Central documentation for application templates that use generally available features. To view the documentation for application templates that use preview features, go to What is Azure IoT Central (preview features)?.

This tutorial shows you how to add and configure a real device to your Microsoft Azure IoT Central application. In this tutorial, you code the real device using Node.js and run the code on a desktop machine. You don't need a separate IoT device such as a Raspberry Pi or MXChip IoT DevKit device to complete this tutorial.

This tutorial is made up of two parts:

  • First, as an operator, you learn how to add and configure a real device in your Azure IoT Central application. At the end of this part, you retrieve a connection string to use in the second part.
  • Then, as a device developer, you learn about the code in your real device. You add the connection string from the first part to the sample code.

In this tutorial, you learn how to:

  • Add a new real device
  • Configure the real device
  • Get connection string for real device from the application
  • Understand how client code maps to the application
  • Configure client code for the real device

Prerequisites

Before you begin, the builder should complete at least the first builder tutorial to create the Azure IoT Central application: Define a new device type (Required)

Install Node.js version 8.0.0 or later on your development machine. You can run node --version in the command line to check your version. Node.js is available for a wide variety of operating systems.

Add a real device

To add a real device to your application, you use the Connected Air Conditioner device template you created in the Define a new device type tutorial.

  1. To add a new device as an operator choose Devices in the left pane:

    Device explorer page showing connected air conditioner

    The Device Explorer shows the Connected Air Conditioner device template and a simulated device. When you create a device template, IoT Central automatically creates a simulated device.

  2. Notice that the Connected Air Conditioner device template is the one selected in the Device Explorer. To start connecting a real air conditioner device that uses this template, select +, then Real:

    Start adding a new, real connected air conditioner device

  3. Enter your own Device ID (should be lowercase) or use the suggested value. You can also enter a Device Name for your new device and choose Create.

    Rename the device

Configure a real device

The real device is created from the Connected Air Conditioner device template. You can use Settings to configure your device and set property values to record information about your device.

  1. On the Settings page, notice that the Set Temperature setting status is no update. It stays in this state until the real device connects to the application and acknowledges that it has acted on the setting.

    Settings show syncing

  2. On the Properties page for your new, real device, both location of service and last service date are editable properties. The serial number and firmware version fields are empty until the device is connected to the application. These read-only values are sent from the device and can't be edited.

    Device Properties for real device

  3. You can view the Measurements, Rules, and Dashboard pages for your real device.

Prepare the client code

The example code in this article is written in Node.js and shows enough code for a device to:

  • Connect to your Azure IoT Central application.
  • Send temperature telemetry as a connected air conditioner device.
  • Send device properties to your Azure IoT Central application.
  • Respond to an operator who uses the Set Temperature setting.
  • Handle the Echo command from your Azure IoT Central application.

The articles listed in the Next Steps section include more complete samples and show other programming languages. For more information about how devices connect to Azure IoT Central, see the Device connectivity article.

The following steps show how to prepare the Node.js sample:

Get the device connection information

  1. The connection string for a device instance in your application is generated from device information provided by the IoT Central.

    On the device screen for your real connected air conditioner, choose Connect.

    Device page showing view connection information link

  2. On the Device Connection page, make a note of the Scope ID, Device ID, and Primary Key values. You use these values later in this tutorial.

    Connection details

Prepare the Node.js project

  1. Create a folder called connectedairconditioner on your development machine.

  2. In your command-line environment, navigate to the connectedairconditioner folder you created.

  3. To initialize your Node.js project, run the following command accepting all the defaults:

    npm init
    
  4. To install the necessary packages, run the following command:

    npm install azure-iot-device azure-iot-device-mqtt azure-iot-provisioning-device-mqtt azure-iot-security-symmetric-key --save
    
  5. Using a text editor, create a file called ConnectedAirConditioner.js in the connectedairconditioner folder.

  6. Add the following require statements at the start of the ConnectedAirConditioner.js file:

    'use strict';
    
    var iotHubTransport = require('azure-iot-device-mqtt').Mqtt;
    var Client = require('azure-iot-device').Client;
    var Message = require('azure-iot-device').Message;
    var ProvisioningTransport = require('azure-iot-provisioning-device-mqtt').Mqtt;
    var SymmetricKeySecurityClient = require('azure-iot-security-symmetric-key').SymmetricKeySecurityClient;
    var ProvisioningDeviceClient = require('azure-iot-provisioning-device').ProvisioningDeviceClient;
    
  7. Add the following variable declarations to the file. Replace the placeholders {your Scope ID}, {your Device ID}, and {your Primary Key} with the device connection information you noted previously:

    var provisioningHost = 'global.azure-devices-provisioning.net';
    var idScope = '{your Scope ID}';
    var registrationId = '{your Device ID}';
    var symmetricKey = '{your Primary Key}';
    var provisioningSecurityClient = new SymmetricKeySecurityClient(registrationId, symmetricKey);
    var provisioningClient = ProvisioningDeviceClient.create(provisioningHost, idScope, new ProvisioningTransport(), provisioningSecurityClient);
    var hubClient;
    var targetTemperature = 0;
    
  8. Save the changes you have made so far, but keep the file open.

Review client code

In the previous section, you created a skeleton Node.js project for a device application that connects to your Azure IoT Central application. The next step is to add code to:

  • Connect to your Azure IoT Central application.
  • Send telemetry to your Azure IoT Central application.
  • Send device properties to your Azure IoT Central application.
  • Receive settings from your Azure IoT Central application.
  • Handle the Echo command from your Azure IoT Central application.
  1. To send temperature telemetry to your Azure IoT Central application, add the following code to the ConnectedAirConditioner.js file:

    // Send device measurements.
    function sendTelemetry() {
      var temperature = targetTemperature + (Math.random() * 15);
      var data = JSON.stringify({ temperature: temperature });
      var message = new Message(data);
      hubClient.sendEvent(message, (err, res) => console.log(`Sent message: ${message.getData()}` +
        (err ? `; error: ${err.toString()}` : '') +
        (res ? `; status: ${res.constructor.name}` : '')));
    }
    

    The name of the field in the JSON you send must match the name of the field you specified for temperature telemetry in your device template. In this example, the name of the field is temperature.

  2. To send the device properties such as firmwareVersion and serialNumber, add the following definition:

    // Send device properties
    function sendDeviceProperties(twin) {
      var properties = {
        firmwareVersion: "9.75",
        serialNumber: "10001"
      };
      twin.properties.reported.update(properties, (errorMessage) =>
      console.log(` * Sent device properties ` + (errorMessage ? `Error: ${errorMessage.toString()}` : `(success)`)));
    }
    
  3. To define the settings your device supports, such as setTemperature, add the following definition:

    // Add any settings your device supports
    // mapped to a function that is called when the setting is changed.
    var settings = {
      'setTemperature': (newValue, callback) => {
        // Simulate the temperature setting taking two steps.
        setTimeout(() => {
          targetTemperature = targetTemperature + (newValue - targetTemperature) / 2;
          callback(targetTemperature, 'pending');
          setTimeout(() => {
            targetTemperature = newValue;
            callback(targetTemperature, 'completed');
          }, 5000);
        }, 5000);
      }
    };
    
  4. To handle settings sent from Azure IoT Central, add the following function that locates and executes the appropriate device code:

    // Handle settings changes that come from Azure IoT Central via the device twin.
    function handleSettings(twin) {
      twin.on('properties.desired', function (desiredChange) {
        for (let setting in desiredChange) {
          if (settings[setting]) {
            console.log(`Received setting: ${setting}: ${desiredChange[setting].value}`);
            settings[setting](desiredChange[setting].value, (newValue, status, message) => {
              var patch = {
                [setting]: {
                  value: newValue,
                  status: status,
                  desiredVersion: desiredChange.$version,
                  message: message
                }
              }
              twin.properties.reported.update(patch, (err) => console.log(`Sent setting update for ${setting}; ` +
                (err ? `error: ${err.toString()}` : `status: success`)));
            });
          }
        }
      });
    }
    

    This function:

    • Watches for Azure IoT Central sending a desired property.
    • Locates the appropriate function to call to handle the setting change.
    • Sends an acknowledgment back to your Azure IoT Central application.
  5. To respond to a command such as echo from your Azure IoT Central application, add the following definition:

    // Respond to the echo command
    function onCommandEcho(request, response) {
      // Display console info
      console.log(' * Echo command received');
      // Respond
      response.send(10, 'Success', function (errorMessage) {});
    }
    
  6. Add the following code to complete the connection to Azure IoT Central and hook up the functions in the client code:

    // Handle device connection to Azure IoT Central.
    var connectCallback = (err) => {
      if (err) {
        console.log(`Device could not connect to Azure IoT Central: ${err.toString()}`);
      } else {
        console.log('Device successfully connected to Azure IoT Central');
    
        // Create handler for countdown command
        hubClient.onDeviceMethod('echo', onCommandEcho);
    
        // Send telemetry measurements to Azure IoT Central every 1 second.
        setInterval(sendTelemetry, 1000);
    
        // Get device twin from Azure IoT Central.
        hubClient.getTwin((err, twin) => {
          if (err) {
            console.log(`Error getting device twin: ${err.toString()}`);
          } else {
            // Send device properties once on device start up.
            sendDeviceProperties(twin);
    
            // Apply device settings and handle changes to device settings.
            handleSettings(twin);
          }
        });
      }
    };
    
  7. Register and connect the device to your IoT Central application:

    // Start the device (connect it to Azure IoT Central).
    provisioningClient.register((err, result) => {
      if (err) {
        console.log("error registering device: " + err);
      } else {
        console.log('registration succeeded');
        console.log('assigned hub=' + result.assignedHub);
        console.log('deviceId=' + result.deviceId);
        var connectionString = 'HostName=' + result.assignedHub + ';DeviceId=' + result.deviceId + ';SharedAccessKey=' + symmetricKey;
        hubClient = Client.fromConnectionString(connectionString, iotHubTransport);
    
        hubClient.open(connectCallback);
      }
    });
    
  8. Save the changes you've made.

Run the client code

Now you can run the client code and see how it interacts with your IoT Central application:

  1. To run the sample, enter the following command in your command-line environment:

    node ConnectedAirConditioner.js
    

    Note

    Make sure you are in the connectedairconditioner folder when you run this command.

  2. The application prints output to the console:

    Client application output

  3. After about 30 seconds, you see the telemetry on the device Measurements page:

    Real telemetry

  4. On the Settings page, you can see the setting is now synchronized. When the device first connected, it received the setting value and acknowledged the change:

    Setting synchronized

  5. On the Settings page, set the device temperature to 95 and choose Update device. Your sample application receives and processes this change:

    Receive and process setting

    Note

    There are two "setting update" messages. One when the pending status is sent and one when the completed status is sent.

  6. On the Measurements page you can see that the device is sending higher temperature values:

    Temperature telemetry is now higher

Next steps

In this tutorial, you learned how to:

  • Add a new real device
  • Configure the new device
  • Get connection string for real device from the application
  • Understand how client code maps to the application
  • Configure client code for the real device

Now that you've connected a real device to your Azure IoT Central application, here are some suggested next steps.

As an operator, you can learn how to:

As a device developer, you can learn how to: