@jiabaida/tools 1.0.0 → 1.0.2

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 (57) hide show
  1. package/dist/cjs/core/BleApiManager.js +1 -1
  2. package/dist/cjs/core/BleCmdAnalysis/BaseParamProtocol.js +1 -0
  3. package/dist/cjs/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -0
  4. package/dist/cjs/core/BleCmdAnalysis/BleCmdDD.js +1 -0
  5. package/dist/cjs/core/BleCmdAnalysis/BleCmdFFAA.js +1 -0
  6. package/dist/cjs/core/BleCmdAnalysis/BleCmdHVES.js +1 -0
  7. package/dist/cjs/core/BleCmdAnalysis/ESHostProtocol.js +1 -0
  8. package/dist/cjs/core/BleCmdAnalysis/readAndSetParam.js +1 -0
  9. package/dist/cjs/core/BleCmdAnalysis.js +1 -0
  10. package/dist/cjs/core/BleDataProcess.js +1 -0
  11. package/dist/cjs/core/OtaUpgrade.js +1 -0
  12. package/dist/cjs/core/TelinkApi.js +1 -0
  13. package/dist/cjs/core/Transfer.js +1 -0
  14. package/dist/cjs/core/commonfun.js +1 -1
  15. package/dist/cjs/core/dataJson/baseParamsJson.js +1 -0
  16. package/dist/cjs/core/keyAndPwdManager.js +1 -0
  17. package/dist/cjs/index.js +1 -1
  18. package/dist/esm/core/BleApiManager.js +1 -1
  19. package/dist/esm/core/BleCmdAnalysis/BaseParamProtocol.js +1 -0
  20. package/dist/esm/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -0
  21. package/dist/esm/core/BleCmdAnalysis/BleCmdDD.js +1 -0
  22. package/dist/esm/core/BleCmdAnalysis/BleCmdFFAA.js +1 -0
  23. package/dist/esm/core/BleCmdAnalysis/BleCmdHVES.js +1 -0
  24. package/dist/esm/core/BleCmdAnalysis/ESHostProtocol.js +1 -0
  25. package/dist/esm/core/BleCmdAnalysis/readAndSetParam.js +1 -0
  26. package/dist/esm/core/BleCmdAnalysis.js +1 -0
  27. package/dist/esm/core/BleDataProcess.js +1 -0
  28. package/dist/esm/core/OtaUpgrade.js +1 -0
  29. package/dist/esm/core/TelinkApi.js +1 -0
  30. package/dist/esm/core/Transfer.js +1 -0
  31. package/dist/esm/core/commonfun.js +1 -1
  32. package/dist/esm/core/dataJson/baseParamsJson.js +1 -0
  33. package/dist/esm/core/keyAndPwdManager.js +1 -0
  34. package/dist/esm/index.js +1 -1
  35. package/package.json +13 -3
  36. package/src/core/BleApiManager.js +487 -0
  37. package/src/core/BleCmdAnalysis/BaseParamProtocol.js +651 -0
  38. package/src/core/BleCmdAnalysis/BleCmdAnalysis.js +222 -0
  39. package/src/core/BleCmdAnalysis/BleCmdDD.js +1214 -0
  40. package/src/core/BleCmdAnalysis/BleCmdDDA4.js +762 -0
  41. package/src/core/BleCmdAnalysis/BleCmdFFAA.js +407 -0
  42. package/src/core/BleCmdAnalysis/BleCmdHVES.js +1222 -0
  43. package/src/core/BleCmdAnalysis/ESHostProtocol.js +829 -0
  44. package/src/core/BleCmdAnalysis/index.js +7 -0
  45. package/src/core/BleCmdAnalysis/readAndSetParam.js +288 -0
  46. package/src/core/BleDataProcess.js +355 -0
  47. package/src/core/OtaUpgrade.js +338 -0
  48. package/src/core/TelinkApi.js +73 -0
  49. package/src/core/Transfer.js +516 -0
  50. package/src/core/array.js +10 -0
  51. package/src/core/commonfun.js +87 -0
  52. package/src/core/dataJson/baseParamsJson.js +754 -0
  53. package/src/core/dataJson/index.js +1 -0
  54. package/src/core/keyAndPwdManager.js +346 -0
  55. package/src/core/mqttServer.js +296 -0
  56. package/src/core/rsaEncrypt.js +45 -0
  57. package/src/index.js +11 -0
