Authentication and connection
A device must be authenticated before it can connect to IoT Platform. This topic describes how to use the Node.js Link software development kit (SDK) to connect a device to IoT Platform.
Prerequisites
- The development environment is set up.
- Create a product and a device in IoT Platform. For more information, see Create a product and Create a single device.
When you create a product, set the Authentication Mode parameter to Device Secret. When you add a device to the product, IoT Platform issues a ProductSecret and a DeviceSecret to the device. When you connect the device to IoT Platform, IoT Platform verifies the device by using the ProductKey and DeviceSecret of the device.
Background information
The Node.js Link SDK supports device identity authentication using device secrets. IoT Platform provides the following three device secret authentication methods for different environments.
| Authentication method | Description | References |
| Unique-certificate-per-device | Each device is programmed with its own device certificate (ProductKey, DeviceName, and DeviceSecret). | Unique-certificate-per-device |
| Unique-certificate-per-product | Unique-certificate-per-product authentication includes the following two methods:
| Unique-certificate-per-product Note For more information about the differences between pre-registration and pre-registration-free methods, see Differences between pre-registration and pre-registration-free methods. |
API description
- Prototype:
iot.device(options) - Description: Creates a device instance and connects it to Alibaba Cloud IoT Platform.
- Request parameters:
Parameter Type Description brokerUrlString The server URI of the MQTT broker. The default value is mqtt://${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com:1883/.In the URI, ${productKey} is the ProductKey of your device.
productKeyString The authentication credentials of the device. For more information, see Obtain device credentials. deviceNameString deviceSecretString regionIdString The ID of the region where the device is connected. For more information, see Regions and zones.
keepaliveInteger The heartbeat interval for the keepalive connection between the device and IoT Platform. The default value is 60 seconds. cleanBoolean Specifies whether to clear the connection session. Valid values: - true: yes
- false (default): no
- Return value: An MQTT client connection instance.
- The following events are triggered:
connect: The device successfully connects to IoT Platform.offline: The device disconnects from IoT Platform.message: The device receives a message from IoT Platform.error: An error occurs. For example, the device credentials are incorrect.
Set the connection region
Alibaba Cloud IoT Platform is available in multiple regions. The default region for the SDK is China (Shanghai). For more information, see Regions and zones.
When you use the SDK to connect a device, you can set the regionId parameter to connect the device to a specific region. The following sample code sets the region to ap-northeast-1, which is Asia Pacific NE 1 (Tokyo).
You can log on to the IoT Platform console and view the region of your device above the navigation pane on the left.
// Import the package in Node.js
const iot = require('alibabacloud-iot-device-sdk');
const device = iot.device({
productKey: `${productKey}`,
deviceName: `${deviceName}`,
deviceSecret: `${deviceSecret}`,
regionId: 'ap-northeast-1'
});
device.on('connect', () => {
console.log('connect successfully!');
})Set the MQTT broker server URI
The format is schema://host:port.
hostis the connection domain name of the device. For more information, see Obtain device credentials.The following are examples of
host:- For an Enterprise instance or a public instance of an IoT Platform service activated on or after July 30, 2021:
iot-06******.mqtt.iothub.aliyuncs.comIn this example,
iot-06******is the instance ID. - For a public instance of an IoT Platform service activated before July 30, 2021:
a1BOO******.iot-as-mqtt.cn-shanghai.aliyuncs.comIn the domain name,
a1BOO******is the ProductKey of your device.
- For an Enterprise instance or a public instance of an IoT Platform service activated on or after July 30, 2021:
schemacan bews,wss,tcp,unix,ssl,tls, ortcps.
const iot = require('alibabacloud-iot-device-sdk');
const device = iot.device({
productKey: `${productKey}`,
deviceName: `${deviceName}`,
deviceSecret: `${deviceSecret}`,
brokerUrl: `wss://${productKey}.iot-as-mqtt.${regionId}.aliyuncs.com:443`,
});
device.on('connect', () => {
console.log('connect successfully!');
});Unique-certificate-per-device
const iot = require('alibabacloud-iot-device-sdk');
// Creating an iot.device object initiates a connection to Alibaba Cloud IoT.
const device = iot.device({
productKey: `${productKey}`, //Replace ${productKey} with the actual ProductKey of your product.
deviceName: `${deviceName}`,//Replace ${deviceName} with the actual DeviceName of your device.
deviceSecret: `${deviceSecret}`,//Replace ${deviceSecret} with the actual DeviceSecret of your device.
});
// Listen for the connect event.
device.on('connect', () => {
//Replace ${productKey} and ${deviceName} with the actual values.
device.subscribe(`/${productKey}/${deviceName}/user/get`);
console.log('connect successfully!');
device.publish(`/${productKey}/${deviceName}/user/update`, 'hello world!');
});
// Listen for the message event.
device.on('message', (topic, payload) => {
console.log(topic, payload.toString());
}); - If the device disconnects unexpectedly, the program automatically attempts to reconnect to IoT Platform.
keepaliveis 60. If you set this parameter, its value cannot be less than 60.
Unique-certificate-per-product
const iot = require('alibabacloud-iot-device-sdk');
const params = {
productKey: `${productKey}`,
productSecret: `${productSecret}`,
deviceName: `${deviceName}`
};
let device;
iot.register(params, (res) => {
console.log("register:", res);
if (res.code == '200') {
// res.data.deviceSecret is the device secret returned by IoT Platform. Securely store this secret.
// After the device successfully connects to IoT Platform using its credentials, you cannot use this function again to obtain the DeviceSecret.
// Create a device object to connect to Alibaba Cloud IoT Platform.
device = iot.device({
productKey: `${productKey}`,
deviceName: `${deviceName}`,
// res.data.deviceSecret is the device secret returned by IoT Platform.
deviceSecret: res.data.deviceSecret,
});
}
});- For the complete sample code for unique-certificate-per-product authentication, see one_model_one_secret.js.
res.code:Value Description 200 The DeviceSecret is obtained. 5005 Invalid product. The ProductKey provided by the device is incorrect. 6100 Invalid device. No device with the specified deviceNameexists in IoT Platform.6288 The product does not support dynamic registration. Enable dynamic registration for the product in IoT Platform. 6289 The device is already activated and cannot be registered again. NoteA device certificate can be used to activate only one physical device.
If Device A is activated by using a DeviceName but Device B must use the DeviceName, you can delete Device A in the IoT Platform console and disable the DeviceSecret of Device A. This way, you can use the DeviceName to add and activate Device B.
If a device needs to be reactivated because the DeviceSecret is lost, you must call the ResetThing operation to reset the device status to Inactive. Then, you can reactivate the device. In this case, the DeviceSecret that is issued by IoT Platform remains unchanged.
6600 Verification error. The ProductSecret of the device is incorrect.
Disconnect from the cloud
To disconnect from IoT Platform, call the end function.
const iot = require('alibabacloud-iot-device-sdk');
const device = iot.device({
productKey: `${productKey}`,
deviceName: `${deviceName}`,
deviceSecret: `${deviceSecret}`,
});
/*Disconnect from Alibaba Cloud IoT Platform*/
device.end();