Get started with IoT Hub module identity and module twin (Node.js)
Module identities and module twins are similar to Azure IoT Hub device identity and device twin, but provide finer granularity. While Azure IoT Hub device identity and device twin enable the back-end application to configure a device and provides visibility on the device's conditions, a module identity and module twin provide these capabilities for individual components of a device. On capable devices with multiple components, such as operating system devices or firmware devices, it allows for isolated configuration and conditions for each component.
Note
The features described in this article are available only in the standard tier of IoT Hub. For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier for your solution.
At the end of this article, you have two Node.js apps:
CreateIdentities: creates a device identity, a module identity, and associated security keys to connect your device and module clients.
UpdateModuleTwinReportedProperties: sends updated module twin, reported properties to your IoT Hub.
Note
For more information about the SDK tools available to build both device and back-end apps, see Azure IoT SDKs.
Prerequisites
An IoT hub in your Azure subscription. If you don't have a hub yet, you can follow the steps in Create an IoT hub.
Node.js version 10.0.x or later. Prepare your development environment describes how to install Node.js for this article on either Windows or Linux.
Module authentication
You can use symmetric keys or X.509 certificates to authenticate module identities. For X.509 certificate authentication, the module's certificate must have its common name (CN) formatted like CN=<deviceid>/<moduleid>
. For example:
openssl req -new -key d1m1.key.pem -out d1m1.csr -subj "/CN=device01\/module01"
Get the IoT hub connection string
In this article, you create a back-end service that adds a device in the identity registry and then adds a module to that device. Your service requires the registry write permission. By default, every IoT hub is created with a shared access policy named registryReadWrite that grants this permission.
To get the IoT Hub connection string for the registryReadWrite policy, follow these steps:
In the Azure portal, select Resource groups. Select the resource group where your hub is located, and then select your hub from the list of resources.
On the left-side pane of your hub, select Shared access policies.
From the list of policies, select the registryReadWrite policy.
Copy the Primary connection string and save the value.
For more information about IoT Hub shared access policies and permissions, see Access control and permissions.
Important
This article includes steps to connect to a service using a shared access signature. This authentication method is convenient for testing and evaluation, but authenticating to a service with Microsoft Entra ID or managed identities is a more secure approach. To learn more, see Security best practices > Cloud security.
Create a device identity and a module identity in IoT Hub
In this section, you create a Node.js app that creates a device identity and a module identity in the identity registry in your IoT hub. A device or module can't connect to IoT hub unless it has an entry in the identity registry. For more information, see Understand the identity registry in your IoT hub. When you run this console app, it generates a unique ID and key for both device and module. The ID and key are case-sensitive. Your device and module use these values to identify itself when it sends device-to-cloud messages to IoT Hub.
Important
This article includes steps to connect a device using a shared access signature, also called symmetric key authentication. This authentication method is convenient for testing and evaluation, but authenticating a device using X.509 certificates is a more secure approach. To learn more, see Security best practices > Connection security.
Create a directory to hold your code.
Inside of that directory, first run npm init -y to create an empty package.json with defaults. This is the project file for your code.
Run npm install -S azure-iothub@modules-preview to install the service SDK inside the node_modules subdirectory.
Note
The subdirectory name node_modules uses the word module to mean "a node library". The term here has nothing to do with IoT Hub modules.
Create the following .js file in your directory. Call it add.js. Copy and paste your hub connection string and hub name.
var Registry = require('azure-iothub').Registry; var uuid = require('uuid'); // Copy/paste your connection string and hub name here var serviceConnectionString = '<hub connection string from portal>'; var hubName = '<hub name>.azure-devices.net'; // Create an instance of the IoTHub registry var registry = Registry.fromConnectionString(serviceConnectionString); // Insert your device ID and moduleId here. var deviceId = 'myFirstDevice'; var moduleId = 'myFirstModule'; // Create your device as a SAS authentication device var primaryKey = new Buffer(uuid.v4()).toString('base64'); var secondaryKey = new Buffer(uuid.v4()).toString('base64'); var deviceDescription = { deviceId: deviceId, status: 'enabled', authentication: { type: 'sas', symmetricKey: { primaryKey: primaryKey, secondaryKey: secondaryKey } } }; // First, create a device identity registry.create(deviceDescription, function(err) { if (err) { console.log('Error creating device identity: ' + err); process.exit(1); } console.log('device connection string = "HostName=' + hubName + ';DeviceId=' + deviceId + ';SharedAccessKey=' + primaryKey + '"'); // Then add a module to that device registry.addModule({ deviceId: deviceId, moduleId: moduleId }, function(err) { if (err) { console.log('Error creating module identity: ' + err); process.exit(1); } // Finally, retrieve the module details from the hub so we can construct the connection string registry.getModule(deviceId, moduleId, function(err, foundModule) { if (err) { console.log('Error getting module back from hub: ' + err); process.exit(1); } console.log('module connection string = "HostName=' + hubName + ';DeviceId=' + foundModule.deviceId + ';ModuleId='+foundModule.moduleId+';SharedAccessKey=' + foundModule.authentication.symmetricKey.primaryKey + '"'); process.exit(0); }); }); });
This app creates a device identity with ID myFirstDevice and a module identity with ID myFirstModule under device myFirstDevice. (If that module ID already exists in the identity registry, the code simply retrieves the existing module information.) The app then displays the primary key for that identity. You use this key in the simulated module app to connect to your IoT hub.
Run this using node add.js. It will give you a connection string for your device identity and another one for your module identity.
Note
The IoT Hub identity registry only stores device and module identities to enable secure access to the IoT hub. The identity registry stores device IDs and keys to use as security credentials. The identity registry also stores an enabled/disabled flag for each device that you can use to disable access for that device. If your application needs to store other device-specific metadata, it should use an application-specific store. There is no enabled/disabled flag for module identities. For more information, see Understand the identity registry in your IoT Hub in the IoT Hub developer guide.
Update the module twin using Node.js device SDK
In this section, you create a Node.js app on your simulated device that updates the module twin reported properties.
Get your module connection string. Sign in to the Azure portal. Navigate to your IoT Hub and select IoT devices. Find myFirstDevice, open it and you see myFirstModule was successfully created. Copy the module connection string. It is needed in the next step.
Similar to what you did in the previous section, create a directory for your device code and use npm to initialize it and install the device SDK (npm install -S azure-iot-device-amqp@modules-preview).
Note
The npm install command may feel slow. Be patient; it's pulling down lots of code from the package repository.
Note
If you see an error that says npm ERR! registry error parsing json, this is safe to ignore. If you see an error that says npm ERR! registry error parsing json, this is safe to ignore.
Create a file called twin.js. Copy and paste your module identity string.
var Client = require('azure-iot-device').Client; var Protocol = require('azure-iot-device-amqp').Amqp; // Copy/paste your module connection string here. var connectionString = '<insert module connection string here>'; // Create a client using the Amqp protocol. var client = Client.fromConnectionString(connectionString, Protocol); client.on('error', function (err) { console.error(err.message); }); // connect to the hub client.open(function(err) { if (err) { console.error('error connecting to hub: ' + err); process.exit(1); } console.log('client opened'); // Create device Twin client.getTwin(function(err, twin) { if (err) { console.error('error getting twin: ' + err); process.exit(1); } // Output the current properties console.log('twin contents:'); console.log(twin.properties); // Add a handler for desired property changes twin.on('properties.desired', function(delta) { console.log('new desired properties received:'); console.log(JSON.stringify(delta)); }); // create a patch to send to the hub var patch = { updateTime: new Date().toString(), firmwareVersion:'1.2.1', weather:{ temperature: 72, humidity: 17 } }; // send the patch twin.properties.reported.update(patch, function(err) { if (err) throw err; console.log('twin state reported'); }); }); });
Now, run this using the command node twin.js.
F:\temp\module_twin>node twin.js
You will then see:
client opened twin contents: { reported: { update: [Function: update], '$version': 1 }, desired: { '$version': 1 } } new desired properties received: {"$version":1} twin state reported
Next steps
To continue getting started with IoT Hub and to explore other IoT scenarios, see: