chenyc
2025-12-09 545c24c6a711d71b65f3d4e8122fee3837fb1edc
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
'use strict';
 
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
 
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
 
var cryptojs = require('crypto-js');
var os = require('os');
var axios = require('axios');
var qs = require('qs');
 
function hmacSign(type, secret, content) {
  return cryptojs.HmacSHA1(content, secret).toString();
}
 
function mqttMatch(filter, topic) {
  var filterArray = filter.split('/');
  var length = filterArray.length;
  var topicArray = topic.split('/');
  for (var i = 0; i < length; ++i) {
    var left = filterArray[i];
    var right = topicArray[i];
    if (left === '#') return topicArray.length >= length - 1;
    if (left !== '+' && left !== right) return false;
  }
  return length === topicArray.length;
}
 
function mqttNotMatch(filter, topic) {
  return !mqttMatch(filter, topic);
}
 
function createGuid() {
  var id = 1;
  return function () {
    return String(id++);
  };
}
 
function isJsonString(str) {
  try {
    if (_typeof(JSON.parse(str)) == "object") {
      return true;
    }
  } catch (e) {}
  return false;
}
 
function signUtil(deviceConfig) {
  var signMethod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'sha1';
 
  var timestamp = Date.now();
  // 忽略三元组大小写
  tripleIgnoreCase(deviceConfig);
  var device = {
    productKey: deviceConfig.productKey,
    deviceName: deviceConfig.deviceName,
    clientId: deviceConfig.productKey + '&' + deviceConfig.deviceName,
    timestamp: timestamp
  };
  device.signMethod = 'hmac' + signMethod;
  var signcontent = 'clientId' + device.clientId + 'deviceName' + device.deviceName + 'productKey' + device.productKey + 'timestamp' + timestamp;
  device.sign = hmacSign(signMethod, deviceConfig.deviceSecret, signcontent);
  return device;
}
 
function deviceRegisterSign(productKey, productSecret, deviceName, random) {
  var signMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'sha1';
 
  // 忽略三元组大小写
  var config = { productKey: productKey, productSecret: productSecret, deviceName: deviceName };
  tripleIgnoreCase(config);
  // signMethod = `hmac${signMethod}`;
  var signcontent = 'deviceName' + config.deviceName + 'productKey' + config.productKey + 'random' + random;
  // console.log("deviceRegisterSign",signMethod,signcontent)
  var sign = hmacSign("sha1", config.productSecret, signcontent);
 
  return sign;
}
 
function createDebug(mod) {
  return function () {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
 
    var debugMod = process.env.DEBUG;
    if (debugMod && (debugMod === '*' || mod.indexOf(debugMod) > -1)) {
      var _console;
 
      var _args = [mod + ':'].concat(args);
      (_console = console).log.apply(_console, _toConsumableArray(_args));
    }
  };
}
 
function getIP() {
  var ifaces = os.networkInterfaces();
  var ip = "";
  for (var dev in ifaces) {
    ifaces[dev].forEach(function (details) {
      if (details.family == 'IPv4' && dev === 'en0') {
        ip = details.address;
      }
    });
  }
  return ip;
}
 
/*
 *  设备动态注册
 *    子设备注册+直连设备使用一型一密动态注册
 */
function register(_ref, cb) {
  var productKey = _ref.productKey,
      productSecret = _ref.productSecret,
      deviceName = _ref.deviceName,
      random = _ref.random,
      signMethod = _ref.signMethod,
      registerURL = _ref.registerURL;
 
  var rd = random || Math.random().toString(36).substr(2);
  var sm = signMethod || "hmacsha1";
  var url = registerURL || "https://iot-auth.cn-shanghai.aliyuncs.com/auth/register/device";
  var sign = deviceRegisterSign(productKey, productSecret, deviceName, rd, sm);
  var data = qs.stringify({
    productKey: productKey,
    deviceName: deviceName,
    random: rd,
    sign: sign,
    signMethod: sm
  });
  axios.post(url, data).then(function (res) {
    var data = res.data;
    if (data.code != 200) {
      throw data;
    }
    cb(data);
  }).catch(function (error) {
    cb(error);
  });
}
// 三元组不为空
function tripleExpectNotNull(triple) {
  if (typeof triple.productKey === 'undefined') {
    throw new Error('productKey should not be empty');
  }
  if (typeof triple.deviceName === 'undefined') {
    throw new Error('deviceName should not be empty');
  }
  if (typeof triple.deviceSecret === 'undefined') {
    throw new Error('deviceSecret should not be empty');
  }
}
 
// 三元组忽略大小写 triple ignore case
function tripleIgnoreCase(config) {
  Object.keys(config).forEach(function (originKey) {
    var key = originKey.toLowerCase();
    switch (key) {
      case "productkey":
        config.productKey = config[originKey];
        break;
      case "devicename":
        config.deviceName = config[originKey];
        break;
      case "devicesecret":
        config.deviceSecret = config[originKey];
        break;
    }
  });
  return config;
}
 
// 获取当前sdk版本
// 支付宝小程序:JS|Ali
// 微信小程序:JS|WX
// 浏览器:JS|Broswer  
// node环境:NodeJS
// 命令行:JS|CLI
// 未知:JS|UNKNOW
var LANG = 'JS|UNKNOW';
 
function getSDKLanguage() {
  // 支付宝小程序运行环境 不完全可靠
  if (typeof my !== 'undefined' && (my.navigateToMiniProgram || my.navigateBackMiniProgram)) {
    return "JS|Ali";
  }
  // 微信小程序判断 不完全可靠
  if (typeof wx !== 'undefined' && (wx.navigateToMiniProgram || wx.navigateBackMiniProgram)) {
    return "JS|WX";
  }
  // 浏览器环境判断
  if (typeof window !== 'undefined' && typeof window.document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
    return "JS|Broswer ";
  }
  // node环境
  if (typeof module !== 'undefined' && module.exports) {
    return "NodeJS";
  }
 
  // 返回主动设置的环境值
  return LANG;
}
function setSDKLanguage(lang) {
  LANG = lang;
}
 
exports.tripleIgnoreCase = tripleIgnoreCase;
exports.tripleExpectNotNull = tripleExpectNotNull;
exports.getIP = getIP;
exports.hmacSign = hmacSign;
exports.mqttMatch = mqttMatch;
exports.mqttNotMatch = mqttNotMatch;
exports.createGuid = createGuid;
exports.signUtil = signUtil;
exports.createDebug = createDebug;
exports.register = register;
exports.isJsonString = isJsonString;
exports.getSDKLanguage = getSDKLanguage;
exports.setSDKLanguage = setSDKLanguage;