mm_os 4.2.6 → 4.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/README_EN.md +2 -2
  3. package/adapter/adapter.js +105 -52
  4. package/adapter/custom_persistence.js +32 -31
  5. package/adapter/mqtt.js +59 -79
  6. package/adapter/socket.js +188 -58
  7. package/adapter/web.js +92 -68
  8. package/adapter/websocket.js +43 -146
  9. package/com/api/drive.js +732 -708
  10. package/com/api/index.js +196 -198
  11. package/com/cmd/config.tpl.json +48 -122
  12. package/com/cmd/drive.js +176 -1548
  13. package/com/cmd/index.js +287 -1066
  14. package/com/cmd/job/config.json +66 -0
  15. package/com/cmd/job/index.js +241 -0
  16. package/com/cmd/job/test.js +188 -0
  17. package/com/cmd/script.tpl.js +12 -33
  18. package/com/db/drive.js +2206 -2019
  19. package/com/db/index.js +241 -242
  20. package/com/event/config.tpl.json +3 -1
  21. package/com/event/drive.js +3 -1
  22. package/com/event/index.js +73 -49
  23. package/com/event/script.tpl.js +1 -1
  24. package/com/mqtt/config.tpl.json +16 -8
  25. package/com/mqtt/drive.js +696 -676
  26. package/com/mqtt/index.js +1012 -822
  27. package/com/mqtt/index.test.js +503 -0
  28. package/com/mqtt/mm_mqtt.js +446 -420
  29. package/com/mqtt/script.tpl.js +3 -7
  30. package/com/nav/drive.js +7 -7
  31. package/com/nav/index.js +228 -231
  32. package/com/param/index.js +19 -17
  33. package/com/pendant/index.js +467 -441
  34. package/com/socket/drive.js +679 -616
  35. package/com/socket/index.js +94 -48
  36. package/com/sql/drive.js +1283 -1259
  37. package/com/sql/index.js +152 -150
  38. package/com/static/drive.js +1 -1
  39. package/com/static/index.js +232 -226
  40. package/com/task/drive.js +428 -405
  41. package/com/task/index.js +154 -148
  42. package/com/template/drive.js +1 -1
  43. package/com/template/index.js +141 -138
  44. package/com.js +87 -6
  45. package/common/middleware/web_after/index.js +4 -10
  46. package/common/middleware/web_base/index.js +1 -1
  47. package/common/middleware/web_cors/index.js +1 -1
  48. package/common/middleware/web_error/index.js +131 -119
  49. package/common/middleware/web_error/middleware.json +2 -1
  50. package/common/middleware/web_logger/index.js +1 -1
  51. package/common/middleware/web_main/index.js +2 -0
  52. package/common/middleware/web_static/index.js +2 -2
  53. package/common/middleware/web_waf/index.js +1 -1
  54. package/core/app/config.tpl.json +4 -4
  55. package/core/app/index.js +710 -534
  56. package/core/middleware/index.js +1 -9
  57. package/core/mod/config.tpl.json +1 -1
  58. package/core/model/config.tpl.json +1 -1
  59. package/core/plugin/config.tpl.json +15 -3
  60. package/core/plugin/index.js +31 -0
  61. package/core/pusher/index.js +158 -161
  62. package/core/scene/loop.js +1306 -1255
  63. package/core/store/index.js +1794 -1755
  64. package/core/store/sql.js +1488 -1464
  65. package/core/zone/bat/index.js +744 -728
  66. package/core/zone/config.tpl.json +3 -3
  67. package/core/zone/index.js +655 -616
  68. package/os.js +0 -4
  69. package/package.json +16 -16
  70. package/server.js +583 -427
  71. package/com/cmd/nlp.js +0 -525
  72. package/core/app/index copy.js +0 -611
  73. package/software.js +0 -194
  74. package/tcp.js +0 -279