@@ -0,0 +1,487 @@
1
+ import { eventBus, getOS, inArray } from './commonfun'; // 导入eventBus
2
+ import { ab2decimalArr } from './BleDataProcess';
3
+ import { ref, reactive } from 'vue';
4
+ const serviceId = '0000FF00-0000-1000-8000-00805F9B34FB';
5
+ const UUID_READ = '0000FF01-0000-1000-8000-00805F9B34FB';
6
+ const UUID_WRITE = '0000FF02-0000-1000-8000-00805F9B34FB';
7
+
8
+ const bluetoothAdapterState = ref({
9
+ available: false,
10
+ discovering: false,
11
+ });
12
+ // #region 处理广播的设备信息
13
+ /**
14
+ * 处理广播的设备信息
15
+ * @param {*} device
16
+ * @returns 处理后的设备信息
17
+ */
18
+ const enhanceDevice = (device) => {
19
+ const adv = device?.advertisData;
20
+ if (!adv) return null;
21
+ if (adv) {
22
+ const advHex = Array.prototype.map
23
+ .call(new Uint8Array(adv), (o) => ('00' + o.toString(16)).slice(-2))
24
+ .join('')
25
+ .toUpperCase();
26
+
27
+ let macAddr = advHex.slice(0, 12).toUpperCase();
28
+ let arr = macAddr.match(/(.{2})/g);
29
+ const flag = macAddr.slice(-4);
30
+ if (flag == 'C1A4' || flag == 'C2A5' || flag == 'C2A8') arr.reverse();
31
+ macAddr = arr.join(':');
32
+ device['hasFound'] = true;
33
+ const moduleType = advHex.slice(12, 16);
34
+ const soc = advHex.slice(16, 18);
35
+ const productType = advHex.slice(18, 20);
36
+ const protocolVersion = advHex.slice(20, 22);
37
+ const appkeyStatus = advHex.slice(22, 24);
38
+ const broadcastLen = advHex.length / 2;
39
+ const isNewAppKey = advHex.length >= 24 //内容长度大于24位则是新appkey蓝牙设备
40
+ device = { ...device, macAddr, moduleType, soc, productType, advHex, protocolVersion, appkeyStatus, broadcastLen, isNewAppKey };
41
+ }
42
+ return device;
43
+ }
44
+ // #region 初始化蓝牙
45
+ /** 初始化蓝牙 */
46
+ export const initBle = async () => {
47
+ const checkBluetoothStatus = async () => {
48
+ return new Promise((resolve, reject) => {
49
+ uni.openBluetoothAdapter({
50
+ success: async (res) => {
51
+ console.log('openBluetoothAdapter success', res);
52
+ resolve(res);
53
+ try {
54
+ // await startDevicesDiscovery(false);
55
+ // stopBluetoothDevicesDiscovery();
56
+ onBluetoothDeviceFound();
57
+ onBLECharacteristicValueChange();
58
+ onBLEConnectionStateChange();
59
+ onBluetoothAdapterStateChange()
60
+ } catch (error) {
61
+ console.log('error: ', error);
62
+ reject(error);
63
+ }
64
+ },
65
+ fail: (err) => {
66
+ console.log('openBluetoothAdapter fail', err);
67
+ reject(err);
68
+ },
69
+ });
70
+ });
71
+ };
72
+ const checkLocationStatus = async () => {
73
+ // 创建超时Promise
74
+ const timeoutPromise = new Promise((resolve, reject) => {
75
+ setTimeout(() => {
76
+ reject(new Error('网络信号差或连接异常,请检查网络情况'));
77
+ }, 10000); // 10秒超时
78
+ });
79
+ // 创建位置获取Promise
80
+ const locationPromise = new Promise((resolve, reject) => {
81
+ uni.getLocation({
82
+ type: 'wgs84',
83
+ success: (res) => {
84
+ console.log('位置信息-----------', res);
85
+ resolve(res);
86
+ },
87
+ fail: (err) => {
88
+ console.log('位置信息err', err);
89
+ reject(err);
90
+ },
91
+ });
92
+ });
93
+ // 使用Promise.race实现超时控制
94
+ Promise.race([locationPromise, timeoutPromise])
95
+ .then((res) => {
96
+ // 成功获取位置信息
97
+ checkBluetoothStatus();
98
+ })
99
+ .catch((err) => {
100
+ console.log('位置获取失败或超时:', err);
101
+ Promise.reject({
102
+ code: 1,
103
+ // message: '请检查手机位置是否开启',
104
+ });
105
+ });
106
+ };
107
+ try {
108
+ const { isAndroid } = getOS();
109
+ if (isAndroid) {
110
+ checkLocationStatus();
111
+ } else {
112
+ checkBluetoothStatus();
113
+ }
114
+ } catch (error) {
115
+ console.error('初始化蓝牙失败:', error);
116
+ Promise.reject({
117
+ code: error.code || error.errCode || -1,
118
+ });
119
+ }
120
+ };
121
+ // #region 获取蓝牙适配器状态
122
+ /** 获取蓝牙适配器状态 */
123
+ export const getBluetoothAdapterState = async () => {
124
+ return new Promise((resolve, reject) => {
125
+ uni.getBluetoothAdapterState({
126
+ success: (res) => {
127
+ console.log('getBluetoothAdapterState success', res);
128
+ resolve(res);
129
+ },
130
+ fail: (err) => {
131
+ console.log('getBluetoothAdapterState fail', err);
132
+ reject(err);
133
+ },
134
+ });
135
+ });
136
+ };
137
+ // #region 开始搜索蓝牙设备
138
+ /** 开始搜索蓝牙设备
139
+ * @param {boolean} allowDuplicatesKey 是否允许重复设备
140
+ * @returns
141
+ */
142
+ export const startDevicesDiscovery = async (allowDuplicatesKey = true) => {
143
+ return new Promise((resolve, reject) => {
144
+ // if (!bluetoothAdapterState.value.available) {
145
+ // reject(new Error('蓝牙适配器未开启'));
146
+ // return;
147
+ // }
148
+ if (bluetoothAdapterState.value.discovering) {
149
+ reject(new Error('蓝牙设备搜索已在进行中'));
150
+ return;
151
+ }
152
+ uni.startBluetoothDevicesDiscovery({
153
+ services: [serviceId],
154
+ allowDuplicatesKey,
155
+ success: async (res) => {
156
+ console.log('广播设备 success', res);
157
+ resolve(res);
158
+ },
159
+ fail: (err) => {
160
+ console.log('广播设备 fail', err);
161
+ reject(err);
162
+ },
163
+ });
164
+ });
165
+ };
166
+ // #region 停止搜索蓝牙设备
167
+ /**停止搜索蓝牙设备 */
168
+ export const stopBluetoothDevicesDiscovery = async () => {
169
+ return new Promise((resolve, reject) => {
170
+ uni.stopBluetoothDevicesDiscovery({
171
+ success: (res) => {
172
+ console.log('停止广播设备 success', res);
173
+ resolve(res);
174
+ },
175
+ fail: (err) => {
176
+ console.log('停止广播设备 fail', err);
177
+ reject(err);
178
+ },
179
+ complete: (res) => {
180
+ console.log('停止广播设备 取消订阅');
181
+ eventBus.off('setBluetoothDeviceFound');
182
+ },
183
+ });
184
+ });
185
+ };
186
+ // #region 监听搜索到的设备列表
187
+ /**监听搜索到的设备 */
188
+ export const onBluetoothDeviceFound = async () => {
189
+ uni.onBluetoothDeviceFound((characteristic) => {
190
+ console.log('setBluetoothDeviceFound', characteristic);
191
+ const device = enhanceDevice(characteristic.devices[0]);
192
+ if (!device) return;
193
+ // 触发事件总线事件
194
+ eventBus.emit('setBluetoothDeviceFound', device);
195
+ });
196
+ };
197
+ // #region 处理搜索到的设备并监听
198
+ /** 处理搜索到的设备并监听 */
199
+ export const onFoundDevice = (callback) => {
200
+ eventBus.on('setBluetoothDeviceFound', callback);
201
+ };
202
+
203
+
204
+ // #region 监听蓝牙适配器状态变化
205
+ /** 监听蓝牙适配器状态变化*/
206
+ export const onBluetoothAdapterStateChange = async () => {
207
+ uni.onBluetoothAdapterStateChange((res) => {
208
+ console.log('onBluetoothAdapterStateChange监听蓝牙适配器变化', res);
209
+ bluetoothAdapterState.value = res;
210
+ });
211
+ };
212
+
213
+
214
+
215
+ // #region 监听蓝牙设备特征值变化
216
+ /** 监听蓝牙设备特征值变化*/
217
+ export const onBLECharacteristicValueChange = async () => {
218
+ uni.onBLECharacteristicValueChange((characteristic) => {
219
+ const decimalArr = ab2decimalArr(characteristic.value);
220
+ console.warn('decimalArr: 监听到的回复-------------------', decimalArr);
221
+ // 触发事件总线事件
222
+ eventBus.emit('setBleChangedCharacteristicValue', characteristic);
223
+ });
224
+ };
225
+ // #region 监听蓝牙设备连接状态变化
226
+ /** 监听蓝牙设备连接状态变化*/
227
+ export const onBLEConnectionStateChange = async () => {
228
+ uni.onBLEConnectionStateChange((characteristic) => {
229
+ console.log('onBLEConnectionStateChange', characteristic);
230
+ // 触发事件总线事件
231
+ eventBus.emit('setBleChangedConnectionState', characteristic);
232
+ });
233
+ };
234
+
235
+ // #region 处理搜索到的设备并监听
236
+ /** 处理搜索到的设备并监听 */
237
+ export const onBleChangedConnectionState = (callback) => {
238
+ eventBus.on('setBleChangedConnectionState', callback);
239
+ };
240
+
241
+
242
+ // #region 连接蓝牙设备
243
+ /** 连接蓝牙设备 */
244
+ export const createBLEConnection = async (deviceId, timeout = 10000) => {
245
+ return new Promise((resolve, reject) => {
246
+ console.log(deviceId, '点击的设备信息');
247
+ // 连接蓝牙
248
+ uni.createBLEConnection({
249
+ deviceId: deviceId,
250
+ timeout,
251
+ success: (res) => {
252
+ console.log(res, '连接成功');
253
+ resolve(true);
254
+ },
255
+ fail: (err) => {
256
+ console.log(err, 'Connection');
257
+ let code = err.code || err.errCode;
258
+ if (code == -1) {
259
+ resolve(true);
260
+ } else {
261
+ // 错误信息提示
262
+ reject(err);
263
+ }
264
+ },
265
+ });
266
+ });
267
+ };
268
+ const withRetry = async (asyncOperation, maxRetries = 20, retryInterval = 100, type) => {
269
+ return new Promise((resolve, reject) => {
270
+ let retryCount = 0;
271
+ const attempt = async () => {
272
+ try {
273
+ const result = await asyncOperation();
274
+ resolve(result);
275
+ } catch (error) {
276
+ if (retryCount >= maxRetries) {
277
+ reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));
278
+ return;
279
+ }
280
+ retryCount++;
281
+ console.warn(`${type}失败,第${retryCount}次重试:`, error.message);
282
+ setTimeout(attempt, retryInterval);
283
+ }
284
+ };
285
+ attempt();
286
+ });
287
+ };
288
+ // #region 获取蓝牙服务
289
+ /** 获取蓝牙服务 */
290
+ export const getBLEDeviceServices = (deviceId) => {
291
+ // 使用通用重试函数封装操作
292
+ return withRetry(
293
+ async () => {
294
+ const res = await new Promise((resolve, reject) => {
295
+ uni.getBLEDeviceServices({
296
+ deviceId,
297
+ success: resolve,
298
+ fail: reject,
299
+ });
300
+ });
301
+ console.log('获取蓝牙服务成功:', res);
302
+ if (res.services.length === 0) {
303
+ throw new Error('未找到蓝牙服务');
304
+ }
305
+ // 假设我们需要获取第一个serviceId
306
+ await getBLEDeviceCharacteristics(deviceId);
307
+ return res.services;
308
+ },
309
+ 20, // 最大重试次数
310
+ 100,
311
+ '获取蓝牙服务'
312
+ ); // 重试间隔
313
+ };
314
+ // #region 获取蓝牙特征值
315
+ /** 获取蓝牙特征值 */
316
+ export const getBLEDeviceCharacteristics = async (deviceId) => {
317
+ // 使用通用重试函数封装操作
318
+ return withRetry(
319
+ async () => {
320
+ const res = await new Promise((resolve, reject) => {
321
+ uni.getBLEDeviceCharacteristics({
322
+ deviceId,
323
+ serviceId: serviceId,
324
+ success: resolve,
325
+ fail: reject,
326
+ });
327
+ });
328
+
329
+ console.log('获取特征值成功:', res);
330
+ return res.characteristics;
331
+ },
332
+ 20, // 最大重试次数
333
+ 100,
334
+ '获取蓝牙特征值'
335
+ ); // 重试间隔
336
+ };
337
+ // #region 订阅特征值
338
+ /** 订阅特征值 */
339
+ export const notify = async (deviceId) => {
340
+ return new Promise((resolve, reject) => {
341
+ uni.notifyBLECharacteristicValueChange({
342
+ deviceId,
343
+ serviceId: serviceId,
344
+ characteristicId: UUID_READ,
345
+ state: true,
346
+ success: (res) => {
347
+ console.log('订阅===========', res);
348
+ resolve(res);
349
+ },
350
+ fail: reject,
351
+ });
352
+ });
353
+ };
354
+ // #region 断开蓝牙连接
355
+ /** 断开蓝牙连接 */
356
+ export const disConnect = (deviceId) => {
357
+ return new Promise((resolve, reject) => {
358
+ uni.closeBLEConnection({
359
+ deviceId,
360
+ success: (res) => {
361
+ resolve(res);
362
+ console.log(res, '断开连接成功');
363
+ },
364
+ fail: (err) => {
365
+ reject(err);
366
+ console.log(err, 'err 断开连接');
367
+ },
368
+ });
369
+ });
370
+ };
371
+ // #region 连接蓝牙并获取服务特征订阅
372
+ /** 连接蓝牙设备
373
+ * 获取特征值并订阅
374
+ * @param {string} deviceId 设备id
375
+ * @returns
376
+ */
377
+ export const connectAsync = async (deviceId, timeout = 10000) => {
378
+ return new Promise(async (resolve, reject) => {
379
+ try {
380
+ await createBLEConnection(deviceId, timeout);
381
+ await getBLEDeviceServices(deviceId);
382
+ await notify(deviceId);
383
+ resolve(true);
384
+ } catch (error) {
385
+ console.log('error: ', error);
386
+ reject(error);
387
+ }
388
+ });
389
+ };
390
+
391
+ // #region 安卓扫码直连,苹果广播5秒
392
+ /**
393
+ * 安卓扫码直连,苹果广播5秒
394
+ */
395
+ export const scanHandle = (historyConnectedList = [], connectFn = (device) => { }) => {
396
+ // 调起条码扫描
397
+ uni.scanCode({
398
+ scanType: ['barCode', 'qrCode'],
399
+ success: async ({ result }) => {
400
+ console.log('扫描内容: ' + result);
401
+ let searchKey = result;
402
+ try {
403
+ // MAC地址格式化工具函数
404
+ const formatMacAddress = (mac) => {
405
+ return mac
406
+ .replace(/(.{2})/g, '$1:')
407
+ .slice(0, -1)
408
+ .toUpperCase();
409
+ };
410
+ // // 判断result是否为mac地址;
411
+ let isMac = false;
412
+ if (result.includes('?qrCodeInfo=')) {
413
+ searchKey = result.split('?qrCodeInfo=')[1];
414
+ // this.searchKey = result;
415
+ if (searchKey.includes(':')) {
416
+ searchKey = searchKey.slice(-17).toUpperCase();
417
+ isMac = true;
418
+ } else {
419
+ // 截取最后12位,每两位加一个冒号,去掉最后一个冒号
420
+ searchKey = searchKey.slice(-12);
421
+ searchKey = formatMacAddress(searchKey);
422
+ isMac = true;
423
+ }
424
+ } else {
425
+ if (result.length === 17 && result.includes(':')) {
426
+ searchKey = result.toUpperCase();
427
+ isMac = true;
428
+ } else if (result.length === 12) {
429
+ searchKey = formatMacAddress(result);
430
+ isMac = true;
431
+ }
432
+ }
433
+
434
+ const { isAndroid } = getOS();
435
+ // 检查历史连接列表是否已包含该设备
436
+ const matchedHistoryDevice = historyConnectedList.find((item) => item.macAddr == searchKey);
437
+ if (matchedHistoryDevice) {
438
+ connectFn(matchedHistoryDevice);
439
+ return;
440
+ }
441
+ // 安卓机且扫码内容是mac地址直连,苹果机广播五秒连接
442
+ if (isAndroid && isMac) {
443
+ connectFn({
444
+ deviceId: searchKey,
445
+ macAddr: searchKey,
446
+ name: searchKey,
447
+ });
448
+ } else {
449
+ foundScanDevice(searchKey, connectFn);
450
+ }
451
+ } catch (error) {
452
+ console.log(error);
453
+ }
454
+ },
455
+ });
456
+ };
457
+ // #region 广播5秒
458
+ export const foundScanDevice = async (result, connectFn) => {
459
+ const deviceList = [];
460
+ await startDevicesDiscovery();
461
+ onFoundDevice((device) => {
462
+ deviceList.push(device)
463
+ const findDevice = device.macAddr === result || device.name === result;
464
+ if (findDevice) {
465
+ if (scanTimeout) {
466
+ clearTimeout(scanTimeout);
467
+ scanTimeout = null;
468
+ }
469
+ uni.stopBluetoothDevicesDiscovery();
470
+ connectFn(findDevice);
471
+ } else {
472
+ console.log('未找到设备,继续搜索中...');
473
+ }
474
+ })
475
+ let scanTimeout = setTimeout(async () => {
476
+ try {
477
+ // 五秒后停止搜索且关闭轮询器
478
+ console.log('stopBluetoothDevicesDiscovery', deviceList);
479
+ clearInterval(scanTimer);
480
+ scanTimer = null;
481
+ uni.stopBluetoothDevicesDiscovery();
482
+ const findDevice = deviceList.find((device) => device.macAddr === result || device.name === result);
483
+ connectFn(findDevice);
484
+ } finally {
485
+ }
486
+ }, 5000);
487
+ };