Connect your simulated device to your IoT hub using Node

Introduction

Azure IoT Hub is a fully managed service that enables reliable and secure bi-directional communications between millions of Internet of Things (IoT) devices and a solution back end. One of the biggest challenges that IoT projects face is how to reliably and securely connect devices to the solution back end. To address this challenge, IoT Hub:

  • Offers reliable device-to-cloud and cloud-to-device hyper-scale messaging.
  • Enables secure communications using per-device security credentials and access control.
  • Includes device libraries for the most popular languages and platforms.

This tutorial shows you how to:

  • Use the Azure portal to create an IoT hub.
  • Create a device identity in your IoT hub.
  • Create a simulated device app that sends telemetry to your solution back end.

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

  • CreateDeviceIdentity.js, which creates a device identity and associated security key to connect your simulated device app.
  • ReadDeviceToCloudMessages.js, which displays the telemetry sent by your simulated device app.
  • SimulatedDevice.js, which connects to your IoT hub with the device identity created earlier, and sends a telemetry message every second using the MQTT protocol.

Note

The article Azure IoT SDKs provides information about the Azure IoT SDKs that you can use to build both applications to run on devices and your solution back end.

To complete this tutorial, you need the following:

  • Node.js version 4.0.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. Select New > Internet of Things > IoT Hub.

    Azure portal Jumpbar

  3. In the IoT hub pane, enter the following information for your IoT hub:

    • Name: Create a name for your IoT hub. If the name you enter is valid, a green check mark appears.

    Important

    The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

    • Pricing and scale tier: For this tutorial, select the F1 - Free tier. For more information, see the Pricing and scale tier.

    • Resource group: Create a resource group to host the IoT hub or use an existing one. For more information, see Use resource groups to manage your Azure resources

    • Location: Select the closest location to you.

    • Pin to dashboard: Check this option for easy access to your IoT hub from the dashboard.

      IoT hub window

  4. Click Create. Your IoT hub might take a few minutes to create. You can monitor the progress in the Notifications pane.

Now that you have created an IoT hub, locate the important information that you use to connect devices and applications to your IoT hub.

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

    New IoT hub window

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

    Shared access policies

You have now created your IoT hub. You have the IoT Hub host name and the IoT Hub connection string that you need to complete the rest of this tutorial.

Create a device identity

In this section, you create a Node.js console app that creates a device identity in the identity registry in your IoT hub. A device can only connect to IoT hub if it has an entry in the identity registry. For more information, see the Identity Registry section of the IoT Hub developer guide. Run this app to generate the unique device ID and key your device uses to identify itself when it sends device-to-cloud messages.

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

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

    npm install azure-iothub --save
    
  3. Using a text editor, create a CreateDeviceIdentity.js file in the createdeviceidentity folder.

  4. Add the following require statement at the start of the CreateDeviceIdentity.js file:

    'use strict';
    
    var iothub = require('azure-iothub');
    
  5. Add the following code to the CreateDeviceIdentity.js file. Replace the placeholder value with the IoT Hub connection string for the hub you created in the previous section:

    var connectionString = '{iothub connection string}';
    
    var registry = iothub.Registry.fromConnectionString(connectionString);
    
  6. Add the following code to create a device definition in the identity registry in your IoT hub. This code creates a device if the device ID does not exist in the identity registry, otherwise it returns the key of the existing device:

    var device = {
      deviceId: 'myFirstNodeDevice'
    }
    registry.create(device, function(err, deviceInfo, res) {
      if (err) {
        registry.get(device.deviceId, printDeviceInfo);
      }
      if (deviceInfo) {
        printDeviceInfo(err, deviceInfo, res)
      }
    });
    
    function printDeviceInfo(err, deviceInfo, res) {
      if (deviceInfo) {
        console.log('Device ID: ' + deviceInfo.deviceId);
        console.log('Device key: ' + deviceInfo.authentication.symmetricKey.primaryKey);
      }
    }
    

    Important

    The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  7. Save and close CreateDeviceIdentity.js file.

  8. To run the createdeviceidentity application, execute the following command at the command prompt in the createdeviceidentity folder:

    node CreateDeviceIdentity.js 
    
  9. Make a note of the Device ID and Device key. You need these values later when you create an application that connects to IoT Hub as a device.

Note

The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. It stores device IDs and keys to use as security credentials and an enabled/disabled flag that you can use to disable access for an individual device. If your application needs to store other device-specific metadata, it should use an application-specific store. For more information, see the IoT Hub developer guide.

Receive device-to-cloud messages

In this section, you create a Node.js console app that reads device-to-cloud messages from IoT Hub. An IoT hub exposes an Event Hubs-compatible endpoint to enable you to read device-to-cloud messages. To keep things simple, this tutorial creates a basic reader that is not suitable for a high throughput deployment. The Process device-to-cloud messages tutorial shows you how to process device-to-cloud messages at scale. The Get Started with Event Hubs tutorial provides further information that is applicable to the IoT Hub Event Hub-compatible endpoints.

Note