package/com/mqtt/index.js CHANGED
@@ -1,822 +1,1012 @@
1
- const Mqtt_client = require('mqtt');
2
- const Manager = require('mm_machine').Manager;
3
- const Drive = require('./drive');
4
-
5
- /**
6
- * Mqtt通讯类
7
- * @augments {Manager}
8
- * @class
9
- */
10
- class Mqtt extends Manager {
11
- /**
12
- * 配置参数
13
- * @type {object}
14
- */
15
- static config = {
16
- /**
17
- * 名称
18
- * @type {string}
19
- */
20
- name: '',
21
- /**
22
- * 标题
23
- * @type {string}
24
- */
25
- title: 'Mqtt通讯类',
26
- /**
27
- * 描述
28
- * @type {string}
29
- */
30
- description: '这是Mqtt通讯类管理器',
31
- /**
32
- * 检索文件名
33
- * @type {string}
34
- */
35
- filename: 'mqtt.json',
36
- /**
37
- * 模板目录
38
- * @type {string}
39
- */
40
- tpl_dir: __dirname,
41
- /**
42
- * 基础目录
43
- * @type {string}
44
- */
45
- base_dir: '../common/mqtt'.fullname(__dirname),
46
- /**
47
- * 自定义目录,加载项目自定义资源
48
- * @type {string}
49
- */
50
- dir: './app'.fullname(),
51
- /**
52
- * 搜索模式 dir按目录搜索 | file按文件名搜索
53
- * @type {string}
54
- */
55
- search_way: 'file',
56
- /**
57
- * 是否懒加载
58
- * @type {boolean}
59
- */
60
- lazy_load: true,
61
- /**
62
- * 模式
63
- * 1.生产模式,改变文件不会重新加载
64
- * 2.热更新模式,改变配置文件会重新加载配置,不重新加载脚本
65
- * 3.热重载模式,改变配置文件都会加载配置和脚本
66
- * 4.重载模式,执行完后重新加载脚本,避免变量污染
67
- * 5.热更新+重载模式,改变配置文件重新加载配置和脚本,执行完后重新加载脚本
68
- * @type {number}
69
- */
70
- mode: 3,
71
- hostname: '127.0.0.1',
72
- port: '1883',
73
- protocol: 'mqtt',
74
- client_id: 'server',
75
- subscribe_qos: 2,
76
- publish_qos: 2,
77
- username: 'server',
78
- password: 'asd123',
79
- table: 'iot_device',
80
- clean: false,
81
- longtime: 15000,
82
- request_timeout: 3000,
83
- // 在线有效期时长判断 单位:毫秒,150000毫秒为2.5分钟
84
- online_expires: 150000,
85
- // 在线有效期检测间隔
86
- online_interval: 10000,
87
- // 连接超时
88
- connect_timeout: 30000,
89
- // maxInflight: 20,
90
- // 重连间隔
91
- reco_period: 6000 // 重连间隔1秒
92
- };
93
-
94
- /**
95
- * 构造函数
96
- * @param {object} config 配置参数
97
- * @param {object} parent 父级模块
98
- */
99
- constructor(config, parent) {
100
- super({ ...Mqtt.config, ...config }, parent);
101
- }
102
- }
103
-
104
- /**
105
- * 预置
106
- */
107
- Mqtt.prototype._preset = function () {
108
- this.dict = {};
109
- // 定时器
110
- this.timer = null;
111
- // mqtt客户端服务器
112
- this.client = null;
113
- /**
114
- * message queue
115
- */
116
- this.list_msg = [
117
- /*
118
- {
119
- // information ID
120
- id: "",
121
- // request method
122
- method: "",
123
- // message parameters
124
- params: {},
125
- // Callback
126
- func: function(res){}
127
- }
128
- */
129
- ];
130
-
131
- /**
132
- * 订阅集合 (主题 => 函数列表)
133
- */
134
- this.dict_subscribe = {};
135
-
136
- /**
137
- * method collection
138
- */
139
- var _this = this;
140
- this.methods = {
141
- /**
142
- * 获取所有方法
143
- * @returns {Array} 函数列表
144
- */
145
- getMethod: function () {
146
- return Object.keys(_this.methods);
147
- }
148
- };
149
-
150
- this.retry_times = 0;
151
- this.connecting = false;
152
- this._createClient();
153
- }
154
-
155
- /**
156
- * mqtt驱动类
157
- * @type {Drive}
158
- */
159
- Mqtt.prototype.Drive = Drive;
160
-
161
- /**
162
- * 主题匹配
163
- * @param {string} topic 接收到的主题
164
- * @param {string} top 匹配用的主题
165
- * @returns {boolean} 返回匹配结果,正确返回true,错误返回false
166
- */
167
- Mqtt.prototype.match = function (topic, top) {
168
- if (topic === top) {
169
- return true;
170
- }
171
- var str = '^' + top.replace('#', '.*').replace('+', '~~~').replace('~~~', '[a-zA-Z0-9_-]+').replace('$', '~~~')
172
- .replace('~~~', '\\$');
173
- var s = str.substring(str.length - 1, str.length);
174
- if (s !== '#') {
175
- str += '$';
176
- }
177
- var mh = new RegExp(str);
178
- return mh.test(topic);
179
- };
180
-
181
- /**
182
- * 初始化
183
- */
184
- Mqtt.prototype.updateAfter = async function () {
185
- var _this = this;
186
- let infos = this.getInfos();
187
- for (var i = 0; i < infos.length; i++) {
188
- var info = infos[i];
189
- if (info.state === 1) {
190
- let mod = this.getMod(info.name);
191
- if (mod) {
192
- mod.send = function (topic, msg, qos = 0, retain = false) {
193
- if (topic) {
194
- _this.send(topic, msg, qos, retain);
195
- }
196
- };
197
- await mod.do('init');
198
- var topics = mod.config.topic;
199
- if (topics) {
200
- for (var n = 0; n < topics.length; n++) {
201
- var tc = topics[n];
202
- var retain = mod.config.retain || false;
203
- var qos = mod.config.qos || 0;
204
- if (tc.indexOf('heartbeat') !== -1) {
205
- retain = false;
206
- qos = 0;
207
- }
208
- this.subscribe(tc, null, qos, retain);
209
- }
210
- }
211
- }
212
- }
213
- }
214
- };
215
-
216
- /**
217
- * 重新连接
218
- */
219
- Mqtt.prototype.reconnect = function () {
220
- // $.sleep(this.config.interval);
221
- // this.retryTimes += 1;
222
- // if (this.retryTimes > 5) {
223
- // try {
224
- // this.client.end();
225
- // this.init();
226
- // } catch (error) {
227
- // this.$message.error(error.toString());
228
- // }
229
- // }
230
- };
231
-
232
- /**
233
- * 初始化
234
- * @param {object} config 配置参数
235
- */
236
- Mqtt.prototype.init = function (config) {
237
- this.config = Object.assign(this.config, config);
238
- this.retry_times = 0;
239
- this.connecting = false;
240
- };
241
-
242
- /**
243
- * 运行Mqtt
244
- * @returns {Promise} 连接结果
245
- */
246
- Mqtt.prototype.start = function () {
247
- setTimeout(() => {
248
- this.startTimer();
249
- }, 2000);
250
-
251
- this.connecting = true;
252
-
253
- try {
254
- this._createClient();
255
-
256
- if (this.client && this.client.on) {
257
- return this._setupClientEvents();
258
- }
259
- } catch (error) {
260
- this.connecting = false;
261
- return this._rejectPromise(error);
262
- }
263
-
264
- return this._rejectPromise();
265
- };
266
-
267
- /**
268
- * 创建客户端
269
- * @private
270
- */
271
- Mqtt.prototype._createClient = function () {
272
- var cg = { ...this.config };
273
- cg.clientId = cg.client_id;
274
- if (cg.host) {
275
- delete cg.hostname;
276
- delete cg.port;
277
- this.client = Mqtt_client.connect(cg.host, cg);
278
- } else {
279
- this.client = Mqtt_client.connect(cg);
280
- }
281
- };
282
-
283
- /**
284
- * 设置客户端事件
285
- * @returns {Promise} 连接结果
286
- * @private
287
- */
288
- Mqtt.prototype._setupClientEvents = function () {
289
- return new Promise((resolve, reject) => {
290
- this.client.on('connect', (packet, err) => {
291
- this.connecting = false;
292
- if (err) {
293
- resolve(null);
294
- reject(err);
295
- } else {
296
- this.client.on('message', async (topic, message) => {
297
- await this.receive(topic, message.toString());
298
- });
299
- resolve(packet);
300
- }
301
- });
302
- this.client.on('reconnect', () => {
303
- this.reconnect();
304
- });
305
- this.client.on('error', (error) => {
306
- console.error('Connection failed', error);
307
- });
308
- });
309
- };
310
-
311
- /**
312
- * 创建被拒绝的Promise
313
- * @param {Error} error 错误对象
314
- * @returns {Promise} 被拒绝的Promise
315
- * @private
316
- */
317
- Mqtt.prototype._rejectPromise = function (error) {
318
- return new Promise((resolve, reject) => {
319
- resolve(null);
320
- reject(error);
321
- });
322
- };
323
-
324
- /**
325
- * 监听事件
326
- * @param {string} topic 事件名称
327
- * @param {Function} func 回调函数
328
- */
329
- Mqtt.prototype.on = function (topic, func) {
330
- this.client.on(topic, func);
331
- };
332
-
333
- /**
334
- * 接收消息
335
- * @param {string} topic 订阅板块
336
- * @param {object} msg 消息主体
337
- */
338
- Mqtt.prototype.message = async function (topic, msg) {
339
- if (this.dict_subscribe[topic]) {
340
- var list = this.dict_subscribe[topic];
341
- try {
342
- for (var key in list) {
343
- list[key](msg);
344
- }
345
- } catch (err) {
346
- console.error(err);
347
- }
348
- }
349
- };
350
-
351
- /**
352
- * 接收消息
353
- * @param {string} push_topic 推送过来的主题
354
- * @param {object} message 消息主体
355
- * @returns {object} 解析后的消息主体
356
- */
357
- Mqtt.prototype.receive = async function (push_topic, message) {
358
- var msg = this._parseMessage(message, push_topic);
359
- if (msg === null) {
360
- return;
361
- }
362
-
363
- // 处理消息回复
364
- this._handleResponse(msg);
365
-
366
- var ret = await this._processTopics(push_topic, msg);
367
- try {
368
- await this.message(ret.topic, msg);
369
- } catch (error) {
370
- this.log('error', 'mqtt处理程序错误', error);
371
- return;
372
- }
373
- return ret.result;
374
- };
375
-
376
- /**
377
- * 解析消息
378
- * @param {object} message 消息主体
379
- * @param {string} push_topic 推送过来的主题
380
- * @returns {object|null} 解析后的消息
381
- * @private
382
- */
383
- Mqtt.prototype._parseMessage = function (message, push_topic) {
384
- var msg = {};
385
- if (message && (message.indexOf('[') === 0 || message.indexOf('{') === 0)) {
386
- try {
387
- msg = JSON.parse(message);
388
- } catch (error) {
389
- this.log('error', '消息结构体不对', push_topic, error);
390
- return null;
391
- }
392
- }
393
- return msg;
394
- };
395
-
396
- /**
397
- * 处理主题
398
- * @param {string} push_topic 推送过来的主题
399
- * @param {object} msg 消息主体
400
- * @returns {object} 处理结果和主题
401
- * @private
402
- */
403
- Mqtt.prototype._processTopics = async function (push_topic, msg) {
404
- var ret;
405
- var topic;
406
- var mods = this.getMods();
407
- for (var k in mods) {
408
- var o = mods[k];
409
- if (o.config.state !== 1) {
410
- continue;
411
- }
412
- var topics = o.config.topic;
413
- if (!topics) {
414
- continue;
415
- }
416
- for (var n = 0; n < topics.length; n++) {
417
- topic = topics[n];
418
- if (this.match(push_topic, topic)) {
419
- ret = await o.call('handle', push_topic, msg, topic, n);
420
- }
421
- }
422
- }
423
- return { result: ret, topic };
424
- };
425
-
426
- /**
427
- * 订阅主题
428
- * @param {string} topic 主题
429
- * @param {Function} func 回调函数
430
- * @param {number} qos 推送方式 0
431
- * @param {boolean} retain 保持
432
- * @returns {string} 主键
433
- */
434
- Mqtt.prototype.subscribe = function (topic, func, qos = null, retain = false) {
435
- if (!this.client) {
436
- return '';
437
- }
438
- this.client.subscribe(topic, {
439
- // 订阅消息方式,0为保留 , 1为确认收到1次
440
- qos: qos || this.config.subscribe_qos || 0,
441
- retain
442
- });
443
- if (func) {
444
- if (!this.dict_subscribe[topic]) {
445
- this.dict_subscribe[topic] = {};
446
- }
447
- var key = this.key_num + 1;
448
- this.dict_subscribe[topic][key] = func;
449
- return key;
450
- }
451
- return '';
452
- };
453
-
454
- /**
455
- * 取消订阅
456
- * @param {string} topic 主题
457
- * @param {string} key 主键
458
- */
459
- Mqtt.prototype.unsubscribe = function (topic, key) {
460
- this.client.unsubscribe(topic);
461
- if (this.dict_subscribe[topic]) {
462
- delete this.dict_subscribe[topic][key];
463
- }
464
- };
465
-
466
- /**
467
- * 结束客户端
468
- */
469
- Mqtt.prototype.end = function () {
470
- if (this.client) {
471
- this.client.end();
472
- }
473
- if (this.timer) {
474
- clearInterval(this.timer);
475
- this.timer = null;
476
- }
477
- };
478
-
479
- /**
480
- * 发布主题
481
- * @param {string} topic 主题
482
- * @param {object} message 消息对象
483
- * @param {number} qos 推送方式 0
484
- * @param {boolean} retain 保持
485
- */
486
- Mqtt.prototype.publish = function (topic, message, qos = null, retain = false) {
487
- this.client.publish(topic, message, {
488
- qos: qos || this.config.publish_qos || 0,
489
- retain
490
- });
491
- };
492
-
493
- /**
494
- * 主题推送
495
- * @param {string} topic 主题
496
- * @param {string} msg_obj 消息主体
497
- * @param {number} qos 推送方式 0
498
- * @param {boolean} retain 保持
499
- */
500
- Mqtt.prototype.send = function (topic, msg_obj, qos = null, retain = false) {
501
- this.publish(topic, JSON.stringify(msg_obj), qos, retain);
502
- };
503
-
504
- /**
505
- * 生成ID
506
- * @param {string} clientId 客户端ID
507
- * @returns {string} ID
508
- */
509
- Mqtt.prototype.genId = function (clientId) {
510
- return clientId + '_' + Date.parse(new Date());
511
- };
512
-
513
- /**
514
- * 请求
515
- * @param {string} topic 主题
516
- * @param {string} method 请求方法
517
- * @param {object} params 请求参数
518
- * @param {Function} func 回调函数
519
- * @param {number} timeout 超时时间(毫秒)
520
- */
521
- Mqtt.prototype.req = function (topic, method, params, func, timeout = 0) {
522
- var data = {
523
- id: this.genId(this.client.options.clientId),
524
- method,
525
- params
526
- };
527
-
528
- if (func) {
529
- data.func = func;
530
- data.timestamp = Date.now();
531
- data.timeout = timeout || this.config.request_timeout || 3000;
532
- this.list_msg.push(data);
533
-
534
- // 设置超时移除定时器
535
- var _this = this;
536
- data.timer = setTimeout(() => {
537
- _this._delMsgById(data.id);
538
- }, data.timeout);
539
- }
540
- this.send(topic, data);
541
- };
542
-
543
- /**
544
- * 同步请求 - 可及时取回消息
545
- * @param {string} topic 订阅板块
546
- * @param {string} method 请求方法
547
- * @param {object} params 传递参数
548
- * @param {number} timeout 超时时间 0为默认值 10000ms
549
- * @returns {object} 返回响应结果
550
- */
551
- Mqtt.prototype.reqAsync = function (topic, method, params, timeout = 0) {
552
- var _this = this;
553
- return new Promise((resolve, reject) => {
554
- _this.req(topic, method, params, (res) => {
555
- resolve(res);
556
- }, timeout);
557
- });
558
- };
559
-
560
- /**
561
- * 根据ID移除消息
562
- * @param {string} msg_id 消息ID
563
- * @private
564
- */
565
- Mqtt.prototype._delMsgById = function (msg_id) {
566
- for (var i = 0; i < this.list_msg.length; i++) {
567
- if (this.list_msg[i].id === msg_id) {
568
- // 清除定时器
569
- if (this.list_msg[i].timer) {
570
- clearTimeout(this.list_msg[i].timer);
571
- }
572
- this.list_msg.splice(i, 1);
573
- break;
574
- }
575
- }
576
- };
577
-
578
- /**
579
- * 处理消息回复
580
- * @param {object} msg 回复消息
581
- * @private
582
- */
583
- Mqtt.prototype._handleResponse = function (msg) {
584
- if (!msg || !msg.id) {
585
- return;
586
- }
587
-
588
- for (var i = 0; i < this.list_msg.length; i++) {
589
- let o = this.list_msg[i];
590
- if (o.id === msg.id && o.func) {
591
- try {
592
- // 执行回调函数
593
- o.func(msg);
594
- } catch (error) {
595
- console.error('MQTT回调函数执行错误:', error);
596
- }
597
-
598
- // 从列表中移除已处理的消息
599
- this._delMsgById(o.id);
600
- break;
601
- }
602
- }
603
- };
604
-
605
- /**
606
- * 保存在线到数据库
607
- * @param {Array} arr 客户端ID数组
608
- * @param {number} online 在线情况 0为不在线,1为在线
609
- */
610
- Mqtt.prototype.saveOnline = async function (arr, online = 1) {
611
- if (!arr || !arr.length) {
612
- return;
613
- }
614
- var body = {
615
- online
616
- };
617
- var db = $.admin.sql('sys').db();
618
- db.table = this.config.table || 'iot_device';
619
- db.size = 0;
620
- var query = {};
621
- query.clientid_has = arr.join(',');
622
- await db.set(query, body);
623
- };
624
-
625
- /**
626
- * 获取所有设备
627
- * @returns {Array} 设备列表
628
- */
629
- Mqtt.prototype.getClients = async function () {
630
- var db = $.admin.sql('sys').db();
631
- db.table = this.config.table || 'iot_device';
632
- db.size = 0;
633
- return await db.get({}, '', 'clientid, online');
634
- };
635
-
636
- /**
637
- * 更新在线设备
638
- */
639
- Mqtt.prototype.updateOnline = async function () {
640
- var now = new Date().getTime();
641
- var online_expires = this.config.online_expires; // 180
642
-
643
- // 获取所有客户端
644
- var drives = await this.getClients();
645
- var { list_online, list_offline } = this._processDeviceStatus(drives, now, online_expires);
646
-
647
- // 处理未出现的设备
648
- // this._processUnseenDevices(drives, list_offline, list_has);
649
-
650
- // 批量更新设备状态
651
- await this._updateDeviceStatus(list_offline, list_online);
652
- };
653
-
654
- /**
655
- * 处理设备状态
656
- * @param {Array} drives 设备列表
657
- * @param {number} now 当前时间戳
658
- * @param {number} online_expires 在线过期时间
659
- * @returns {object} 在线和离线设备列表
660
- * @private
661
- */
662
- Mqtt.prototype._processDeviceStatus = function (drives, now, online_expires) {
663
- var list_online = [];
664
- var list_offline = [];
665
- var list_has = [];
666
-
667
- var mods = this.getMods();
668
- for (var k in mods) {
669
- var o = mods[k];
670
- var dict = o.drives;
671
- for (var clientid in dict) {
672
- list_has.push(clientid);
673
- var drive = drives.getObj({ clientid });
674
- var o = dict[clientid];
675
-
676
- if (o.online === 1) {
677
- this._onlineDevice(
678
- o, drive, clientid, now, online_expires,
679
- list_online, list_offline, dict
680
- );
681
- } else {
682
- this._offlineDevice(drive, clientid, list_offline);
683
- }
684
- }
685
- }
686
-
687
- return { list_online, list_offline, list_has };
688
- };
689
-
690
- /**
691
- * 处理在线设备
692
- * @param {object} device 设备对象
693
- * @param {object} drive 数据库中的设备信息
694
- * @param {string} clientid 设备ID
695
- * @param {number} now 当前时间戳
696
- * @param {number} online_expires 在线过期时间
697
- * @param {Array} list_online 在线设备列表
698
- * @param {Array} list_offline 离线设备列表
699
- * @param {object} dict 设备字典
700
- * @private
701
- */
702
- /* eslint-disable no-param-reassign */
703
- Mqtt.prototype._onlineDevice = function (
704
- device, drive, clientid, now, online_expires,
705
- list_online, list_offline, dict
706
- ) {
707
- if (device.time_last) {
708
- var cha = now - device.time_last;
709
- if (cha > online_expires) {
710
- if (drive && drive.online) {
711
- list_offline.push(clientid);
712
- }
713
- // 这里需要修改设备状态,但由于参数修改限制,我们直接修改字典
714
- // 注意:这里仍然会修改外部对象,但这是业务逻辑需要
715
- device.online = 0;
716
- delete dict[clientid];
717
- } else {
718
- if (drive && !drive.online) {
719
- list_online.push(clientid);
720
- }
721
- }
722
- }
723
- };
724
- /* eslint-enable no-param-reassign */
725
-
726
- /**
727
- * 处理离线设备
728
- * @param {object} drive 数据库中的设备信息
729
- * @param {string} clientid 设备ID
730
- * @param {Array} list_offline 离线设备列表
731
- * @private
732
- */
733
- Mqtt.prototype._offlineDevice = function (drive, clientid, list_offline) {
734
- if (drive && drive.online) {
735
- list_offline.push(clientid);
736
- }
737
- };
738
-
739
- /**
740
- * 处理未出现的设备
741
- * @param {Array} drives 设备列表
742
- * @param {Array} list_offline 离线设备列表
743
- * @param {Array} list_has 已处理的设备ID列表
744
- * @private
745
- */
746
- Mqtt.prototype._processUnseenDevices = function (drives, list_offline, list_has) {
747
- // 处理未出现的设备
748
- for (var i = 0; i < drives.length; i++) {
749
- var { clientid, online } = drives[i];
750
- if (online && list_has.indexOf(clientid) === -1) {
751
- list_offline.push(clientid);
752
- }
753
- }
754
- };
755
-
756
- /**
757
- * 更新设备状态
758
- * @param {Array} list_offline 离线设备列表
759
- * @param {Array} list_online 在线设备列表
760
- * @private
761
- */
762
- Mqtt.prototype._updateDeviceStatus = async function (list_offline, list_online) {
763
- // 先将设备离线
764
- var list_off = list_offline.to2D(30);
765
- for (var i = 0; i < list_off.length; i++) {
766
- await this.saveOnline(list_off[i], 0);
767
- }
768
-
769
- // 再将设备在线
770
- var list_on = list_online.to2D(30);
771
- for (var i = 0; i < list_on.length; i++) {
772
- await this.saveOnline(list_on[i], 1);
773
- }
774
- };
775
-
776
- /**
777
- * 开始计时器
778
- */
779
- Mqtt.prototype.startTimer = function () {
780
- if (!this.timer) {
781
- this.timer = setInterval(() => {
782
- try {
783
- this.updateOnline();
784
- } catch (err) {
785
- console.error('更新在线设备失败', err);
786
- }
787
- }, this.config.online_interval);
788
- }
789
- };
790
-
791
- exports.Mqtt = Mqtt;
792
-
793
-
794
- /**
795
- * 创建全局管理器
796
- */
797
- if (!$.pool.mqtt) {
798
- $.pool.mqtt = {};
799
- }
800
-
801
- function mqttAdmin(scope, title) {
802
- var sc = scope || $.val.scope + '';
803
- var obj = $.pool.mqtt[sc];
804
- if (!obj) {
805
- $.pool.mqtt[sc] = new Mqtt({
806
- name: sc,
807
- title: title
808
- });
809
- obj = $.pool.mqtt[sc];
810
- }
811
- return obj;
812
- }
813
-
814
- /**
815
- * mqtt管理器, 用于管理插件
816
- * @param {string} scope 作用域
817
- * @param {string} title 标题
818
- * @returns {object} 返回一个缓存类
819
- */
820
- if ($.admin) {
821
- $.admin.mqtt = mqttAdmin;
822
- }
1
+ const Mqtt_client = require("mqtt");
2
+ const Manager = require("mm_machine").Manager;
3
+ const Drive = require("./drive");
4
+
5
+ /**
6
+ * Mqtt通讯类
7
+ * @augments {Manager}
8
+ * @class
9
+ */
10
+ class Mqtt extends Manager {
11
+ /**
12
+ * 配置参数
13
+ * @type {object}
14
+ */
15
+ static config = {
16
+ /**
17
+ * 名称
18
+ * @type {string}
19
+ */
20
+ name: "",
21
+ /**
22
+ * 标题
23
+ * @type {string}
24
+ */
25
+ title: "Mqtt通讯类",
26
+ /**
27
+ * 描述
28
+ * @type {string}
29
+ */
30
+ description: "这是Mqtt通讯类管理器",
31
+ /**
32
+ * 检索文件名
33
+ * @type {string}
34
+ */
35
+ filename: "mqtt.json",
36
+ /**
37
+ * 模板目录
38
+ * @type {string}
39
+ */
40
+ tpl_dir: __dirname,
41
+ /**
42
+ * 基础目录
43
+ * @type {string}
44
+ */
45
+ base_dir: "../common/mqtt".fullname(__dirname),
46
+ /**
47
+ * 自定义目录,加载项目自定义资源
48
+ * @type {string}
49
+ */
50
+ dir: "./app".fullname(),
51
+ /**
52
+ * 搜索模式 dir按目录搜索 | file按文件名搜索
53
+ * @type {string}
54
+ */
55
+ search_way: "file",
56
+ /**
57
+ * 是否懒加载
58
+ * @type {boolean}
59
+ */
60
+ lazy_load: false,
61
+ /**
62
+ * 模式
63
+ * 1.生产模式,改变文件不会重新加载
64
+ * 2.热更新模式,改变配置文件会重新加载配置,不重新加载脚本
65
+ * 3.热重载模式,改变配置文件都会加载配置和脚本
66
+ * 4.重载模式,执行完后重新加载脚本,避免变量污染
67
+ * 5.热更新+重载模式,改变配置文件重新加载配置和脚本,执行完后重新加载脚本
68
+ * @type {number}
69
+ */
70
+ mode: process.env.NODE_ENV === "production" ? 1 : 3,
71
+ host: "",
72
+ hostname: "127.0.0.1",
73
+ port: "1883",
74
+ protocol: "mqtt",
75
+ // MQTT协议版本: 4表示MQTT 3.1.1(兼容aedes v1.x)
76
+ protocol_version: 4,
77
+ clientid: "server",
78
+ subscribe_qos: 2,
79
+ publish_qos: 2,
80
+ username: "server",
81
+ password: process.env.MQTT_PASSWORD || "",
82
+ table: "iot_device",
83
+ clean: false,
84
+ longtime: 15000,
85
+ request_timeout: 3000,
86
+ // 在线有效期时长判断 单位:毫秒,150000毫秒为2.5分钟
87
+ online_expires: 150000,
88
+ // 在线有效期检测间隔
89
+ online_interval: 10000,
90
+ // 连接超时
91
+ connect_timeout: 30000,
92
+ // maxInflight: 20,
93
+ // 重连间隔
94
+ reconnet_period: 6000, // 重连间隔1秒
95
+ };
96
+
97
+ /**
98
+ * 构造函数
99
+ * @param {object} config 配置参数
100
+ * @param {object} parent 父级模块
101
+ */
102
+ constructor(config, parent) {
103
+ super({ ...Mqtt.config, ...config }, parent);
104
+ this.retryTimes = 0;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 预置
110
+ */
111
+ Mqtt.prototype._preset = function () {
112
+ this.dict = {};
113
+ // 缓存缺失记录, 用于宽容期判断幽灵在线
114
+ this.dict_lost = {};
115
+ // 定时器
116
+ this.timer = null;
117
+ // 关闭旧客户端
118
+ if (this.client && this.client.end) {
119
+ try {
120
+ this.client.end(true);
121
+ } catch {
122
+ // ignore close error
123
+ }
124
+ }
125
+ // mqtt客户端服务器
126
+ this.client = null;
127
+ /**
128
+ * message queue
129
+ */
130
+ this.list_msg = [
131
+ /*
132
+ {
133
+ // information ID
134
+ id: "",
135
+ // request method
136
+ method: "",
137
+ // message parameters
138
+ params: {},
139
+ // Callback
140
+ func: function(res){}
141
+ }
142
+ */
143
+ ];
144
+
145
+ /**
146
+ * 消息ID索引 (id => message对象), 用于O(1)查找
147
+ */
148
+ this.dict_msg = {};
149
+
150
+ /**
151
+ * 订阅集合 (主题 => 函数列表)
152
+ */
153
+ this.dict_subscribe = {};
154
+
155
+ /**
156
+ * 正则表达式缓存 (模式字符串 => RegExp对象)
157
+ */
158
+ this._regex_cache = {};
159
+
160
+ /**
161
+ * method collection
162
+ */
163
+ var _this = this;
164
+ this.methods = {
165
+ /**
166
+ * 获取所有方法
167
+ * @returns {Array} 函数列表
168
+ */
169
+ getMethod: function () {
170
+ return Object.keys(_this.methods);
171
+ },
172
+ };
173
+
174
+ this.retry_times = 0;
175
+ this.connecting = false;
176
+ };
177
+
178
+ /**
179
+ * mqtt驱动类
180
+ * @type {Drive}
181
+ */
182
+ Mqtt.prototype.Drive = Drive;
183
+
184
+ /**
185
+ * 主题匹配
186
+ * @param {string} topic 接收到的主题
187
+ * @param {string} top 匹配用的主题
188
+ * @returns {boolean} 返回匹配结果,正确返回true,错误返回false
189
+ */
190
+ Mqtt.prototype.match = function (topic, top) {
191
+ if (topic === top) {
192
+ return true;
193
+ }
194
+ var regex = this._regex_cache[top];
195
+ if (!regex) {
196
+ // 限制正则缓存大小,避免无限增长
197
+ if (Object.keys(this._regex_cache).length > 500) {
198
+ this._regex_cache = {};
199
+ }
200
+ var str =
201
+ "^" +
202
+ top
203
+ .replace("#", ".*")
204
+ .replace("+", "~~~")
205
+ .replace("~~~", "[a-zA-Z0-9_-]+")
206
+ .replace("$", "~~~")
207
+ .replace("~~~", "\\$");
208
+ var s = str.substring(str.length - 1, str.length);
209
+ if (s !== "#") {
210
+ str += "$";
211
+ }
212
+ regex = new RegExp(str);
213
+ this._regex_cache[top] = regex;
214
+ }
215
+ return regex.test(topic);
216
+ };
217
+
218
+ /**
219
+ * 初始化
220
+ */
221
+ Mqtt.prototype.updateAfter = async function () {
222
+ var _this = this;
223
+ var infos = this.getInfos();
224
+ var promises = [];
225
+
226
+ for (var i = 0; i < infos.length; i++) {
227
+ var info = infos[i];
228
+ if (info.state === 1) {
229
+ var mod = this.getMod(info.name);
230
+ if (mod) {
231
+ mod.send = function (topic, msg, qos = 0, retain = false) {
232
+ if (topic) {
233
+ _this.send(topic, msg, qos, retain);
234
+ }
235
+ };
236
+ promises.push(
237
+ mod.do("init").catch((err) => {
238
+ console.error("MQTT mod初始化失败:", mod.config.name, err);
239
+ }),
240
+ );
241
+ }
242
+ }
243
+ }
244
+
245
+ await Promise.allSettled(promises);
246
+ };
247
+
248
+ /**
249
+ * 订阅所有已启用mod的主题
250
+ * 需在客户端连接成功后调用
251
+ * @private
252
+ */
253
+ Mqtt.prototype._subscribeTopics = function () {
254
+ var mods = this.getMods();
255
+ for (var k in mods) {
256
+ var o = mods[k];
257
+ if (o.config.state !== 1) {
258
+ continue;
259
+ }
260
+ var topics = o.config.topic;
261
+ if (!topics) {
262
+ continue;
263
+ }
264
+ for (var n = 0; n < topics.length; n++) {
265
+ var tc = topics[n];
266
+ var retain = o.config.retain || false;
267
+ var qos = o.config.qos || 0;
268
+ if (tc.indexOf("heartbeat") !== -1) {
269
+ retain = false;
270
+ qos = 0;
271
+ }
272
+ this.subscribe(tc, null, qos, retain);
273
+ }
274
+ }
275
+ };
276
+
277
+ /**
278
+ * 重新连接
279
+ */
280
+ Mqtt.prototype.reconnect = async function () {
281
+ await $.sleep(this.config.reconnet_period);
282
+ this.retryTimes += 1;
283
+ if (this.retryTimes > 5) {
284
+ try {
285
+ // 保存当前订阅状态
286
+ var saved_subs = this.dict_subscribe;
287
+ this.dict_subscribe = {};
288
+ this.client.end();
289
+ this.client.removeAllListeners();
290
+ this.client = null;
291
+ // 重新初始化并启动
292
+ this.init();
293
+ await this.start();
294
+ // 恢复订阅
295
+ for (var k in saved_subs) {
296
+ var o = saved_subs[k];
297
+ var topics = o.topics || [];
298
+ for (var n = 0; n < topics.length; n++) {
299
+ var tc = topics[n];
300
+ this.subscribe(tc, null, o.config.qos || 0, o.config.retain || false);
301
+ }
302
+ }
303
+ } catch (error) {
304
+ this.log("error", error.toString());
305
+ }
306
+ }
307
+ };
308
+
309
+ /**
310
+ * 运行Mqtt
311
+ * @returns {Promise} 连接结果
312
+ */
313
+ Mqtt.prototype.start = async function () {
314
+ this.connecting = true;
315
+
316
+ try {
317
+ await this._createClient();
318
+
319
+ if (this.client && this.client.on) {
320
+ return await this._setupClientEvents();
321
+ }
322
+ } catch (error) {
323
+ this.connecting = false;
324
+ return await this._rejectPromise(error);
325
+ }
326
+
327
+ return await this._rejectPromise();
328
+ };
329
+
330
+ /**
331
+ * 创建客户端
332
+ * @private
333
+ */
334
+ Mqtt.prototype._createClient = async function () {
335
+ var cg = { ...this.config };
336
+ cg.clientId = cg.clientid;
337
+ if (cg.host) {
338
+ var broker_url = cg.host;
339
+ delete cg.hostname;
340
+ delete cg.port;
341
+ delete cg.host;
342
+ this.client = Mqtt_client.connect(broker_url, cg);
343
+ } else {
344
+ delete cg.host;
345
+ this.client = Mqtt_client.connect(cg);
346
+ }
347
+ };
348
+
349
+ /**
350
+ * 设置客户端事件
351
+ * @returns {Promise} 连接结果
352
+ * @private
353
+ */
354
+ Mqtt.prototype._setupClientEvents = function () {
355
+ var _this = this;
356
+ var timeout_ms = _this.config.connect_timeout || 30000;
357
+ return new Promise((resolve, reject) => {
358
+ var timeout_timer = setTimeout(() => {
359
+ _this.connecting = false;
360
+ reject(new Error("MQTT连接超时"));
361
+ }, timeout_ms);
362
+
363
+ _this.client.on("connect", (connack) => {
364
+ clearTimeout(timeout_timer);
365
+ _this.connecting = false;
366
+ // 避免重连时重复绑定message事件
367
+ _this.client.removeAllListeners("message");
368
+ _this.client.on("message", (topic, message) => {
369
+ _this.receive(topic, message.toString()).catch((err) => {
370
+ console.error("MQTT消息处理错误:", err);
371
+ });
372
+ });
373
+ // 连接成功后订阅所有已启用mod的主题
374
+ _this._subscribeTopics();
375
+ // 启动在线状态定时器
376
+ _this.startTimer();
377
+ resolve(connack);
378
+ });
379
+ _this.client.on("error", (error) => {
380
+ clearTimeout(timeout_timer);
381
+ _this.connecting = false;
382
+ _this.log("error", "连接失败", error);
383
+ reject(error);
384
+ });
385
+ });
386
+ };
387
+
388
+ /**
389
+ * 创建被拒绝的Promise
390
+ * @param {Error} error 错误对象
391
+ * @returns {Promise} 被拒绝的Promise
392
+ * @private
393
+ */
394
+ Mqtt.prototype._rejectPromise = function (error) {
395
+ return new Promise((resolve, reject) => {
396
+ if (error) {
397
+ reject(error);
398
+ } else {
399
+ reject(new Error("MQTT客户端连接失败"));
400
+ }
401
+ });
402
+ };
403
+
404
+ /**
405
+ * 监听事件
406
+ * @param {string} topic 事件名称
407
+ * @param {Function} func 回调函数
408
+ * @returns {object} 返回当前实例
409
+ */
410
+ Mqtt.prototype.on = function (topic, func) {
411
+ if (!this.client) {
412
+ return this;
413
+ }
414
+ this.client.on(topic, func);
415
+ return this;
416
+ };
417
+
418
+ /**
419
+ * 接收消息
420
+ * @param {string} topic 订阅板块
421
+ * @param {object} msg 消息主体
422
+ */
423
+ Mqtt.prototype.message = async function (topic, msg) {
424
+ if (this.dict_subscribe[topic]) {
425
+ var list = this.dict_subscribe[topic];
426
+ try {
427
+ for (var key in list) {
428
+ list[key](msg);
429
+ }
430
+ } catch (err) {
431
+ console.error(err);
432
+ }
433
+ }
434
+ };
435
+
436
+ /**
437
+ * 接收消息
438
+ * @param {string} push_topic 推送过来的主题
439
+ * @param {object} message 消息主体
440
+ * @returns {object} 解析后的消息主体
441
+ */
442
+ Mqtt.prototype.receive = async function (push_topic, message) {
443
+ var msg = this._parseMessage(message, push_topic);
444
+ if (msg === null) {
445
+ return;
446
+ }
447
+
448
+ // 处理消息回复
449
+ this._handleResponse(msg);
450
+
451
+ var ret = await this._processTopics(push_topic, msg);
452
+ try {
453
+ await this.message(ret.topic, msg);
454
+ } catch (error) {
455
+ this.log("error", "mqtt处理程序错误", error);
456
+ return;
457
+ }
458
+ return ret.result;
459
+ };
460
+
461
+ /**
462
+ * 解析消息
463
+ * @param {object} message 消息主体
464
+ * @param {string} push_topic 推送过来的主题
465
+ * @returns {object|null} 解析后的消息
466
+ * @private
467
+ */
468
+ Mqtt.prototype._parseMessage = function (message, push_topic) {
469
+ var msg = {};
470
+ if (message && (message.indexOf("[") === 0 || message.indexOf("{") === 0)) {
471
+ try {
472
+ msg = JSON.parse(message);
473
+ } catch (error) {
474
+ this.log("error", "消息结构体不对", push_topic, error);
475
+ return null;
476
+ }
477
+ }
478
+ return msg;
479
+ };
480
+
481
+ /**
482
+ * 处理主题
483
+ * @param {string} push_topic 推送过来的主题
484
+ * @param {object} msg 消息主体
485
+ * @returns {object} 处理结果和主题
486
+ * @private
487
+ */
488
+ Mqtt.prototype._processTopics = async function (push_topic, msg) {
489
+ var ret;
490
+ var collected = this._collectTopicPromises(push_topic, msg);
491
+ var promises = collected.promises;
492
+ var topic = collected.topic;
493
+
494
+ if (promises.length > 0) {
495
+ var results = await Promise.allSettled(promises);
496
+ // 取最后一个成功的结果作为返回值 (保持向后兼容)
497
+ for (var i = results.length - 1; i >= 0; i--) {
498
+ if (
499
+ results[i].status === "fulfilled" &&
500
+ results[i].value !== undefined &&
501
+ results[i].value !== null
502
+ ) {
503
+ ret = results[i].value;
504
+ break;
505
+ }
506
+ }
507
+ }
508
+
509
+ return { result: ret, topic };
510
+ };
511
+
512
+ /**
513
+ * 收集匹配主题的handler Promise
514
+ * @param {string} push_topic 推送过来的主题
515
+ * @param {object} msg 消息主体
516
+ * @returns {object} {promises: Array, topic: string} Promise数组和最后匹配的主题
517
+ * @private
518
+ */
519
+ Mqtt.prototype._collectTopicPromises = function (push_topic, msg) {
520
+ var promises = [];
521
+ var topic = "";
522
+ var mods = this.getMods();
523
+
524
+ for (var k in mods) {
525
+ var o = mods[k];
526
+ if (o.config.state !== 1) {
527
+ continue;
528
+ }
529
+ var topics = o.config.topic;
530
+ if (!topics) {
531
+ continue;
532
+ }
533
+ for (var n = 0; n < topics.length; n++) {
534
+ topic = topics[n];
535
+ if (this.match(push_topic, topic)) {
536
+ promises.push(
537
+ o.call("handle", push_topic, msg, topic, n).catch((err) => {
538
+ console.error("MQTT handler执行错误:", err);
539
+ }),
540
+ );
541
+ }
542
+ }
543
+ }
544
+
545
+ return { promises, topic };
546
+ };
547
+
548
+ /**
549
+ * 订阅主题
550
+ * @param {string} topic 主题
551
+ * @param {Function} func 回调函数
552
+ * @param {number} qos 推送方式 0
553
+ * @param {boolean} retain 保持
554
+ * @returns {string} 主键
555
+ */
556
+ Mqtt.prototype.subscribe = function (topic, func, qos = null, retain = false) {
557
+ if (!this.client) {
558
+ return "";
559
+ }
560
+ this.client.subscribe(topic, {
561
+ // 订阅消息方式,0为保留 , 1为确认收到1次
562
+ qos: qos || this.config.subscribe_qos || 0,
563
+ retain,
564
+ });
565
+ if (func) {
566
+ if (!this.dict_subscribe[topic]) {
567
+ this.dict_subscribe[topic] = {};
568
+ }
569
+ var key = this.key_num + 1;
570
+ this.dict_subscribe[topic][key] = func;
571
+ return key;
572
+ }
573
+ return "";
574
+ };
575
+
576
+ /**
577
+ * 取消订阅
578
+ * @param {string} topic 主题
579
+ * @param {string} key 主键
580
+ */
581
+ Mqtt.prototype.unsubscribe = function (topic, key) {
582
+ this.client.unsubscribe(topic);
583
+ if (this.dict_subscribe[topic]) {
584
+ delete this.dict_subscribe[topic][key];
585
+ }
586
+ };
587
+
588
+ /**
589
+ * 结束客户端
590
+ */
591
+ Mqtt.prototype.end = function () {
592
+ if (this.client) {
593
+ this.client.removeAllListeners();
594
+ this.client.end();
595
+ this.client = null;
596
+ }
597
+ if (this.timer) {
598
+ clearInterval(this.timer);
599
+ this.timer = null;
600
+ }
601
+ // 清空运行时数据结构
602
+ this.list_msg = [];
603
+ this.dict_msg = {};
604
+ this.dict_subscribe = {};
605
+ this._regex_cache = {};
606
+ };
607
+
608
+ /**
609
+ * 发布主题
610
+ * @param {string} topic 主题
611
+ * @param {object} message 消息对象
612
+ * @param {number} qos 推送方式 0
613
+ * @param {boolean} retain 保持
614
+ */
615
+ Mqtt.prototype.publish = function (topic, message, qos = null, retain = false) {
616
+ this.client.publish(topic, message, {
617
+ qos: qos || this.config.publish_qos || 0,
618
+ retain,
619
+ });
620
+ };
621
+
622
+ /**
623
+ * 主题推送
624
+ * @param {string} topic 主题
625
+ * @param {string} msg_obj 消息主体
626
+ * @param {number} qos 推送方式 0
627
+ * @param {boolean} retain 保持
628
+ */
629
+ Mqtt.prototype.send = function (topic, msg_obj, qos = null, retain = false) {
630
+ this.publish(topic, JSON.stringify(msg_obj), qos, retain);
631
+ };
632
+
633
+ /**
634
+ * 生成ID
635
+ * @param {string} clientId 客户端ID
636
+ * @returns {string} ID
637
+ */
638
+ Mqtt.prototype.genId = function (clientId) {
639
+ return clientId + "_" + Date.parse(new Date());
640
+ };
641
+
642
+ /**
643
+ * 请求
644
+ * @param {string} topic 主题
645
+ * @param {string} method 请求方法
646
+ * @param {object} params 请求参数
647
+ * @param {Function} func 回调函数
648
+ * @param {number} timeout 超时时间(毫秒)
649
+ */
650
+ Mqtt.prototype.req = function (topic, method, params, func, timeout = 0) {
651
+ var data = {
652
+ id: this.genId(this.client.options.clientId),
653
+ method,
654
+ params,
655
+ };
656
+
657
+ if (func) {
658
+ data.func = func;
659
+ data.timestamp = Date.now();
660
+ data.timeout = timeout || this.config.request_timeout || 3000;
661
+ this.list_msg.push(data);
662
+ this.dict_msg[data.id] = data;
663
+
664
+ // 设置超时移除定时器
665
+ var _this = this;
666
+ data.timer = setTimeout(() => {
667
+ _this._delMsgById(data.id);
668
+ }, data.timeout);
669
+ }
670
+ this.send(topic, data);
671
+ };
672
+
673
+ /**
674
+ * 同步请求 - 可及时取回消息
675
+ * @param {string} topic 订阅板块
676
+ * @param {string} method 请求方法
677
+ * @param {object} params 传递参数
678
+ * @param {number} timeout 超时时间 0为默认值 10000ms
679
+ * @returns {object} 返回响应结果
680
+ */
681
+ Mqtt.prototype.reqAsync = function (topic, method, params, timeout = 0) {
682
+ var _this = this;
683
+ return new Promise((resolve, reject) => {
684
+ _this.req(
685
+ topic,
686
+ method,
687
+ params,
688
+ (res) => {
689
+ resolve(res);
690
+ },
691
+ timeout,
692
+ );
693
+ });
694
+ };
695
+
696
+ /**
697
+ * 根据ID移除消息
698
+ * @param {string} msg_id 消息ID
699
+ * @private
700
+ */
701
+ Mqtt.prototype._delMsgById = function (msg_id) {
702
+ var o = this.dict_msg[msg_id];
703
+ if (!o) {
704
+ return;
705
+ }
706
+ // 清除定时器
707
+ if (o.timer) {
708
+ clearTimeout(o.timer);
709
+ }
710
+ delete this.dict_msg[msg_id];
711
+
712
+ // 从数组中移除 (保持list_msg与dict_msg同步)
713
+ for (var i = 0; i < this.list_msg.length; i++) {
714
+ if (this.list_msg[i].id === msg_id) {
715
+ this.list_msg.splice(i, 1);
716
+ break;
717
+ }
718
+ }
719
+ };
720
+
721
+ /**
722
+ * 处理消息回复
723
+ * @param {object} msg 回复消息
724
+ * @private
725
+ */
726
+ Mqtt.prototype._handleResponse = function (msg) {
727
+ if (!msg || !msg.id) {
728
+ return;
729
+ }
730
+
731
+ var o = this.dict_msg[msg.id];
732
+ if (o && o.func) {
733
+ try {
734
+ // 执行回调函数
735
+ o.func(msg);
736
+ } catch (error) {
737
+ console.error("MQTT回调函数执行错误:", error);
738
+ }
739
+
740
+ // 从列表中移除已处理的消息
741
+ this._delMsgById(o.id);
742
+ }
743
+ };
744
+
745
+ /**
746
+ * 保存在线到数据库
747
+ * @param {Array} arr 客户端ID数组
748
+ * @param {number} online 在线情况 0为不在线,1为在线
749
+ */
750
+ Mqtt.prototype.saveOnline = async function (arr, online = 1) {
751
+ if (!arr || !arr.length) {
752
+ return;
753
+ }
754
+ var body = {
755
+ online,
756
+ };
757
+ var db = $.admin.sql("sys").db();
758
+ db.table = this.config.table || "iot_device";
759
+ db.size = 0;
760
+ var query = {};
761
+ query.clientid_has = arr.join(",");
762
+ await db.set(query, body);
763
+ };
764
+
765
+ /**
766
+ * 获取所有设备
767
+ * @returns {Array} 设备列表
768
+ */
769
+ Mqtt.prototype.getClients = async function () {
770
+ var db = $.admin.sql("sys").db();
771
+ db.table = this.config.table || "iot_device";
772
+ db.size = 0;
773
+ return await db.get({}, "", "clientid, online");
774
+ };
775
+
776
+ /**
777
+ * 更新在线设备
778
+ */
779
+ Mqtt.prototype.updateOnline = async function () {
780
+ var now = new Date().getTime();
781
+ var online_expires = this.config.online_expires; // 180
782
+
783
+ // 获取所有客户端
784
+ var drives = await this.getClients();
785
+ var result = this._processDeviceStatus(drives, now, online_expires);
786
+ var { list_online, list_offline, list_has } = result;
787
+
788
+ // 处理数据库在线但缓存缺失的设备
789
+ this._processUnseenDevices(
790
+ drives,
791
+ list_offline,
792
+ list_has,
793
+ now,
794
+ online_expires,
795
+ );
796
+
797
+ // 批量更新设备状态
798
+ await this._updateDeviceStatus(list_offline, list_online);
799
+ };
800
+
801
+ /**
802
+ * 处理设备状态
803
+ * @param {Array} drives 设备列表
804
+ * @param {number} now 当前时间戳
805
+ * @param {number} online_expires 在线过期时间
806
+ * @returns {object} 在线和离线设备列表
807
+ * @private
808
+ */
809
+ Mqtt.prototype._processDeviceStatus = function (drives, now, online_expires) {
810
+ var list_online = [];
811
+ var list_offline = [];
812
+ var list_has = [];
813
+
814
+ var mods = this.getMods();
815
+ for (var k in mods) {
816
+ var o = mods[k];
817
+ var dict = o.drives || {};
818
+ for (var clientid in dict) {
819
+ list_has.push(clientid);
820
+ // 设备已出现, 清除缺失记录
821
+ delete this.dict_lost[clientid];
822
+ var drive = drives.getObj({ clientid });
823
+ var device = dict[clientid];
824
+
825
+ if (device.online === 1) {
826
+ this._onlineDevice(
827
+ device,
828
+ drive,
829
+ clientid,
830
+ now,
831
+ online_expires,
832
+ list_online,
833
+ list_offline,
834
+ dict,
835
+ );
836
+ } else {
837
+ this._offlineDevice(drive, clientid, list_offline, dict);
838
+ }
839
+ }
840
+ }
841
+
842
+ return { list_online, list_offline, list_has };
843
+ };
844
+
845
+ /**
846
+ * 处理在线设备
847
+ * @param {object} device 设备对象
848
+ * @param {object} drive 数据库中的设备信息
849
+ * @param {string} clientid 设备ID
850
+ * @param {number} now 当前时间戳
851
+ * @param {number} online_expires 在线过期时间
852
+ * @param {Array} list_online 在线设备列表
853
+ * @param {Array} list_offline 离线设备列表
854
+ * @param {object} dict 设备字典
855
+ * @private
856
+ */
857
+ /* eslint-disable no-param-reassign */
858
+ Mqtt.prototype._onlineDevice = function (
859
+ device,
860
+ drive,
861
+ clientid,
862
+ now,
863
+ online_expires,
864
+ list_online,
865
+ list_offline,
866
+ dict,
867
+ ) {
868
+ if (device.time_last) {
869
+ var cha = now - device.time_last;
870
+ if (cha > online_expires) {
871
+ if (drive && drive.online) {
872
+ list_offline.push(clientid);
873
+ }
874
+ // 这里需要修改设备状态,但由于参数修改限制,我们直接修改字典
875
+ // 注意:这里仍然会修改外部对象,但这是业务逻辑需要
876
+ device.online = 0;
877
+ delete dict[clientid];
878
+ } else {
879
+ if (drive && !drive.online) {
880
+ list_online.push(clientid);
881
+ }
882
+ }
883
+ }
884
+ };
885
+ /* eslint-enable no-param-reassign */
886
+
887
+ /**
888
+ * 处理离线设备
889
+ * @param {object} drive 数据库中的设备信息
890
+ * @param {string} clientid 设备ID
891
+ * @param {Array} list_offline 离线设备列表
892
+ * @param {object} dict 设备字典
893
+ * @private
894
+ */
895
+ /* eslint-disable no-param-reassign */
896
+ Mqtt.prototype._offlineDevice = function (drive, clientid, list_offline, dict) {
897
+ if (drive && drive.online) {
898
+ list_offline.push(clientid);
899
+ }
900
+ // 从缓存中删除离线设备,避免下次再判断
901
+ delete dict[clientid];
902
+ };
903
+ /* eslint-enable no-param-reassign */
904
+
905
+ /**
906
+ * 处理数据库在线但缓存中缺失的设备, 连续缺失超过在线有效期才判离线
907
+ * @param {Array} drives 设备列表
908
+ * @param {Array} list_offline 离线设备列表
909
+ * @param {Array} list_has 已出现的设备ID列表
910
+ * @param {number} now 当前时间戳
911
+ * @param {number} online_expires 在线过期时间
912
+ * @private
913
+ */
914
+ Mqtt.prototype._processUnseenDevices = function (
915
+ drives,
916
+ list_offline,
917
+ list_has,
918
+ now,
919
+ online_expires,
920
+ ) {
921
+ // 处理未出现的设备
922
+ for (var i = 0; i < drives.length; i++) {
923
+ var { clientid, online } = drives[i];
924
+ if (!online || list_has.indexOf(clientid) !== -1) {
925
+ continue;
926
+ }
927
+ // 首次缺失, 记录时间, 等待下一个周期
928
+ if (!this.dict_lost[clientid]) {
929
+ this.dict_lost[clientid] = now;
930
+ continue;
931
+ }
932
+ // 连续缺失超过在线有效期, 判定离线
933
+ if (now - this.dict_lost[clientid] > online_expires) {
934
+ list_offline.push(clientid);
935
+ delete this.dict_lost[clientid];
936
+ }
937
+ }
938
+ };
939
+
940
+ /**
941
+ * 更新设备状态
942
+ * @param {Array} list_offline 离线设备列表
943
+ * @param {Array} list_online 在线设备列表
944
+ * @private
945
+ */
946
+ Mqtt.prototype._updateDeviceStatus = async function (
947
+ list_offline,
948
+ list_online,
949
+ ) {
950
+ var promises = [];
951
+
952
+ // 先将设备离线
953
+ var list_off = list_offline.to2D(30);
954
+ for (var i = 0; i < list_off.length; i++) {
955
+ promises.push(this.saveOnline(list_off[i], 0));
956
+ }
957
+
958
+ // 再将设备在线
959
+ var list_on = list_online.to2D(30);
960
+ for (var i = 0; i < list_on.length; i++) {
961
+ promises.push(this.saveOnline(list_on[i], 1));
962
+ }
963
+
964
+ await Promise.allSettled(promises);
965
+ };
966
+
967
+ /**
968
+ * 开始计时器
969
+ */
970
+ Mqtt.prototype.startTimer = function () {
971
+ if (!this.timer) {
972
+ this.timer = setInterval(() => {
973
+ try {
974
+ this.updateOnline();
975
+ } catch (err) {
976
+ console.error("更新在线设备失败", err);
977
+ }
978
+ }, this.config.online_interval);
979
+ }
980
+ };
981
+
982
+ exports.Mqtt = Mqtt;
983
+
984
+ /**
985
+ * 创建全局管理器
986
+ */
987
+ if (!$.pool.mqtt) {
988
+ $.pool.mqtt = {};
989
+ }
990
+
991
+ function mqttAdmin(scope, title) {
992
+ var sc = scope || $.val.scope + "";
993
+ var obj = $.pool.mqtt[sc];
994
+ if (!obj) {
995
+ $.pool.mqtt[sc] = new Mqtt({
996
+ name: sc,
997
+ title: title,
998
+ });
999
+ obj = $.pool.mqtt[sc];
1000
+ }
1001
+ return obj;
1002
+ }
1003
+
1004
+ /**
1005
+ * mqtt管理器, 用于管理插件
1006
+ * @param {string} scope 作用域
1007
+ * @param {string} title 标题
1008
+ * @returns {object} 返回一个缓存类
1009
+ */
1010
+ if ($.admin) {
1011
+ $.admin.mqtt = mqttAdmin;
1012
+ }