mm_os 4.2.6 → 4.2.7

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/drive.js CHANGED
@@ -1,676 +1,696 @@
1
- const os = require('os');
2
- const util = require('util');
3
- const Item = require('mm_machine').Drive;
4
-
5
- /**
6
- * mqtt驱动类
7
- * @augments {Item}
8
- * @class
9
- */
10
- class Drive extends Item {
11
- static config = {
12
- // 订阅的主题
13
- 'topic': [],
14
- // 主题回复
15
- 'topic_receive': [],
16
- // 给客户端推送的主题
17
- 'topic_push': 'mqtt/client/${clientid}',
18
- // 接收方式
19
- 'qos': 1,
20
- // 推送方式
21
- 'qos_push': 1,
22
- // 保持接收
23
- 'retain': true,
24
- // 超时反馈
25
- 'longtime': 10000,
26
- // 消息ID
27
- 'clientid': 'clientid',
28
- // 消息ID
29
- 'msgid': 'msgid',
30
- // 请求方法
31
- 'method': 'method',
32
- // 参数
33
- 'params': 'params',
34
- // 结果
35
- 'result': 'result',
36
- // 回复方法
37
- 'method_receive': '${method}-Ack',
38
- // 服务器地址
39
- 'host': ''
40
- };
41
- /**
42
- * 构造函数
43
- * @param {object} config 配置参数
44
- * @param {object} parent 父对象
45
- * @class
46
- */
47
- constructor(config, parent) {
48
- super({ ...Drive.config, ...config }, parent);
49
-
50
- this.mode = 3;
51
- }
52
- }
53
-
54
- /**
55
- * 配置预设
56
- */
57
- Drive.prototype._preset = function () {
58
- // 开放给前端调用的函数
59
- this.methods = { ...$.methods };
60
-
61
- // 客户端列表
62
- this.clients = {};
63
- };
64
-
65
- /**
66
- * 配置示例
67
- * @returns {object} 返回配置示例
68
- */
69
- Drive.prototype.model = function () {
70
- // 单层匹配订阅,用于订阅所有客户端要接收的数据 格式:$SYS/<代理服务器>/service/业务/+
71
- // "topic": "$SYS/mm/service/user/+"
72
- // 通配方式订阅,用于订阅仅该设备或该客户端要订阅的数据 格式:$SYS/<代理服务器>/service/appid/#
73
- // "topic": "$SYS/mm/service/idd6877e1561/#"
74
- // 完全匹配订阅,用于特定的业务订阅,业务压力最小,建议尽可能使用完全匹配
75
- // "topic": "$SYS/mm/service/state"
76
- return {
77
- // 名称, 由中英文和下“_”组成, 用于修改或卸载 例如: demo
78
- 'name': 'demo_test',
79
- // mqtt 服务标题
80
- 'title': '示例MQTT',
81
- // mqtt 服务介绍
82
- 'description': '',
83
- // 状态 0未启用,1启用
84
- 'state': 1,
85
- // 订阅的主题
86
- 'topic': ['mqtt/face/#', 'face/+/response', 'mqtt/server/#'],
87
- // 回复订阅主题
88
- 'topic_receive': ['mqtt/face/${clientid}', 'face/${clientid}/request'],
89
- // 给客户端推送的主题
90
- 'topic_push': 'mqtt/client/${clientid}',
91
- // 接收方式
92
- 'qos': 1,
93
- // 推送方式
94
- 'qos_push': 1,
95
- // 保持接收
96
- 'retain': true,
97
- // 超时反馈
98
- 'longtime': 10000,
99
- // 消息ID
100
- 'clientid': 'clientid',
101
- // 消息ID
102
- 'msgid': 'msgid',
103
- // 请求方法
104
- 'method': 'method',
105
- // 参数
106
- 'params': 'params',
107
- // 结果
108
- 'result': 'result',
109
- // 回复方法
110
- 'method_receive': '${method}-Ack'
111
- };
112
- };
113
-
114
- /**
115
- * 新建配置
116
- * @param {string} file 文件名
117
- */
118
- Drive.prototype.newConfig = function (file) {
119
- var fl = __dirname + '/config.tpl.json';
120
- if (fl.hasFile()) {
121
- var text = fl.loadText();
122
- if (text) {
123
- var l = $.slash;
124
- if (file.indexOf('mqtt' + l) !== -1) {
125
- var name = file.between('mqtt' + l, l);
126
- text = text.replaceAll('{0}', name);
127
- }
128
- file.saveText(text);
129
- }
130
- }
131
- };
132
-
133
- /**
134
- * 获取IP
135
- * @returns {string} 返回IP地址
136
- */
137
- Drive.prototype.getIp = function () {
138
- let interfaces = os.networkInte();
139
- for (let iface of Object.values(interfaces)) {
140
- for (let config of iface) {
141
- if (config.family === 'IPv4' && !config.internal) {
142
- return config.address;
143
- }
144
- }
145
- }
146
- return '127.0.0.1'; // 如果没有找到,返回本地回环地址
147
- };
148
-
149
- /**
150
- * 新建消息ID
151
- * @param {string} method 方法
152
- * @param {string} terminal 终端
153
- * @returns {string} 返回消息ID
154
- */
155
- Drive.prototype.getMsgId = function (method, terminal = 'server') {
156
- var time = new Date().getTime();
157
- var ip = this.getIp();
158
- // var msgid = "ID:localhost-" + clientid + "-" + time;
159
- var msgid = `${terminal}:${ip}-${time}-${method}`;
160
- return msgid;
161
- };
162
-
163
- /**
164
- * 回复的方法格式
165
- * @param {string} method 方法
166
- * @returns {string} 返回回复方法
167
- */
168
- Drive.prototype.getMethod = function (method) {
169
- var str = this.config.method_receive;
170
- return str.replace('${method}', method);
171
- };
172
-
173
- /**
174
- * 获取回复KEY
175
- * @param {string} method 方法
176
- * @param {string} clientid 客户端ID
177
- * @param {string} msgid 消息ID
178
- * @returns {string} 返回KEY
179
- */
180
- Drive.prototype.getReceiveKey = function (method, clientid, msgid) {
181
- return this.getMethod(method) + '_' + clientid + '_' + msgid;
182
- };
183
-
184
- /**
185
- * 获取KEY
186
- * @param {string} method 方法
187
- * @param {string} clientid 客户端ID
188
- * @param {string} msgid 消息ID
189
- * @returns {string} 返回KEY
190
- */
191
- Drive.prototype.getKey = function (method, clientid, msgid) {
192
- return method + '_' + clientid + '_' + msgid;
193
- };
194
-
195
- /**
196
- * 补全路径
197
- * @param {string} path 路径
198
- * @returns {string} 返回完整的路径
199
- */
200
- Drive.prototype.fullUrl = function (path) {
201
- var src = path || '';
202
- if (src.indexOf('http') !== 0) {
203
- var host = this.config.host || $.host;
204
- if (host.indexOf('http') !== 0) {
205
- host = 'http://' + host;
206
- }
207
- if (src.indexOf('~/') === 0) {
208
- src = src.replace('~/', host);
209
- } else if (src.indexOf('/') === 0) {
210
- src = src.replace('/', host);
211
- }
212
- }
213
- return src;
214
- };
215
-
216
- /**
217
- * 推送消息
218
- * @param {string} topic 推送主题
219
- * @param {object} msg 推送内容
220
- * @param {number} qos 接收方式
221
- * @param {boolean} retain 是否保持推送
222
- */
223
- Drive.prototype.send = function (topic, msg, qos = 0, retain = false) {
224
-
225
- };
226
-
227
- /**
228
- * 收到消息
229
- * @param {string} push_topic 推送过来的主题
230
- * @param {object} msg 原消息
231
- * @param {number} index 索引
232
- * @param {string} topic 订阅的主题
233
- */
234
- Drive.prototype.message = async function (push_topic, msg, index, topic) {
235
- // console.log("请求后", push_topic, msg, index, topic);
236
- };
237
-
238
- /**
239
- * 推送消息到设备
240
- * @param {string} clientid 客户端ID
241
- * @param {object} msg 消息主题
242
- * @param {Function} func 回调函数
243
- * @param {number} longtime 超时时间
244
- */
245
- Drive.prototype.pushSync = function (clientid, msg, func, longtime = 0) {
246
- var {
247
- msgid,
248
- method,
249
- topic_push,
250
- qos_push
251
- } = this.config;
252
- var id = msg[msgid];
253
- if (!id) {
254
- msg[msgid] = this.getMsgId(msg[method], 'server');
255
- id = msg[msgid];
256
- }
257
- var key = this.getReceiveKey(msg[method], clientid, id);
258
- if (func) {
259
- if (!this.clients[clientid]) {
260
- this.clients[clientid] = {};
261
- }
262
- this.clients[clientid][key] = {
263
- clientid,
264
- id,
265
- func
266
- };
267
- }
268
-
269
- var topic = this.getTopic(topic_push, clientid);
270
- this.send(topic, msg, qos_push);
271
- if (func) {
272
- setTimeout(async () => {
273
- // 如果时间到了,回调函数还在队列中,则视为无回复
274
- if (this.clients[clientid] && this.clients[clientid][key]) {
275
- try {
276
- await this.clients[clientid][key].func(null);
277
- } catch (error) {
278
- this.log('error', 'MQTT回调错误', key, error);
279
- //TODO handle the exception
280
- }
281
- this.delMsg(clientid, key);
282
- }
283
- }, longtime || this.config.longtime || 60000);
284
- }
285
- };
286
-
287
- /**
288
- * 推送消息
289
- * @param {string} clientid 客户端ID
290
- * @param {object} msg 信息
291
- * @param {number} longtime 超时回馈
292
- * @returns {object} 返回消息主体
293
- */
294
- Drive.prototype.pushS = function (clientid, msg, longtime) {
295
- var _this = this;
296
- return new Promise((resolve, reject) => {
297
- _this.pushSync(clientid, msg, (res) => {
298
- resolve(res);
299
- }, longtime);
300
- });
301
- };
302
-
303
- /**
304
- * 保存设备在线状态
305
- * @param {string} clientid 客户端ID
306
- * @param {object} online 是否在线 0为没在线 1为在线
307
- * @param {object} ip 设备IP
308
- */
309
- Drive.prototype.saveOnline = async function (clientid, online, ip) {
310
- if (!clientid) {
311
-
312
- }
313
- };
314
-
315
- /**
316
- * 更新设备在线
317
- * @param {string} clientid 客户端ID
318
- * @param {boolean} online 是否在线 0为没在线 1为在线
319
- * @param {string} ip 设备IP
320
- */
321
- Drive.prototype.updateOnline = async function (clientid, online = 1, ip = '') {
322
- if (!this.clients[clientid]) {
323
- this.clients[clientid] = {};
324
- }
325
- var time_last = new Date().getTime(); // 跟新时间戳
326
- this.clients[clientid].online = online;
327
- if (online) {
328
- this.clients[clientid].time_last = time_last;
329
- }
330
- var {
331
- device
332
- } = await $.server.checkDevice(clientid);
333
- if (device && online && !device.online) {
334
- device.online = online;
335
- if (ip) {
336
- device.ip = ip;
337
- }
338
- }
339
- };
340
-
341
- /**
342
- * 推送消息
343
- * @param {string} method 方法
344
- * @param {string} clientid 客户端ID
345
- * @param {object} params 信息
346
- * @param {number} longtime 超时回馈
347
- * @returns {object} 返回消息主体
348
- */
349
- Drive.prototype.push = function (method, clientid, params, longtime = 0) {
350
- var cg = this.config;
351
- var msg = {};
352
- msg[cg.msgid] = this.getMsgId(method);
353
- msg[cg.method] = method;
354
- msg[cg.params] = params;
355
- return this.pushS(clientid, msg, longtime);
356
- };
357
-
358
- /**
359
- * 删除消息
360
- * @param {string} clientid 设备ID
361
- * @param {string} key 消息键
362
- */
363
- Drive.prototype.delMsg = function (clientid, key) {
364
- if (this.clients[clientid]) {
365
- var dict = this.clients[clientid];
366
- delete dict[key];
367
- }
368
- };
369
-
370
- /**
371
- * 处理事件
372
- * @param {string} clientid 客户端ID
373
- * @param {string} key 键
374
- * @param {object} json 信息
375
- */
376
- Drive.prototype.runEvent = function (clientid, key, json) {
377
- var method = key.left('_');
378
- if (this[method + '_event']) {
379
- try {
380
- this[method + '_event'](clientid, json);
381
- } catch (err) {
382
- this.log('error', 'MQTT事件执行失败!', key, err);
383
- }
384
- }
385
- };
386
-
387
- /**
388
- * 执行响应
389
- * @param {string} clientid 客户端ID
390
- * @param {string} key 键
391
- * @param {object} json 信息
392
- * @returns {object} 返回执行结果
393
- */
394
- Drive.prototype.run = async function (clientid, key, json) {
395
- var o;
396
- if (this.clients[clientid]) {
397
- o = this.clients[clientid][key];
398
- }
399
- if (o) {
400
- delete this.clients[clientid][key];
401
- try {
402
- await o.func(json);
403
- } catch (err) {
404
- this.log('error', 'MQTT执行失败!', key, err);
405
- }
406
- } else {
407
- await this.runEvent(clientid, key, json);
408
- }
409
- return o;
410
- };
411
-
412
- /**
413
- * 获取客户端ID
414
- * @param {string} push_topic 推送过来的主题
415
- * @param {object} body 消息主体
416
- * @param {object} msg 消息源
417
- * @param {string} topic 订阅的主题
418
- * @returns {string} 返回客户端ID
419
- */
420
- Drive.prototype.getClientId = function (push_topic, body, msg, topic) {
421
- var cg = this.config;
422
- var clientid = body[cg.clientid] || msg[cg.clientid];
423
- if (!clientid) {
424
- var str = topic.left('#');
425
- clientid = push_topic.right(str).left('/', true);
426
- }
427
- return clientid;
428
- };
429
-
430
- /**
431
- * 数据格式转换-转入
432
- * @param {string} push_topic 推送过来的主题
433
- * @param {object} msg 消息源
434
- * @param {string} topic 订阅的主题
435
- * @param {number} index 索引
436
- * @returns {object} 返回消息主体
437
- */
438
- Drive.prototype.toIn = function (push_topic, msg, topic, index) {
439
- var cg = this.config;
440
- var method = msg[cg.method];
441
- var json = {
442
- clientid: '',
443
- id: msg[cg.msgid] || this.getMsgId(method, 'client'),
444
- method
445
- };
446
- if (msg[cg.params]) {
447
- json.params = msg[cg.params];
448
- }
449
- if (msg[cg.result]) {
450
- json.result = msg[cg.result];
451
- }
452
- json.clientid = this.getClientId(push_topic, json.params || json.result || {}, msg, topic);
453
- return json;
454
- };
455
-
456
- /**
457
- * 数据格式转换-转出
458
- * @param {string} push_topic 推送过来的主题
459
- * @param {object} msg 消息主体
460
- * @param {string} topic 订阅的主题
461
- * @param {number} index 索引
462
- * @returns {object} 返回消息主体
463
- */
464
- Drive.prototype.toOut = function (push_topic, msg, topic, index) {
465
- return msg;
466
- };
467
-
468
- /**
469
- * 获取回复主题
470
- * @param {string} topic_tpl 主题模板
471
- * @param {string} clientid 客户端ID
472
- * @param {object} params 消息
473
- * @returns {string} 返回主题
474
- */
475
- Drive.prototype.getTopic = function (topic_tpl, clientid, params) {
476
- return (topic_tpl || '').replace('${clientid}', clientid);
477
- };
478
-
479
- /**
480
- * 处理函数, 用于处理订阅内容
481
- * @param {string} push_topic 推送过来的主题
482
- * @param {object} msg 消息正文
483
- * @param {string} topic 订阅的主题
484
- * @param {number} index 索引
485
- * @returns {object} 返回执行结果
486
- */
487
- Drive.prototype.run = async function (push_topic, msg, topic, index) {
488
- var json = this.convertIn(push_topic, msg, topic, index);
489
-
490
- if (await this._handleMessage(json)) {
491
- return;
492
- }
493
-
494
- if (json.method) {
495
- await this._handleMethodMessage(json, msg, topic, index);
496
- }
497
-
498
- return;
499
- };
500
-
501
- /**
502
- * 处理消息
503
- * @param {object} json 消息对象
504
- * @returns {boolean} 是否处理成功
505
- * @private
506
- */
507
- Drive.prototype._handleMessage = async function (json) {
508
- var id = json.id;
509
- if (json.result && id) {
510
- var key = this.getKey(json.method, json.clientid, id);
511
- var o = await this.run(json.clientid, key, json.result);
512
- if (o) {
513
- return true;
514
- }
515
- }
516
- return false;
517
- };
518
-
519
- /**
520
- * 处理方法消息
521
- * @param {object} json 消息对象
522
- * @param {object} msg 原始消息
523
- * @param {string} topic 订阅主题
524
- * @param {number} index 索引
525
- * @private
526
- */
527
- Drive.prototype._handleMethodMessage = async function (json, msg, topic, index) {
528
- var func = this._getMethod(json.method);
529
- if (func) {
530
- var ret = await this._execMethod(func, json, msg);
531
- if (ret) {
532
- await this._sendMethodRes(ret, json, topic, index);
533
- }
534
- }
535
- };
536
-
537
- /**
538
- * 获取方法
539
- * @param {string} methodStr 方法字符串
540
- * @returns {Function|null} 方法函数
541
- * @private
542
- */
543
- Drive.prototype._getMethod = function (methodStr) {
544
- var methods = this.methods;
545
- var arr = methodStr.split('.');
546
-
547
- for (var i = 0; i < arr.length; i++) {
548
- var key = arr[i];
549
- var m = methods[key];
550
- if (m) {
551
- methods = m;
552
- } else {
553
- return null;
554
- }
555
- }
556
-
557
- return typeof (methods) == 'function' ? methods : null;
558
- };
559
-
560
- /**
561
- * 执行方法
562
- * @param {Function} func 方法函数
563
- * @param {object} json 消息对象
564
- * @param {object} msg 原始消息
565
- * @returns {*} 方法执行结果
566
- * @private
567
- */
568
- Drive.prototype._execMethod = async function (func, json, msg) {
569
- var id = json.id;
570
- var params = json.params;
571
- var ret;
572
-
573
- try {
574
- ret = func(json.clientid, params, msg, id);
575
- if (util.types.isPromise(ret)) {
576
- ret = await ret;
577
- }
578
- } catch (err) {
579
- this.log('error', '事件回调失败!', err);
580
- }
581
-
582
- return ret;
583
- };
584
-
585
- /**
586
- * 发送方法响应
587
- * @param {*} ret 方法执行结果
588
- * @param {object} json 消息对象
589
- * @param {string} topic 订阅主题
590
- * @param {number} index 索引
591
- * @private
592
- */
593
- Drive.prototype._sendMethodRes = async function (ret, json, topic, index) {
594
- var arr_tc = this.config.topic_receive;
595
- if (arr_tc.length > index) {
596
- var obj = {};
597
- var cg = this.config;
598
- var id = json.id;
599
-
600
- if (id) {
601
- obj[cg.msgid] = id;
602
- }
603
-
604
- try {
605
- obj[cg.method] = this.getMethod(json.method);
606
- obj[cg.result] = ret;
607
- var topic_receive = this.getTopic(arr_tc[index], json.clientid, json.params);
608
- var reply_msg = this.convertOut(topic_receive, obj, topic, index);
609
- await this.send(topic_receive, reply_msg);
610
- } catch (err) {
611
- this.log('error', 'MQTT事件响应失败!', err);
612
- }
613
- }
614
- };
615
-
616
- /**
617
- * 主函数, 用于接收并处理订阅内容
618
- * @param {string} push_topic 推送过来的主题
619
- * @param {object} msg 消息正文
620
- * @param {string} topic 订阅的主题
621
- * @param {number} index 索引
622
- * @returns {object} 返回执行结果
623
- */
624
- Drive.prototype.main = async function (push_topic, msg, topic, index) {
625
- return this.handle(push_topic, msg, topic, index);
626
- };
627
-
628
- /**
629
- * 接收订阅消息
630
- * @param {object} ret 执行结果
631
- * @param {object} push_topic 主题
632
- * @param {object} msg 消息正文
633
- * @param {string} topic 订阅的主题
634
- * @param {number} index 索引
635
- */
636
- Drive.prototype.mainAfter = async function (ret, push_topic, msg, topic, index) {
637
- await this.message(push_topic, msg, topic, index);
638
- };
639
-
640
- /**
641
- * 获取插件
642
- * @param {string} app 应用名称
643
- * @param {string} name 插件名称
644
- * @returns {object} 返回获取到的插件
645
- */
646
- Drive.prototype.plugin = function (app, name) {
647
- var l = $.slash;
648
- var app_name = app || this.config_file.between('app' + l, l);
649
- var plugin_name = name || this.config_file.between('plugin' + l, l);
650
- var plus;
651
- var plugins = $.pool.plugin[app_name];
652
- if (plugins) {
653
- plus = plugins.get(plugin_name);
654
- }
655
- return plus;
656
- };
657
-
658
- /**
659
- * 获取模型
660
- * @param {string} type 模型类型
661
- * @returns {object} 返回获取到的模型
662
- */
663
- Drive.prototype.getModel = function (type) {
664
- let model = { ...this.config };
665
- let dir = this.getDir();
666
- let l = $.slash;
667
- let app_name = dir.between('app' + l, l);
668
- let plugin_name = dir.between('plugin' + l, l);
669
- let name = dir.basename();
670
- model.app = app_name;
671
- model.plugin = plugin_name;
672
- model.name = model.name || name;
673
- return model;
674
- };
675
-
676
- module.exports = Drive;
1
+ const os = require("os");
2
+ const util = require("util");
3
+ const Item = require("mm_machine").Drive;
4
+
5
+ /**
6
+ * mqtt驱动类
7
+ * @augments {Item}
8
+ * @class
9
+ */
10
+ class Drive extends Item {
11
+ static config = {
12
+ // 名称
13
+ name: "",
14
+ // mqtt 服务标题
15
+ title: "",
16
+ // mqtt 服务介绍
17
+ description: "",
18
+ // 状态 0未启用,1启用
19
+ state: 1,
20
+ // 订阅的主题
21
+ topic: [],
22
+ // 主题回复
23
+ topic_receive: [],
24
+ // 给客户端推送的主题
25
+ topic_push: "face/${clientid}/cmd/${method}",
26
+ // 接收方式
27
+ qos: 1,
28
+ // 推送方式
29
+ qos_push: 1,
30
+ // 保持接收
31
+ retain: true,
32
+ // 超时反馈
33
+ longtime: 10000,
34
+ // 消息ID
35
+ clientid: "clientid",
36
+ // 消息ID
37
+ msgid: "msgid",
38
+ // 请求方法
39
+ method: "method",
40
+ // 参数
41
+ params: "params",
42
+ // 结果
43
+ result: "result",
44
+ // 回复方法
45
+ method_receive: "${method}_ask",
46
+ // 主程序
47
+ main: "./index.js",
48
+ };
49
+ /**
50
+ * 构造函数
51
+ * @param {object} config 配置参数
52
+ * @param {object} parent 父对象
53
+ * @class
54
+ */
55
+ constructor(config, parent) {
56
+ super({ ...Drive.config, ...config }, parent);
57
+
58
+ // 开放给前端调用的函数
59
+ this.methods = { ...$.methods };
60
+
61
+ // 客户端列表
62
+ this.clients = {};
63
+ // 设备在线状态缓存
64
+ this.drives = {};
65
+ this.mode = 3;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * 配置示例
71
+ * @returns {object} 返回配置示例
72
+ */
73
+ Drive.prototype.model = function () {
74
+ // 单层匹配订阅,用于订阅所有客户端要接收的数据 格式:$SYS/<代理服务器>/service/业务/+
75
+ // "topic": "$SYS/mm/service/user/+"
76
+ // 通配方式订阅,用于订阅仅该设备或该客户端要订阅的数据 格式:$SYS/<代理服务器>/service/appid/#
77
+ // "topic": "$SYS/mm/service/idd6877e1561/#"
78
+ // 完全匹配订阅,用于特定的业务订阅,业务压力最小,建议尽可能使用完全匹配
79
+ // "topic": "$SYS/mm/service/state"
80
+ return {
81
+ // 名称, 由中英文和下“_”组成, 用于修改或卸载 例如: demo
82
+ name: "demo_test",
83
+ // mqtt 服务标题
84
+ title: "示例MQTT",
85
+ // mqtt 服务介绍
86
+ description: "",
87
+ // 状态 0未启用,1启用
88
+ state: 1,
89
+ // 订阅的主题 {产品类型}/{设备ID}/{数据类型}/{子类型}
90
+ // 接收设备状态、事件、命令回复、设备请求
91
+ topic: [
92
+ "face/+/status",
93
+ "face/+/event/recognition",
94
+ "face/+/cmd/+/response",
95
+ "face/+/request/+",
96
+ ],
97
+ // 回复订阅主题
98
+ topic_receive: ["face/${clientid}/response/${method}"],
99
+ // 给客户端推送的主题
100
+ topic_push: "face/${clientid}/cmd/${method}",
101
+ // 接收方式
102
+ qos: 1,
103
+ // 推送方式
104
+ qos_push: 1,
105
+ // 保持接收
106
+ retain: true,
107
+ // 超时反馈
108
+ longtime: 10000,
109
+ // 消息ID
110
+ clientid: "clientid",
111
+ // 消息ID
112
+ msgid: "msgid",
113
+ // 请求方法
114
+ method: "method",
115
+ // 参数
116
+ params: "params",
117
+ // 结果
118
+ result: "result",
119
+ // 回复方法
120
+ method_receive: "${method}_ask",
121
+ };
122
+ };
123
+
124
+ /**
125
+ * 获取IP
126
+ * @returns {string} 返回IP地址
127
+ */
128
+ Drive.prototype.getIp = function () {
129
+ let interfaces = os.networkInterfaces();
130
+ for (let iface of Object.values(interfaces)) {
131
+ for (let config of iface) {
132
+ if (config.family === "IPv4" && !config.internal) {
133
+ return config.address;
134
+ }
135
+ }
136
+ }
137
+ return "127.0.0.1"; // 如果没有找到,返回本地回环地址
138
+ };
139
+
140
+ /**
141
+ * 新建消息ID
142
+ * @param {string} method 方法
143
+ * @param {string} terminal 终端
144
+ * @returns {string} 返回消息ID
145
+ */
146
+ Drive.prototype.getMsgId = function (method, terminal = "server") {
147
+ var time = new Date().getTime();
148
+ var ip = this.getIp();
149
+ // var msgid = "ID:localhost-" + clientid + "-" + time;
150
+ var msgid = `${terminal}:${ip}-${time}-${method}`;
151
+ return msgid;
152
+ };
153
+
154
+ /**
155
+ * 回复的方法格式
156
+ * @param {string} method 方法
157
+ * @returns {string} 返回回复方法
158
+ */
159
+ Drive.prototype.getReplyMethod = function (method) {
160
+ var str = this.config.method_receive;
161
+ return str.replace("${method}", method);
162
+ };
163
+
164
+ /**
165
+ * 获取回复KEY
166
+ * @param {string} method 方法
167
+ * @param {string} clientid 客户端ID
168
+ * @param {string} msgid 消息ID
169
+ * @returns {string} 返回KEY
170
+ */
171
+ Drive.prototype.getReceiveKey = function (method, clientid, msgid) {
172
+ return this.getReplyMethod(method) + "_" + clientid + "_" + msgid;
173
+ };
174
+
175
+ /**
176
+ * 获取KEY
177
+ * @param {string} method 方法
178
+ * @param {string} clientid 客户端ID
179
+ * @param {string} msgid 消息ID
180
+ * @returns {string} 返回KEY
181
+ */
182
+ Drive.prototype.getKey = function (method, clientid, msgid) {
183
+ return method + "_" + clientid + "_" + msgid;
184
+ };
185
+
186
+ /**
187
+ * 补全路径
188
+ * @param {string} path 路径
189
+ * @returns {string} 返回完整的路径
190
+ */
191
+ Drive.prototype.fullUrl = function (path) {
192
+ var src = path || "";
193
+ if (src.indexOf("http") !== 0) {
194
+ var host = this.config.host || $.host;
195
+ if (host.indexOf("http") !== 0) {
196
+ host = "http://" + host;
197
+ }
198
+ if (src.indexOf("~/") === 0) {
199
+ src = src.replace("~/", host);
200
+ } else if (src.indexOf("/") === 0) {
201
+ src = src.replace("/", host);
202
+ }
203
+ }
204
+ return src;
205
+ };
206
+
207
+ /**
208
+ * 推送消息
209
+ * @param {string} topic 推送主题
210
+ * @param {object} msg 推送内容
211
+ * @param {number} qos 接收方式
212
+ * @param {boolean} retain 是否保持推送
213
+ */
214
+ Drive.prototype.send = function (topic, msg, qos = 0, retain = false) {};
215
+
216
+ /**
217
+ * 收到消息
218
+ * @param {string} push_topic 推送过来的主题
219
+ * @param {object} msg 原消息
220
+ * @param {number} index 索引
221
+ * @param {string} topic 订阅的主题
222
+ */
223
+ Drive.prototype.message = async function (push_topic, msg, index, topic) {};
224
+
225
+ /**
226
+ * 推送消息到设备
227
+ * @param {string} clientid 客户端ID
228
+ * @param {object} msg 消息主题
229
+ * @param {Function} func 回调函数
230
+ * @param {number} longtime 超时时间
231
+ */
232
+ Drive.prototype.pushSync = function (clientid, msg, func, longtime = 0) {
233
+ var { msgid, method, topic_push, qos_push } = this.config;
234
+ var id = msg[msgid];
235
+ if (!id) {
236
+ msg[msgid] = this.getMsgId(msg[method], "server");
237
+ id = msg[msgid];
238
+ }
239
+ var key = this.getReceiveKey(msg[method], clientid, id);
240
+ if (func) {
241
+ if (!this.clients[clientid]) {
242
+ this.clients[clientid] = {};
243
+ }
244
+ this.clients[clientid][key] = {
245
+ clientid,
246
+ id,
247
+ func,
248
+ };
249
+ }
250
+
251
+ var topic = this.getTopic(topic_push, clientid, msg);
252
+ this.send(topic, msg, qos_push);
253
+ if (func) {
254
+ var _this = this;
255
+ var timer_key = this.getReceiveKey(msg[method], clientid, id);
256
+ this._push_timers = this._push_timers || {};
257
+ this._push_timers[timer_key] = setTimeout(
258
+ async () => {
259
+ if (_this.clients[clientid] && _this.clients[clientid][key]) {
260
+ try {
261
+ await _this.clients[clientid][key].func(null);
262
+ } catch (error) {
263
+ _this.log("error", "MQTT回调错误", key, error);
264
+ }
265
+ _this.delMsg(clientid, key);
266
+ }
267
+ delete _this._push_timers[timer_key];
268
+ },
269
+ longtime || this.config.longtime || 60000,
270
+ );
271
+ }
272
+ };
273
+
274
+ /**
275
+ * 推送消息
276
+ * @param {string} clientid 客户端ID
277
+ * @param {object} msg 信息
278
+ * @param {number} longtime 超时回馈
279
+ * @returns {object} 返回消息主体
280
+ */
281
+ Drive.prototype.pushS = function (clientid, msg, longtime) {
282
+ var _this = this;
283
+ return new Promise((resolve, reject) => {
284
+ _this.pushSync(
285
+ clientid,
286
+ msg,
287
+ (res) => {
288
+ resolve(res);
289
+ },
290
+ longtime,
291
+ );
292
+ });
293
+ };
294
+
295
+ /**
296
+ * 更新设备在线
297
+ * @param {string} clientid 客户端ID
298
+ * @param {boolean} online 是否在线 0为没在线 1为在线
299
+ * @param {string} ip 设备IP
300
+ */
301
+ Drive.prototype.updateOnline = async function (clientid, online = 1, ip = "") {
302
+ if (!this.drives[clientid]) {
303
+ this.drives[clientid] = {};
304
+ }
305
+ var time_last = new Date().getTime(); // 跟新时间戳
306
+ this.drives[clientid].online = online;
307
+ if (online) {
308
+ this.drives[clientid].time_last = time_last;
309
+ }
310
+ if ($.server && $.server.checkDevice) {
311
+ await this._updateDeviceInfo(clientid, online, ip);
312
+ }
313
+ };
314
+
315
+ /**
316
+ * 更新数据库设备在线信息
317
+ * @param {string} clientid 客户端ID
318
+ * @param {boolean} online 是否在线 0为没在线 1为在线
319
+ * @param {string} ip 设备IP
320
+ * @private
321
+ */
322
+ Drive.prototype._updateDeviceInfo = async function (clientid, online, ip) {
323
+ try {
324
+ var { device } = await $.server.checkDevice(clientid);
325
+ if (device && online && !device.online) {
326
+ device.online = online;
327
+ if (ip) {
328
+ device.ip = ip;
329
+ }
330
+ }
331
+ } catch (error) {
332
+ this.log("error", "更新设备在线失败", error);
333
+ }
334
+ };
335
+
336
+ /**
337
+ * 推送消息
338
+ * @param {string} method 方法
339
+ * @param {string} clientid 客户端ID
340
+ * @param {object} params 信息
341
+ * @param {number} longtime 超时回馈
342
+ * @returns {object} 返回消息主体
343
+ */
344
+ Drive.prototype.push = function (method, clientid, params, longtime = 0) {
345
+ var cg = this.config;
346
+ var msg = {};
347
+ msg[cg.msgid] = this.getMsgId(method);
348
+ msg[cg.method] = method;
349
+ msg[cg.params] = params;
350
+ return this.pushS(clientid, msg, longtime);
351
+ };
352
+
353
+ /**
354
+ * 删除消息
355
+ * @param {string} clientid 设备ID
356
+ * @param {string} key 消息键
357
+ */
358
+ Drive.prototype.delMsg = function (clientid, key) {
359
+ if (this.clients[clientid]) {
360
+ var dict = this.clients[clientid];
361
+ delete dict[key];
362
+ // 清除关联的定时器
363
+ if (this._push_timers && this._push_timers[key]) {
364
+ clearTimeout(this._push_timers[key]);
365
+ delete this._push_timers[key];
366
+ }
367
+ // 当该客户端没有待处理消息时,清理空对象
368
+ if (Object.keys(dict).length === 0) {
369
+ delete this.clients[clientid];
370
+ }
371
+ }
372
+ };
373
+
374
+ /**
375
+ * 处理事件
376
+ * @param {string} clientid 客户端ID
377
+ * @param {string} key 键
378
+ * @param {object} json 信息
379
+ */
380
+ Drive.prototype.runEvent = function (clientid, key, json) {
381
+ var method = key.left("_");
382
+ if (this[method + "_event"]) {
383
+ try {
384
+ this[method + "_event"](clientid, json);
385
+ } catch (err) {
386
+ this.log("error", "MQTT事件执行失败!", key, err);
387
+ }
388
+ }
389
+ };
390
+
391
+ /**
392
+ * 获取客户端ID
393
+ * @param {string} push_topic 推送过来的主题
394
+ * @param {object} body 消息主体
395
+ * @param {object} msg 消息源
396
+ * @param {string} topic 订阅的主题
397
+ * @returns {string} 返回客户端ID
398
+ */
399
+ Drive.prototype.getClientId = function (push_topic, body, msg, topic) {
400
+ var cg = this.config;
401
+ var clientid = body[cg.clientid] || msg[cg.clientid];
402
+ if (!clientid) {
403
+ var str = topic.left("#");
404
+ clientid = push_topic.right(str).left("/", true);
405
+ }
406
+ return clientid;
407
+ };
408
+
409
+ /**
410
+ * 数据格式转换-转入
411
+ * @param {string} push_topic 推送过来的主题
412
+ * @param {object} msg 消息源
413
+ * @param {string} topic 订阅的主题
414
+ * @param {number} index 索引
415
+ * @returns {object} 返回消息主体
416
+ */
417
+ Drive.prototype.toIn = function (push_topic, msg, topic, index) {
418
+ var cg = this.config;
419
+ var method = msg[cg.method];
420
+ var json = {
421
+ clientid: "",
422
+ id: msg[cg.msgid] || this.getMsgId(method, "client"),
423
+ method,
424
+ };
425
+ if (msg[cg.params]) {
426
+ json.params = msg[cg.params];
427
+ }
428
+ if (msg[cg.result]) {
429
+ json.result = msg[cg.result];
430
+ }
431
+ json.clientid = this.getClientId(
432
+ push_topic,
433
+ json.params || json.result || {},
434
+ msg,
435
+ topic,
436
+ );
437
+ return json;
438
+ };
439
+
440
+ /**
441
+ * 数据格式转换-转出
442
+ * @param {string} push_topic 推送过来的主题
443
+ * @param {object} msg 消息主体
444
+ * @param {string} topic 订阅的主题
445
+ * @param {number} index 索引
446
+ * @returns {object} 返回消息主体
447
+ */
448
+ Drive.prototype.toOut = function (push_topic, msg, topic, index) {
449
+ return msg;
450
+ };
451
+
452
+ /**
453
+ * 获取回复主题
454
+ * @param {string} topic_tpl 主题模板
455
+ * @param {string} clientid 客户端ID
456
+ * @param {object} params 消息
457
+ * @returns {string} 返回主题
458
+ */
459
+ Drive.prototype.getTopic = function (topic_tpl, clientid, params) {
460
+ return (topic_tpl || "")
461
+ .replace("${clientid}", clientid)
462
+ .replace("${method}", params[this.config.method]);
463
+ };
464
+
465
+ /**
466
+ * 处理函数, 用于处理订阅内容
467
+ * @param {string} push_topic 推送过来的主题
468
+ * @param {object} msg 消息正文
469
+ * @param {string} topic 订阅的主题
470
+ * @param {number} index 索引
471
+ * @returns {object} 返回执行结果
472
+ */
473
+ Drive.prototype.handle = async function (push_topic, msg, topic, index) {
474
+ var json = this.toIn(push_topic, msg, topic, index);
475
+
476
+ if (await this._handleMessage(json)) {
477
+ return;
478
+ }
479
+
480
+ if (json.method) {
481
+ await this._handleMethodMessage(json, msg, topic, index);
482
+ }
483
+
484
+ return;
485
+ };
486
+
487
+ /**
488
+ * 执行响应
489
+ * @param {string} clientid 客户端ID
490
+ * @param {string} key 键
491
+ * @param {object} json 信息
492
+ * @returns {object} 返回执行结果
493
+ */
494
+ Drive.prototype.main = async function (clientid, key, json) {
495
+ var o;
496
+ if (this.clients[clientid]) {
497
+ o = this.clients[clientid][key];
498
+ }
499
+ if (o) {
500
+ delete this.clients[clientid][key];
501
+ try {
502
+ await o.func(json);
503
+ } catch (err) {
504
+ this.log("error", "MQTT执行失败!", key, err);
505
+ }
506
+ } else {
507
+ await this.runEvent(clientid, key, json);
508
+ }
509
+ return o;
510
+ };
511
+
512
+ /**
513
+ * 处理消息
514
+ * @param {object} json 消息对象
515
+ * @returns {boolean} 是否处理成功
516
+ * @private
517
+ */
518
+ Drive.prototype._handleMessage = async function (json) {
519
+ var id = json.id;
520
+ if (json.result && id) {
521
+ var key = this.getKey(json.method, json.clientid, id);
522
+ var o = await this.run(json.clientid, key, json.result);
523
+ if (o) {
524
+ return true;
525
+ }
526
+ }
527
+ return false;
528
+ };
529
+
530
+ /**
531
+ * 处理方法消息
532
+ * @param {object} json 消息对象
533
+ * @param {object} msg 原始消息
534
+ * @param {string} topic 订阅主题
535
+ * @param {number} index 索引
536
+ * @private
537
+ */
538
+ Drive.prototype._handleMethodMessage = async function (
539
+ json,
540
+ msg,
541
+ topic,
542
+ index,
543
+ ) {
544
+ var func = this._getMethod(json.method);
545
+ if (func) {
546
+ var ret = await this._execMethod(func, json, msg);
547
+ if (ret) {
548
+ await this._sendMethodRes(ret, json, topic, index);
549
+ }
550
+ }
551
+ };
552
+
553
+ /**
554
+ * 获取方法
555
+ * @param {string} method_name 方法字符串
556
+ * @returns {Function|null} 方法函数
557
+ * @private
558
+ */
559
+ Drive.prototype._getMethod = function (method_name) {
560
+ var methods = this.methods;
561
+ var arr = method_name.split(".");
562
+
563
+ for (var i = 0; i < arr.length; i++) {
564
+ var key = arr[i];
565
+ var m = methods[key];
566
+ if (m) {
567
+ methods = m;
568
+ } else {
569
+ return null;
570
+ }
571
+ }
572
+
573
+ return typeof methods == "function" ? methods : null;
574
+ };
575
+
576
+ /**
577
+ * 执行方法
578
+ * @param {Function} func 方法函数
579
+ * @param {object} json 消息对象
580
+ * @param {object} msg 原始消息
581
+ * @returns {*} 方法执行结果
582
+ * @private
583
+ */
584
+ Drive.prototype._execMethod = async function (func, json, msg) {
585
+ var id = json.id;
586
+ var params = json.params;
587
+ var ret;
588
+
589
+ try {
590
+ ret = func(json.clientid, params, msg, id);
591
+ if (util.types.isPromise(ret)) {
592
+ ret = await ret;
593
+ }
594
+ } catch (err) {
595
+ this.log("error", "事件回调失败!", err);
596
+ }
597
+
598
+ return ret;
599
+ };
600
+
601
+ /**
602
+ * 发送方法响应
603
+ * @param {*} ret 方法执行结果
604
+ * @param {object} json 消息对象
605
+ * @param {string} topic 订阅主题
606
+ * @param {number} index 索引
607
+ * @private
608
+ */
609
+ Drive.prototype._sendMethodRes = async function (ret, json, topic, index) {
610
+ var arr_tc = this.config.topic_receive;
611
+ if (arr_tc.length > index) {
612
+ var obj = {};
613
+ var cg = this.config;
614
+ var id = json.id;
615
+
616
+ if (id) {
617
+ obj[cg.msgid] = id;
618
+ }
619
+
620
+ try {
621
+ obj[cg.method] = this.getReplyMethod(json.method);
622
+ obj[cg.result] = ret;
623
+ var topic_receive = this.getTopic(
624
+ arr_tc[index],
625
+ json.clientid,
626
+ json.params,
627
+ );
628
+ var reply_msg = this.toOut(topic_receive, obj, topic, index);
629
+ await this.send(topic_receive, reply_msg);
630
+ } catch (err) {
631
+ this.log("error", "MQTT事件响应失败!", err);
632
+ }
633
+ }
634
+ };
635
+
636
+ // /**
637
+ // * 主函数, 用于接收并处理订阅内容
638
+ // * @param {string} push_topic 推送过来的主题
639
+ // * @param {object} msg 消息正文
640
+ // * @param {string} topic 订阅的主题
641
+ // * @param {number} index 索引
642
+ // * @returns {object} 返回执行结果
643
+ // */
644
+ // Drive.prototype.main = async function (push_topic, msg, topic, index) {
645
+ // return this.handle(push_topic, msg, topic, index);
646
+ // };
647
+
648
+ // /**
649
+ // * 接收订阅消息
650
+ // * @param {object} ret 执行结果
651
+ // * @param {object} push_topic 主题
652
+ // * @param {object} msg 消息正文
653
+ // * @param {string} topic 订阅的主题
654
+ // * @param {number} index 索引
655
+ // */
656
+ // Drive.prototype.mainAfter = async function (ret, push_topic, msg, topic, index) {
657
+ // await this.message(push_topic, msg, topic, index);
658
+ // };
659
+
660
+ /**
661
+ * 获取插件
662
+ * @param {string} app 应用名称
663
+ * @param {string} name 插件名称
664
+ * @returns {object} 返回获取到的插件
665
+ */
666
+ Drive.prototype.plugin = function (app, name) {
667
+ var l = $.slash;
668
+ var app_name = app || this.config_file.between("app" + l, l);
669
+ var plugin_name = name || this.config_file.between("plugin" + l, l);
670
+ var plus;
671
+ var plugins = $.pool.plugin[app_name];
672
+ if (plugins) {
673
+ plus = plugins.get(plugin_name);
674
+ }
675
+ return plus;
676
+ };
677
+
678
+ /**
679
+ * 获取模型
680
+ * @param {string} type 模型类型
681
+ * @returns {object} 返回获取到的模型
682
+ */
683
+ Drive.prototype.getModel = function (type) {
684
+ let model = { ...this.config };
685
+ let dir = this.getDir();
686
+ let l = $.slash;
687
+ let app_name = dir.between("app" + l, l);
688
+ let plugin_name = dir.between("plugin" + l, l);
689
+ let name = dir.basename();
690
+ model.app = app_name;
691
+ model.plugin = plugin_name;
692
+ model.name = model.name || name;
693
+ return model;
694
+ };
695
+
696
+ module.exports = Drive;