forked from wongxming/aliyun-iot-client-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·54 lines (45 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';
const crypto = require('./lib/hex_hmac_sha1');
const mqtt = require('mqtt');
/**
* options
productKey
deviceName
deviceSecret
*/
exports.getAliyunIotMqttClient = function(opts) {
if (!opts || !opts.productKey ||
!opts.deviceName || !opts.deviceSecret) {
throw new Error('options need productKey,deviceName,deviceSecret');
}
if (opts.protocol === 'mqtts' && !opts.ca) {
throw new Error('mqtts need ca ');
}
if (!opts.host && !opts.regionId) {
throw new Error('options need host or regionId (aliyun regionId)');
}
const deviceSecret = opts.deviceSecret;
delete opts.deviceSecret;
let secureMode = (opts.protocol === 'mqtts') ? 2 : 3;
var options = {
productKey: opts.productKey,
deviceName: opts.deviceName,
timestamp: Date.now(),
clientId: Math.random().toString(36).substr(2)
}
let keys = Object.keys(options).sort();
// 按字典序排序
keys = keys.sort();
const list = [];
keys.map((key) => {
list.push(`${key}${options[key]}`);
});
const contentStr = list.join('');
opts.password = crypto.hex_hmac_sha1(deviceSecret, contentStr);
opts.clientId = `${options.clientId}|securemode=${secureMode},signmethod=hmacsha1,timestamp=${options.timestamp}|`;
opts.username = `${options.deviceName}&${options.productKey}`;
opts.port = opts.port || 1883;
opts.host = opts.host || `${opts.productKey}.iot-as-mqtt.${opts.regionId}.aliyuncs.com`;
opts.protocol = opts.protocol || 'mqtt';
return mqtt.connect(opts);
}