@jiabaida/tools 1.0.6 → 1.0.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 (38) hide show
  1. package/dist/cjs/core/BleApiManager.js +1 -1
  2. package/dist/cjs/core/BleCmdAnalysis/BaseParamProtocol.js +1 -1
  3. package/dist/cjs/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -1
  4. package/dist/cjs/core/BleCmdAnalysis/BleCmdDD.js +1 -1
  5. package/dist/cjs/core/BleCmdAnalysis/BleCmdDDA4.js +1 -0
  6. package/dist/cjs/core/BleCmdAnalysis/readAndSetParam.js +1 -1
  7. package/dist/cjs/core/OtaUpgrade.js +1 -1
  8. package/dist/cjs/core/Queue.js +1 -0
  9. package/dist/cjs/core/mqttServer.js +1 -0
  10. package/dist/cjs/core/rsaEncrypt.js +1 -0
  11. package/dist/cjs/core/tcpServer.js +1 -0
  12. package/dist/cjs/index.js +1 -1
  13. package/dist/esm/core/BleApiManager.js +1 -1
  14. package/dist/esm/core/BleCmdAnalysis/BaseParamProtocol.js +1 -1
  15. package/dist/esm/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -1
  16. package/dist/esm/core/BleCmdAnalysis/BleCmdDD.js +1 -1
  17. package/dist/esm/core/BleCmdAnalysis/BleCmdDDA4.js +1 -0
  18. package/dist/esm/core/BleCmdAnalysis/readAndSetParam.js +1 -1
  19. package/dist/esm/core/OtaUpgrade.js +1 -1
  20. package/dist/esm/core/Queue.js +1 -0
  21. package/dist/esm/core/mqttServer.js +1 -0
  22. package/dist/esm/core/rsaEncrypt.js +1 -0
  23. package/dist/esm/core/tcpServer.js +1 -0
  24. package/dist/esm/index.js +1 -1
  25. package/package.json +4 -3
  26. package/src/core/BleApiManager.js +3 -1
  27. package/src/core/BleCmdAnalysis/BaseParamProtocol.js +71 -12
  28. package/src/core/BleCmdAnalysis/BleCmdAnalysis.js +3 -2
  29. package/src/core/BleCmdAnalysis/BleCmdDD.js +72 -13
  30. package/src/core/BleCmdAnalysis/BleCmdDDA4.js +74 -11
  31. package/src/core/BleCmdAnalysis/index.js +6 -5
  32. package/src/core/BleCmdAnalysis/readAndSetParam.js +97 -8
  33. package/src/core/OtaUpgrade.js +8 -2
  34. package/src/core/Queue.js +34 -0
  35. package/src/core/mqttServer.js +28 -9
  36. package/src/core/rsaEncrypt.js +1 -1
  37. package/src/core/tcpServer.js +303 -0
  38. package/src/index.js +5 -2
@@ -1,15 +1,15 @@
1
- import { sleep } from './BleDataProcess.js';
2
- import { decrypt } from './rsaEncrypt.js';
3
- import CryptoJS from 'crypto-js/crypto-js.js';
4
- import mqtt from 'mqtt/dist/mqtt.js';
1
+ import SHA256 from 'crypto-js/sha256';
2
+ import mqtt from 'mqtt/dist/mqtt.min.js';
5
3
  import { set_PlanCMD_DD } from './BleCmdAnalysis/BleCmdDD';
6
4
  import { getFFAA80Async, resolveFFAA80, set_PlanCMD_FFAA } from './BleCmdAnalysis/BleCmdFFAA';
7
- import { Transfer } from './Transfer.js';
8
5
  import { getCMDESInfoAsync } from './BleCmdAnalysis/BleCmdHVES.js';
6
+ import { sleep } from './BleDataProcess.js';
7
+ import { decrypt } from './rsaEncrypt.js';
8
+ import { Transfer } from './Transfer.js';
9
9
 
10
10
  // 新的MQTT服务类
