mm_os 4.3.7 → 5.0.1

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