The Event Hub-compatible endpoint for reading device-to-cloud messages always uses the AMQP protocol.

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

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

    npm install azure-event-hubs --save
    
  3. Using a text editor, create a ReadDeviceToCloudMessages.js file in the readdevicetocloudmessages folder.

  4. Add the following require statements at the start of the ReadDeviceToCloudMessages.js file:

    'use strict';
    
    var EventHubClient = require('azure-event-hubs').Client;
    
  5. Add the following variable declaration and replace the placeholder value with the IoT Hub connection string for your hub:

    var connectionString = '{iothub connection string}';
    
  6. Add the following two functions that print output to the console:

    var printError = function (err) {
      console.log(err.message);
    };
    
    var printMessage = function (message) {
      console.log('Message received: ');
      console.log(JSON.stringify(message.body));
      console.log('');
    };
    
  7. Add the following code to create the EventHubClient, open the connection to your IoT Hub, and create a receiver for each partition. This application uses a filter when it creates a receiver so that the receiver only reads messages sent to IoT Hub after the receiver starts running. This filter is useful in a test environment so you see just the current set of messages. In a production environment, your code should make sure that it processes all the messages. For more information, see the How to process IoT Hub device-to-cloud messages tutorial:

    var client = EventHubClient.fromConnectionString(connectionString);
    client.open()
        .then(client.getPartitionIds.bind(client))
        .then(function (partitionIds) {
            return partitionIds.map(function (partitionId) {
                return client.createReceiver('$Default', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
                    console.log('Created partition receiver: ' + partitionId)
                    receiver.on('errorReceived', printError);
                    receiver.on('message', printMessage);
                });
            });
        })
        .catch(printError);
    
  8. Save and close the ReadDeviceToCloudMessages.js file.

Create a simulated device app

In this section, you create a Node.js console app that simulates a device that sends device-to-cloud messages to an IoT hub.

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

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

    npm install azure-iot-device azure-iot-device-mqtt --save
    
  3. Using a text editor, create a SimulatedDevice.js file in the simulateddevice folder.

  4. Add the following require statements at the start of the SimulatedDevice.js file:

    'use strict';
    
    var clientFromConnectionString = require('azure-iot-device-mqtt').clientFromConnectionString;
    var Message = require('azure-iot-device').Message;
    
  5. Add a connectionString variable and use it to create a Client instance. Replace {youriothostname} with the name of the IoT hub you created the Create an IoT Hub section. Replace {yourdevicekey} with the device key value you generated in the Create a device identity section:

    var connectionString = 'HostName={youriothostname};DeviceId=myFirstNodeDevice;SharedAccessKey={yourdevicekey}';
    
    var client = clientFromConnectionString(connectionString);
    
  6. Add the following function to display output from the application:

    function printResultFor(op) {
      return function printResult(err, res) {
        if (err) console.log(op + ' error: ' + err.toString());
        if (res) console.log(op + ' status: ' + res.constructor.name);
      };
    }
    
  7. Create a callback and use the setInterval function to send a message to your IoT hub every second:

    var connectCallback = function (err) {
      if (err) {
        console.log('Could not connect: ' + err);
      } else {
        console.log('Client connected');
    
        // Create a message and send it to the IoT Hub every second
        setInterval(function(){
            var temperature = 20 + (Math.random() * 15);
            var humidity = 60 + (Math.random() * 20);            
            var data = JSON.stringify({ deviceId: 'myFirstNodeDevice', temperature: temperature, humidity: humidity });
            var message = new Message(data);
            message.properties.add('temperatureAlert', (temperature > 30) ? 'true' : 'false');
            console.log("Sending message: " + message.getData());
            client.sendEvent(message, printResultFor('send'));
        }, 1000);
      }
    };
    
  8. Open the connection to your IoT Hub and start sending messages:

    client.open(connectCallback);
    
  9. Save and close the SimulatedDevice.js file.

Note

To keep things simple, this tutorial does not implement any retry policy. In production code, you should implement retry policies (such as an exponential backoff), as suggested in the MSDN article Transient Fault Handling.

Run the apps

You are now ready to run the apps.

  1. At a command prompt in the readdevicetocloudmessages folder, run the following command to begin monitoring your IoT hub:

    node ReadDeviceToCloudMessages.js 
    

    Node.js IoT Hub service app to monitor device-to-cloud messages

  2. At a command prompt in the simulateddevice folder, run the following command to begin sending telemetry data to your IoT hub:

    node SimulatedDevice.js
    

    Node.js IoT Hub device app to send device-to-cloud messages

  3. The Usage tile in the Azure portal shows the number of messages sent to the IoT hub:

    Azure portal Usage tile showing number of messages sent to IoT Hub

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 used this device identity to enable the simulated device app to send device-to-cloud messages to the IoT hub. You also created an app that displays the messages received by the IoT hub.

To continue getting started with IoT Hub and to explore other IoT scenarios, see:

To learn how to extend your IoT solution and process device-to-cloud messages at scale, see the Process device-to-cloud messages tutorial.

To continue to get started with Azure IoT Hub and to explore other IoT scenarios, see the following: