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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _const = require('./const');
 
var _package = require('../package.json');
 
var _package2 = _interopRequireDefault(_package);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
var _require = require('./utils'),
    hmacSign = _require.hmacSign,
    getSDKLanguage = _require.getSDKLanguage;
 
var util = require('util');
 
var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
var DEFAULT_REGION = 'cn-shanghai';
var BROKER_URL = '%s%s.iot-as-mqtt.%s.aliyuncs.com:%s/';
var tlsPrefix = ['tls://', 'mqtts://', 'wss://', 'wxs://', 'alis://'];
 
var Model = function () {
  function Model(config) {
    _classCallCheck(this, Model);
 
    //初始化参数
    this.init(config);
    //参数校验合法
    this.configchecking();
  }
 
  // 获取通配订阅topic
 
 
  _createClass(Model, [{
    key: 'getWildcardTopic',
    value: function getWildcardTopic() {
      return util.format("/sys/%s/%s/thing", this.productKey, this.deviceName);
    }
 
    // 获取三元组
 
  }, {
    key: 'triple',
    value: function triple() {
      var productKey = this.productKey,
          deviceName = this.deviceName,
          deviceSecret = this.deviceSecret;
 
      return {
        productKey: productKey,
        deviceName: deviceName,
        deviceSecret: deviceSecret
      };
    }
  }, {
    key: 'getPostEventMethod',
    value: function getPostEventMethod(eventName) {
      return util.format(_const.ALIYUN_BROKER_METHODS_TEMPLATE.POST_EVENT, eventName);
    }
  }, {
    key: 'getPostEvenTopic',
    value: function getPostEvenTopic(eventName) {
      return util.format(_const.ALIYUN_BROKER_TOPICS.EVENT_POST_TOPIC, this.productKey, this.deviceName, eventName);
    }
  }, {
    key: 'getWildcardEvenTopic',
    value: function getWildcardEvenTopic() {
      return util.format(_const.ALIYUN_BROKER_TOPICS.EVENT_WILDCARD_TOPIC, this.productKey, this.deviceName);
    }
  }, {
    key: 'getPostEvenReplyTopic',
    value: function getPostEvenReplyTopic(eventName) {
      return util.format(_const.ALIYUN_BROKER_TOPICS.EVENT_POST_REPLY_TOPIC, this.productKey, this.deviceName, eventName);
    }
  }, {
    key: 'getServiceTopic',
    value: function getServiceTopic(serviceName) {
      var serviceNameReplace = serviceName;
      if (serviceName.indexOf('/') != -1) {
        serviceNameReplace = serviceName.replace('.', '/');
      }
      return util.format(_const.ALIYUN_BROKER_TOPICS.SERVICE_TOPIC, this.productKey, this.deviceName, serviceNameReplace);
    }
  }, {
    key: 'getWildcardServiceTopic',
    value: function getWildcardServiceTopic() {
      return util.format(_const.ALIYUN_BROKER_TOPICS.SERVICE_TOPIC, this.productKey, this.deviceName, '#');
    }
  }, {
    key: 'getWildcardConfigTopic',
    value: function getWildcardConfigTopic() {
      return util.format(_const.ALIYUN_BROKER_TOPICS.CONFIG_WILDCARD_TOPIC, this.productKey, this.deviceName);
    }
  }, {
    key: 'getServiceRespTopic',
    value: function getServiceRespTopic(serviceName) {
      var serviceNameReplace = serviceName;
      if (serviceName.indexOf('/') != -1) {
        serviceNameReplace = serviceName.replace('.', '/');
      }
      return util.format(_const.ALIYUN_BROKER_TOPICS.SERVICE_REPLY_TOPIC, this.productKey, this.deviceName, serviceNameReplace);
    }
  }, {
    key: 'getRRPCRespTopic',
    value: function getRRPCRespTopic(msgId) {
      return util.format(_const.ALIYUN_BROKER_TOPICS.RRPC_RESP_TOPIC, this.productKey, this.deviceName, msgId);
    }
 
    //生成alink协议内容
 
  }, {
    key: 'genAlinkContent',
    value: function genAlinkContent(method, params) {
      var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
      var version = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '1.0';
 
      var msg = {
        id: id,
        version: version,
        params: params,
        method: method
      };
      return msg;
    }
 
    /**
     * 连接参数生成规则
     * broker:${YourProductKey}.iot-as-mqtt.${Region}.aliyuncs.com:1883 
     *    Region:https://help.aliyun.com/document_detail/40654.html?spm=a2c4g.11186623.2.14.6cba65fekp352N
     * ClientId: 表示客户端ID,建议使用设备的MAC地址或SN码,64字符内 ,clientId+"|securemode=3,signmethod=hmacsha1,timestamp=132323232|"
     * Username: deviceName+"&"+productKey 
     * Password: sign_hmac(deviceSecret,content)
     * securemode:表示目前安全模式,可选值有2 (TLS直连模式)和3(TCP直连模式)
     * signmethod:签名算法,支持hmacmd5,hmacsha1,hmacsha256和 sha256,默认为hmacmd5。
     * timestamp: 可选
     */
 
  }, {
    key: 'genConnectPrarms1',
    value: function genConnectPrarms1() {
      var lang = getSDKLanguage();
      var extra = 'lan=' + lang + ',_v=' + _package2.default.version;
      var params = {
        clientId: '\n        ' + this.clientId + '|securemode=' + this.securemode + ',\n        signmethod=hmac' + this.signAlgorithm + ',\n        timestamp=' + this.timestamp + '|\n      ',
        username: this.deviceName + '&' + this.productKey,
        password: hmacSign(this.signAlgorithm, this.deviceSecret, 'clientId' + this.clientId + 'deviceName' + this.deviceName + 'productKey' + this.productKey + 'timestamp' + this.timestamp),
        keepalive: this.keepalive,
        clean: this.clean
        // 支付宝小程序api全局对象my
      };if (lang === 'JS|Ali') {
        params.my = my;
      }
      return params;
    }
  }, {
    key: 'genConnectPrarms',
    value: function genConnectPrarms() {
      var lang = getSDKLanguage();
      var extra = 'lan=' + lang + ',_v=' + _package2.default.version + '|';
      // console.log('extra',extra);
      // const extra =''
      var params = {
        clientId: this.clientId + '|securemode=' + this.securemode + ',signmethod=hmac' + this.signAlgorithm + ',timestamp=' + this.timestamp + ',' + extra,
        username: this.deviceName + '&' + this.productKey,
        password: hmacSign(this.signAlgorithm, this.deviceSecret, 'clientId' + this.clientId + 'deviceName' + this.deviceName + 'productKey' + this.productKey + 'timestamp' + this.timestamp),
        keepalive: this.keepalive,
        clean: this.clean
 
        // 支付宝小程序api全局对象my
      };if (lang === 'JS|Ali') {
        params.my = my;
      }
      return params;
    }
 
    // 初始化连接参数
 
  }, {
    key: 'init',
    value: function init(config) {
      var _this = this;
 
      // 判断是否使用加密模式
      if (config.brokerUrl && tlsPrefix.some(function (prefix) {
        return config.brokerUrl.startsWith(prefix);
      }) || config.protocol && tlsPrefix.some(function (prefix) {
        return config.protocol.startsWith(prefix);
      }) || config.tls) {
        this.securemode = 2;
        this.tls = true;
      } else {
        this.securemode = 3;
      }
      // 浏览器使用433端口,非浏览器使用1883端口
      if (isBrowser) {
        if (this.tls) {
          this.brokerProtocol = 'wss://';
        } else {
          this.brokerProtocol = 'ws://';
        }
        this.brokerPort = 443;
      } else {
        if (this.tls) {
          this.brokerProtocol = 'mqtts://';
        } else {
          this.brokerProtocol = 'mqtt://';
        }
        this.brokerPort = 1883;
      }
 
      // 补充自定义protocol,支持微信小程序wxs://和阿里小程序alis://
      if (config.protocol && (config.protocol.startsWith('wxs') || config.protocol.startsWith('alis'))) {
        // 支持wxs://和wxs两种传入模式
        this.brokerProtocol = config.protocol.indexOf('://') != -1 ? config.protocol : config.protocol + "://";
        this.brokerPort = 443;
      }
 
      //三元组忽略大小写
      Object.keys(config).forEach(function (originKey) {
        var key = originKey.toLowerCase();
        switch (key) {
          case "productkey":
            _this.productKey = config[originKey];
            break;
          case "devicename":
            _this.deviceName = config[originKey];
            break;
          case "devicesecret":
            _this.deviceSecret = config[originKey];
            break;
        }
      });
      this.region = config.region || config.regionId;
      this.keepalive = config.keepalive || 60; //keepalive,默认60
      this.clean = config.clean || false; //cleanSession配置选项
      this.signAlgorithm = config.signAlgorithm || 'sha1';
      this.config = config || {};
      if (config.brokerUrl) {
        this.brokerUrl = config.brokerUrl;
      } else {
        this.brokerUrl = util.format(BROKER_URL, this.brokerProtocol, this.productKey, this.region || DEFAULT_REGION, this.brokerPort);
      }
      this.timestamp = Date.now();
      this.clientId = config.clientId ? '' + config.clientId : this.productKey + '&' + this.deviceName;
 
      /* 初始化topic */
      //methods
      this.POST_PROPERY_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.POST_PROPERY;
      // this.POST_EVENT = util.format(METHODS_TEMPLATE.POST_EVENT, eventName);
      this.POST_TAGS_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.POST_TAGS;
      this.DELETE_TAGS_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.DELETE_TAGS;
      this.GET_CONFIG_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.GET_CONFIG;
      this.ADD_TOPO_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.ADD_TOPO;
      this.DELETE_TOPO_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.DELETE_TOPO;
      this.GET_TOPO_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.GET_TOPO;
      this.SUBDEVICE_REGISTER_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.SUBDEVICE_REGISTER;
 
      //topic
      var _formatWithPKDN = function _formatWithPKDN(template) {
        return util.format(template, _this.productKey, _this.deviceName);
      };
      this.POST_PROPS_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.PROPERTY_POST_TOPIC);
      this.POST_PROPS_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.PROPERTY_POST_REPLY_TOPIC);
      this.ONSET_PROPS_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.ONSET_PROPS_TOPIC);
 
      // this.POST_EVENT_TOPIC = _formatWithPKDN(BROKER_TOPICS.EVENT_POST_TOPIC)
      // this.POST_EVENT_REPLY_TOPIC = _formatWithPKDN(BROKER_TOPICS.EVENT_POST_REPLY_TOPIC)
      this.SERVICE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SERVICE_TOPIC);
      this.TAG_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_TOPIC);
      this.TAG_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_REPLY_TOPIC);
      this.TAG_DELETE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_DELETE_TOPIC);
      this.TAG_DELETE_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_DELETE_REPLY_TOPIC);
      this.CONFIG_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_TOPIC);
      this.CONFIG_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_REPLY_TOPIC);
      this.CONFIG_SUBSCRIBE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_SUBSCRIBE_TOPIC);
      this.CONFIG_SUBSCRIBE_RESP_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_SUBSCRIBE_RESP_TOPIC);
      this.SHADOW_SUBSCRIBE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SHADOW_SUBSCRIBE_TOPIC);
      this.SHADOW_GET_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SHADOW_GET_TOPIC);
      this.SHADOW_POST_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SHADOW_POST_TOPIC);
      this.RRPC_REQ_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.RRPC_REQ_TOPIC);
 
      // gateway
      this.ADD_TOPO_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.ADD_TOPO_TOPIC);
      this.ADD_TOPO_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.ADD_TOPO_REPLY_TOPIC);
      this.DELETE_TOPO_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.DELETE_TOPO_TOPIC);
      this.DELETE_TOPO_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.DELETE_TOPO_REPLY_TOPIC);
      this.GET_TOPO_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.GET_TOPO_TOPIC);
      this.GET_TOPO_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.GET_TOPO_REPLY_TOPIC);
      this.LOGIN_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGIN_TOPIC);
      this.LOGIN_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGIN_REPLY_TOPIC);
      this.LOGOUT_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGOUT_TOPIC);
      this.LOGOUT_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGOUT_REPLY_TOPIC);
      this.SUBDEVICE_REGISTER_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SUBDEVICE_REGISTER_TOPIC);
      this.SUBDEVICE_REGISTER_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SUBDEVICE_REGISTER_REPLY_TOPIC);
    }
  }, {
    key: 'configchecking',
    value: function configchecking() {
      if (typeof this.productKey === 'undefined') {
        throw new Error('productKey should not be empty');
      }
      if (typeof this.deviceName === 'undefined') {
        throw new Error('deviceName should not be empty');
      }
      if (typeof this.deviceSecret === 'undefined') {
        throw new Error('deviceSecret should not be empty');
      }
    }
  }]);
 
  return Model;
}();
 
exports.default = Model;
 
 
module.exports = Model;