11
- class MqttServer {
12
- constructor({ mqttClient = {}, MQTT_HOST = 'wx://mqtt.jiabaida.com:8083/mqtt', DELAY_TIME = 300, networkModelUrl = 'https://cloud.jiabaida.com/bluetooth/server/device/networkModel', request }) {
11
+ export class MqttServer {
12
+ constructor({ mqttClient = {}, MQTT_HOST = 'wxs://mqtt.jiabaida.com/mqtt', DELAY_TIME = 300, networkModelUrl = 'https://cloud.jiabaida.com/bluetooth/server/device/networkModel', request, store = null }) {
13
13
  this.timer = null;
14
14
  this.productKey = 'bms_wifi';
15
15
  this.is0f = false;
@@ -23,6 +23,7 @@ class MqttServer {
23
23
  this.DELAY_TIME = DELAY_TIME;
24
24
  this.networkModelUrl = networkModelUrl;
25
25
  this.request = request; // 必须传入的http请求方法
26
+ this.$store = store;
26
27
  // ...existing code...
27
28
  }
28
29
 
@@ -56,7 +57,7 @@ class MqttServer {
56
57
  connectTimeout: 4000,
57
58
  clientId,
58
59
  username,
59
- password: CryptoJS.SHA256(password).toString(),
60
+ password: SHA256(password).toString(),
60
61
  deviceId: deviceObj.deviceId,
61
62
  };
62
63
  const client = mqtt.connect(this.MQTT_HOST, options);
@@ -88,6 +89,7 @@ class MqttServer {
88
89
 
89
90
  storeMqttClient(client) {
90
91
  this.mqttClient[`${client.options.deviceId}_mqtt`] = client;
92
+ this.$store?.commit('setMqttClient', this.mqttClient);
91
93
  console.log('存储的 MQTT 客户端:', this.mqttClient);
92
94
  }
93
95
 
@@ -151,6 +153,8 @@ class MqttServer {
151
153
  }
152
154
  }
153
155
 
156
+
157
+
154
158
  async processMessageAsync(client, message) {
155
159
  const msg = JSON.parse(message);
156
160
  this.callbackId = msg.callbackId;
@@ -212,6 +216,7 @@ class MqttServer {
212
216
  if (isLast) {
213
217
  await sleep(300);
214
218
  this.mqttPublish = false;
219
+ this.$store?.commit('setMqttPublish', false);
215
220
  uni.removeStorageSync && uni.removeStorageSync(`${deviceId}_mqttPublish`);
216
221
  }
217
222
  } catch (error) {
@@ -219,10 +224,21 @@ class MqttServer {
219
224
  }
220
225
  }
221
226
 
227
+ closeMqttByDeviceId(deviceId) {
228
+ const client = this.mqttClient[`${deviceId}_mqtt`];
229
+ if (client) {
230
+ client.end(() => {
231
+ this.mqttClient[`${deviceId}_mqtt`] = null;
232
+ console.log(`MQTT 连接已关闭,设备ID: ${deviceId}`);
233
+ });
234
+ }
235
+ }
236
+
222
237
  handleMqttClose(client, res) {
223
238
  console.log('MQTT 连接关闭', res, client);
224
239
  client.end(() => {
225
240
  this.mqttClient[`${client.options.deviceId}_mqtt`] = null;
241
+ this.$store?.commit('setMqttClient', this.mqttClient);
226
242
  });
227
243
  }
228
244
 
@@ -243,6 +259,7 @@ class MqttServer {
243
259
  if (this.publishObj.isLast) {
244
260
  await sleep(300);
245
261
  this.mqttPublish = false;
262
+ this.$store?.commit('setMqttPublish', false);
246
263
  uni.removeStorageSync && uni.removeStorageSync(`${this.publishObj.deviceId}_mqttPublish`);
247
264
  }
248
265
  }
@@ -266,6 +283,7 @@ class MqttServer {
266
283
  async writePublishInfoCmd(values) {
267
284
  clearTimeout(this.timer);
268
285
  this.mqttPublish = true;
286
+ this.$store?.commit('setMqttPublish', true);
269
287
  this.mqttCode = values[2];
270
288
  let res = null;
271
289
  // 下发指令逻辑
@@ -289,8 +307,9 @@ class MqttServer {
289
307
  }
290
308
  this.timer = setTimeout(() => {
291
309
  this.mqttPublish = false;
310
+ this.$store?.commit('setMqttPublish', false);
292
311
  }, 30000);
293
312
  }
294
313
  }
295
314
 
296
- export default MqttServer;
315
+ // export default MqttServer;
@@ -1,4 +1,4 @@
1
- import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
1
+ import JSEncrypt from 'jsencrypt'
2
2
 
3
3
  // 密钥对生成 http://web.chacuo.net/netrsakeypair
4
4
 
@@ -0,0 +1,303 @@
1
+ // import store from '@/store/index';
2
+ import {
3
+ reactive
4
+ } from "vue";
5
+ import { set_PlanCMD_DD } from './BleCmdAnalysis/BleCmdDD';
6
+ import { set_PlanCMD_FFAA } from './BleCmdAnalysis/BleCmdFFAA';
7
+ import { getCMDESInfoAsync } from './BleCmdAnalysis/BleCmdHVES.js';
8
+ import { sleep } from './BleDataProcess.js';
9
+ import Queue from './Queue.js';
10
+ import { Transfer } from './Transfer.js';
11
+ export const tcpSend = reactive({
12
+ isSending: false, //是否在下发平台指令
13
+ isLast: false,
14
+ code: null,
15
+ hasHeartbeat: false,
16
+ tcpClose: false,
17
+ devices: {}
18
+ })
19
+ // / 创建一个队列来存储接收到的消息
20
+ const messageQueue = new Queue();
21
+ let timer = null
22
+ export const tcpServer = {
23
+ version: '2.8.2', // 每次上传需要手动修改此 版本号
24
+ socketOpen: false, //是否建立连接
25
+ macAddr: '',
26
+ txnNo: '',
27
+ baseDelay: 1000, // 初始重试延迟(毫秒)
28
+ maxDelay: 60 * 1000, // 最大重试延迟(毫秒)
29
+ retryCount: 0, // 重试次数
30
+ url: {
31
+ address: 'cloud.jiabaida.com',
32
+ port: 10241
33
+ },
34
+ url1: {
35
+ address: '192.168.80.36',
36
+ port: 10240
37
+ },
38
+ timers: {},
39
+ heartBeatTimers: {},
40
+ tcpSockets: {},
41
+ isRetryings: {},
42
+ socketOpens: {},
43
+ async initTCPConnection(macAddr, deviceId) {
44
+ console.log('macAddr: init-------tcp', macAddr, deviceId);
45
+ return new Promise((resolve, reject) => {
46
+ try {
47
+ tcpSend.devices[macAddr] = {
48
+ macAddr,
49
+ deviceId
50
+ }
51
+ this.tcpSockets[`${deviceId}_socket`] = wx.createTCPSocket();
52
+ console.log('this.tcpSockets[`${deviceId}_socket`]: ', this.tcpSockets[`${deviceId}_socket`]);
53
+ this.tcpSockets[`${deviceId}_socket`].connect(this.url);
54
+ this.tcpSockets[`${deviceId}_socket`].onConnect(() => {
55
+ this.listenerConnect(macAddr, deviceId)
56
+ resolve(true)
57
+ });
58
+
59
+ this.tcpSockets[`${deviceId}_socket`].onMessage((message) => {
60
+ console.log('接收到消息:', message);
61
+ // 处理接收到的消息
62
+ // 将buffer转为常规数组 十六进制
63
+ const intArr = Array.prototype.map.call(
64
+ new Uint8Array(message.message),
65
+ function (bit) {
66
+ return bit;
67
+ }
68
+ );
69
+ // 将十六进制转为对应的字符
70
+ let valueString = String.fromCharCode(...intArr)
71
+ console.log(valueString, 'valueString');
72
+ // messageQueue.enqueue(valueString);
73
+ // this.processQueue()
74
+ this.processMessageAsync(valueString)
75
+ });
76
+
77
+ this.tcpSockets[`${deviceId}_socket`].onError((error) => {
78
+ this.listenerError(macAddr, deviceId, error)
79
+ reject(error)
80
+ });
81
+
82
+ this.tcpSockets[`${deviceId}_socket`].onClose(this.listenerClose(deviceId));
83
+ } catch (error) {
84
+ console.error('error: tcp连接失败', error);
85
+ reject(error)
86
+ }
87
+ })
88
+ },
89
+ listenerConnect(macAddr, deviceId) {
90
+ this.socketOpens[`open_${deviceId}`] = true
91
+ this.isRetryings[`retry_${deviceId}`] = false
92
+ console.log('TCP 连接已建立');
93
+ clearInterval(this.timers[`timer_${deviceId}`])
94
+ this.timers[`timer_${deviceId}`] = null
95
+ // 连接建立后,开始发送心跳包
96
+ this.sendHeartbeat(macAddr, deviceId);
97
+ },
98
+ listenerError(macAddr, deviceId, error) {
99
+ this.socketOpens[`open_${deviceId}`] = false
100
+ console.log('TCP 连接错误:', deviceId, error);
101
+ this.stopHeartBeat(deviceId)
102
+ if (!this.isRetryings[`retry_${deviceId}`]) {
103
+ this.retryCount = 0
104
+ // 重连
105
+ this.reConnect(macAddr, deviceId, true)
106
+ }
107
+ },
108
+ listenerClose(deviceId) {
109
+ this.socketOpens[`open_${deviceId}`] = false
110
+ console.log('TCP 连接已关闭');
111
+ },
112
+ // 关闭tcp连接
113
+ closeTcpSocket(deviceId) {
114
+ try {
115
+ clearInterval(this.timers[`timer_${deviceId}`])
116
+ this.timers[`timer_${deviceId}`] = null
117
+ if (this.tcpSockets[`${deviceId}_socket`]) {
118
+ this.socketOpens[`open_${deviceId}`] = false
119
+ this.stopHeartBeat(deviceId)
120
+ this.tcpSockets[`${deviceId}_socket`].offMessage()
121
+ this.tcpSockets[`${deviceId}_socket`].offConnect()
122
+ this.tcpSockets[`${deviceId}_socket`].offClose()
123
+ this.tcpSockets[`${deviceId}_socket`].offError()
124
+ this.tcpSockets[`${deviceId}_socket`].close()
125
+ this.tcpSockets[`${deviceId}_socket`] = null
126
+ }
127
+ } catch (error) {
128
+ console.error('error: closeTcpSocket', error);
129
+ }
130
+ },
131
+ async reConnect(macAddr, deviceId, closeSocket = false) {
132
+ console.log('重连 this.macAddr', macAddr);
133
+ this.isRetryings[`retry_${deviceId}`] = true
134
+ // 关闭旧的连接再重连
135
+ if (closeSocket) this.tcpSockets[`${deviceId}_socket`].close()
136
+ this.tcpSockets[`${deviceId}_socket`].connect(this.url);
137
+ const delay = Math.min(this.baseDelay * Math.pow(2, this.retryCount), this.maxDelay);
138
+ console.log(`准备 ${delay}ms 后重试...`);
139
+ this.timers[`timer_${deviceId}`] = setTimeout(() => {
140
+ this.reConnect(macAddr, deviceId);
141
+ }, delay);
142
+ this.retryCount++
143
+ },
144
+ sendHeartbeat(macAddr, deviceId) {
145
+ let tokenStr = uni.getStorageSync('token')
146
+ let token = tokenStr.replace('Bearer ', '')
147
+ const heartbeatMsg = {
148
+ command: 96, //业务操作码,96代表心跳包
149
+ data: {
150
+ token,
151
+ appVersion: "xiaoxiang:" + this.version, //小程序版本号
152
+ macAddr,
153
+ },
154
+ txnNo: +new Date(), //当前时间戳
155
+ isAnonymous: 0, //是否匿名登录
156
+ };
157
+ console.log('heartbeatMsg: ', heartbeatMsg);
158
+ tcpSend.hasHeartbeat = false
159
+ this.tcpSockets[`${deviceId}_socket`].write(JSON.stringify(heartbeatMsg));
160
+ this.heartBeatTimers[`heartTimer_${deviceId}`] = setInterval(() => {
161
+ heartbeatMsg.txnNo = +new Date() //当前时间戳
162
+ //##console.log(heartbeatMsg, 'heartbeatMsg');
163
+ tcpSend.hasHeartbeat = false
164
+ this.tcpSockets[`${deviceId}_socket`].write(JSON.stringify(heartbeatMsg));
165
+ }, 30000); // 每5秒发送一次心跳包
166
+ },
167
+ // 清除心跳上报计时器
168
+ stopHeartBeat(deviceId) {
169
+ if (this.heartBeatTimers[`heartTimer_${deviceId}`]) {
170
+ clearInterval(this.heartBeatTimers[`heartTimer_${deviceId}`]);
171
+ this.heartBeatTimers[`heartTimer_${deviceId}`] = null;
172
+ }
173
+ },
174
+ //上报基础 信息
175
+ sendReportData(data) {
176
+ const reportData = {
177
+ command: 999, //业务操作码,999代表上报
178
+ data: {
179
+ value: data.value,
180
+ cmdCode: 'jbd0F',
181
+ bluetoothName: data.bluetoothName,
182
+ },
183
+ macAddr: data.macAddr,
184
+ txnNo: +new Date(), //当前时间戳
185
+ };
186
+ console.log(reportData, 'reportData111上报基础数据');
187
+ this.tcpSockets[`${data.deviceId}_socket`].write(JSON.stringify(reportData));
188
+ },
189
+ // 执行完平台下发的指令后上报数据
190
+ sendWriteReportData(data, deviceId) {
191
+ console.warn('执行后上报数据data: ', data);
192
+ const reportData = {
193
+ command: 121, //业务操作码,代表执行上报
194
+ data: {
195
+ macAddr: this.macAddr,
196
+ content: data,
197
+ },
198
+ txnNo: this.txnNo, //callbackId
199
+ };
200
+ //##console.log(reportData, 'WriteReportData执行指令后上报数据');
201
+ this.tcpSockets[`${deviceId}_socket`].write(JSON.stringify(reportData));
202
+ if (tcpSend.isLast) {
203
+ tcpSend.isSending = false
204
+ }
205
+ },
206
+ // 处理队列中的消息
207
+ processQueue() {
208
+ if (!tcpSend.isSending) {
209
+ this.processNextMessage();
210
+ }
211
+ },
212
+ async processNextMessage() {
213
+ //##console.log('messageQueue-------', messageQueue);
214
+
215
+ if (!messageQueue.isEmpty()) {
216
+ const message = messageQueue.dequeue();
217
+ //##console.log('Processing:', message);
218
+ // 异步处理消息
219
+ this.processMessageAsync(message).then(() => {
220
+ this.processNextMessage();
221
+ });
222
+ } else {
223
+ await sleep(300)
224
+ tcpSend.isSending = false;
225
+ //##console.log('tcpSend.isSending发送完成', tcpSend.isSending);
226
+ }
227
+ },
228
+ async processMessageAsync(message) {
229
+ clearTimeout(timer)
230
+ // 假设这里是异步操作,例如写入数据库
231
+ return new Promise(async (resolve) => {
232
+ try {
233
+ console.log('Message processed:', message);
234
+ let msgObj = JSON.parse(message)
235
+ console.warn('----------msgObj后台下发的指令: -----------', msgObj);
236
+ // 为120,即接收到后台下发的指令
237
+ if (msgObj.command == 120) {
238
+ let value = msgObj.data.content
239
+ if (!value) return
240
+
241
+ // 使用正则表达式将字符串两两分隔为数组
242
+ let resultArray = value.match(/.{1,2}/g);
243
+ console.log('resultArray: ', resultArray);
244
+ // 给蓝牙设备发送指令
245
+ this.macAddr = msgObj.data.macAddr
246
+ let deviceId = null
247
+ for (let key in tcpSend.devices) {
248
+ if (tcpSend.devices[key].macAddr == this.macAddr) {
249
+ deviceId = tcpSend.devices[key].deviceId
250
+ }
251
+ }
252
+ console.log('deviceId: ', deviceId);
253
+ this.txnNo = msgObj.txnNo
254
+ tcpSend.isLast = msgObj.isLast
255
+ tcpSend.isSending = true
256
+ tcpSend.code = resultArray[2]
257
+ // 向蓝牙设备发送一个0x00的16进制数据,读取指令
258
+ let length = resultArray.length
259
+ const buffer = new ArrayBuffer(length);
260
+ const dataView = new DataView(buffer);
261
+ resultArray.forEach((el, index) => {
262
+ // 循环,取每一个十六进制值 添加到buffer
263
+ dataView.setUint8(index, '0x' + el);
264
+ })
265
+ console.log(buffer, "读取指令-----------------------");
266
+ // store.commit('setPassthroughType', 1);// 设置类型为 被动回复1
267
+ // BLE.sendMsgToKey(buffer, deviceId)
268
+
269
+ // this.mqttCode = resultArray[2];
270
+ let res = null;
271
+ // 下发指令逻辑
272
+ if (resultArray[0]?.toUpperCase() === 'FF' && resultArray[1]?.toUpperCase() === 'AA') {
273
+ res = await set_PlanCMD_FFAA(deviceId, resultArray.join(''));
274
+ } else if (resultArray[1]?.toUpperCase() === '78' || resultArray[1]?.toUpperCase() === '50') {
275
+ res = await getCMDESInfoAsync(deviceId, resultArray.join(''));
276
+ } else {
277
+ // DD
278
+ res = await set_PlanCMD_DD(deviceId, resultArray.join(''));
279
+ }
280
+ const content = res?.data || []
281
+ let code = Transfer.decimalToHex(content[1]);
282
+ if (content[0] == 0xff && content[1] == 0xaa) {
283
+ code = Transfer.decimalToHex(content[2]);
284
+ }
285
+ console.log('code: 回复的code', code);
286
+ if (code.toUpperCase() == tcpSend?.code?.toUpperCase()) {
287
+ this.sendWriteReportData(content, deviceId)
288
+ }
289
+ } else if (msgObj.command == 97) {
290
+ tcpSend.hasHeartbeat = true
291
+ }
292
+ // 超时 30s 未收到指令反馈 认为指令发送失败
293
+ timer = setTimeout(() => {
294
+ tcpSend.isSending = false
295
+ }, 30000)
296
+ resolve(true);
297
+ } catch (error) {
298
+ console.log('error: ', error);
299
+
300
+ }
301
+ });
302
+ },
303
+ }
package/src/index.js CHANGED
@@ -2,10 +2,13 @@
2
2
  export * from './core/array';
3
3
  export * from './core/BleApiManager';
4
4
  export * from './core/BleCmdAnalysis/index';
5
+ export * from './core/BleDataProcess';
5
6
  export * from './core/commonfun';
7
+ export * from './core/dataJson/index.js';
6
8
  export * from './core/keyAndPwdManager';
9
+ export * from './core/mqttServer.js';
7
10
  export * from './core/OtaUpgrade';
11
+ export * from './core/rsaEncrypt';
12
+ export * from './core/tcpServer.js';
8
13
  export * from './core/TelinkApi';
9
14
  export * from './core/Transfer';
10
- export * from './core/BleDataProcess'
11
- export * from './core/dataJson/index.js'