mini_program_gizwits_sdk 3.7.2-kuka → 3.7.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 (138) hide show
  1. package/README.md +237 -23
  2. package/{index.ts → dist/index.d.ts} +3 -3
  3. package/dist/index.js +6 -4
  4. package/dist/src/crc/calculators/crc16modbus.d.ts +2 -0
  5. package/dist/src/crc/calculators/crc32.d.ts +2 -0
  6. package/dist/src/crc/crc16modbus.d.ts +7 -0
  7. package/dist/src/crc/crc32.d.ts +7 -0
  8. package/dist/src/crc/create_buffer.d.ts +4 -0
  9. package/dist/src/crc/define_crc.d.ts +7 -0
  10. package/dist/src/crc/index.d.ts +19 -0
  11. package/{src/crc/types.ts → dist/src/crc/types.d.ts} +1 -1
  12. package/dist/src/handler/EventListener.d.ts +9 -0
  13. package/dist/src/handler/ble.d.ts +130 -0
  14. package/dist/src/handler/lan.d.ts +79 -0
  15. package/dist/src/handler/socket.d.ts +161 -0
  16. package/dist/src/protocol/Bind.d.ts +7 -0
  17. package/dist/src/protocol/DeviceInfo.d.ts +11 -0
  18. package/dist/src/protocol/DiscoverUDP.d.ts +17 -0
  19. package/dist/src/protocol/GetDeviceStatus.d.ts +5 -0
  20. package/dist/src/protocol/Login.d.ts +12 -0
  21. package/dist/src/protocol/Ntp.d.ts +5 -0
  22. package/dist/src/protocol/OTA/AwaitNoti.d.ts +7 -0
  23. package/dist/src/protocol/OTA/CheckCanOTA.d.ts +10 -0
  24. package/dist/src/protocol/OTA/OTAPackPackage.d.ts +8 -0
  25. package/dist/src/protocol/OTA/OtaComplete.d.ts +8 -0
  26. package/dist/src/protocol/OTA/PreOTA.d.ts +11 -0
  27. package/dist/src/protocol/OTA/ResetPosition.d.ts +6 -0
  28. package/dist/src/protocol/OTAStatus.d.ts +4 -0
  29. package/dist/src/protocol/OffLineData.d.ts +23 -0
  30. package/dist/src/protocol/ProtocolBase.d.ts +12 -0
  31. package/dist/src/protocol/Reset.d.ts +8 -0
  32. package/dist/src/protocol/SetReset.d.ts +7 -0
  33. package/dist/src/protocol/TransparentData.d.ts +12 -0
  34. package/dist/src/protocol/WifiConfig.d.ts +11 -0
  35. package/dist/src/protocol/dataPoint.d.ts +34 -0
  36. package/dist/src/protocol/tool.d.ts +14 -0
  37. package/dist/src/sdk.d.ts +158 -0
  38. package/dist/src/services/devices.d.ts +52 -0
  39. package/dist/src/services/login.d.ts +4 -0
  40. package/dist/src/services/monitor.d.ts +12 -0
  41. package/dist/src/services/ota.d.ts +7 -0
  42. package/dist/src/services/tool.d.ts +4 -0
  43. package/dist/src/services/uploadP0.d.ts +14 -0
  44. package/dist/src/types/index.d.ts +414 -0
  45. package/dist/src/types/otaStatus.d.ts +72 -0
  46. package/dist/src/utils/GizLog.d.ts +18 -0
  47. package/dist/src/utils/bleConfigLog.d.ts +11 -0
  48. package/dist/src/utils/connectedBssid.d.ts +6 -0
  49. package/dist/src/utils/errorCode.d.ts +3 -0
  50. package/dist/src/utils/globalData.d.ts +2 -0
  51. package/dist/src/utils/openApiRequest.d.ts +27 -0
  52. package/dist/src/utils/productConfigFileManage.d.ts +15 -0
  53. package/dist/src/utils/randomCode.d.ts +3 -0
  54. package/dist/src/utils/request.d.ts +1 -0
  55. package/dist/src/utils/sentry.d.ts +2 -0
  56. package/dist/src/utils/sleep.d.ts +2 -0
  57. package/dist/src/utils/utils.d.ts +55 -0
  58. package/dist/src/utils/wechatApi.d.ts +24 -0
  59. package/dist/src/utils/wifiConfigLogReport.d.ts +28 -0
  60. package/dist/src/wifiConfig/ConfigBase.d.ts +30 -0
  61. package/dist/src/wifiConfig/ap.d.ts +11 -0
  62. package/dist/src/wifiConfig/ble.d.ts +43 -0
  63. package/dist/src/wifiConfig/nfc/disposeData.d.ts +2 -0
  64. package/dist/src/wifiConfig/nfc/formatData.d.ts +3 -0
  65. package/dist/src/wifiConfig/nfc/formatSSID.d.ts +6 -0
  66. package/dist/src/wifiConfig/nfc/index.d.ts +22 -0
  67. package/dist/src/wifiConfig/nfc/isIncludedCH.d.ts +1 -0
  68. package/dist/src/wifiConfig/nfc/nfcAConnect.d.ts +6 -0
  69. package/dist/src/wifiConfig/nfc/nfcATransceive.d.ts +5 -0
  70. package/dist/src/wifiConfig/nfc/ssIDToASC.d.ts +1 -0
  71. package/dist/src/wifiConfig/nfc/stringToGbk.d.ts +1 -0
  72. package/dist/src/wifiConfig/nfc/transceive.wx.d.ts +2 -0
  73. package/dist/src/wifiConfig/nfc/types.d.ts +15 -0
  74. package/docs/ble-bssid.md +38 -0
  75. package/docs/ota-status.md +139 -0
  76. package/global.d.ts +3 -19
  77. package/package.json +13 -6
  78. package/.istanbul.yml +0 -4
  79. package/.travis.yml +0 -23
  80. package/.vscode/launch.json +0 -19
  81. package/.vscode/settings.json +0 -3
  82. package/src/GizLog.ts +0 -51
  83. package/src/aepApi/aepApiRequest.ts +0 -61
  84. package/src/crc/calculators/crc16modbus.ts +0 -36
  85. package/src/crc/calculators/crc32.ts +0 -47
  86. package/src/crc/crc16modbus.ts +0 -3
  87. package/src/crc/crc32.ts +0 -4
  88. package/src/crc/create_buffer.ts +0 -7
  89. package/src/crc/define_crc.ts +0 -9
  90. package/src/crc/index.ts +0 -10
  91. package/src/crc/package.json +0 -3
  92. package/src/errorCode.ts +0 -84
  93. package/src/global.d.ts +0 -53
  94. package/src/globalData.ts +0 -9
  95. package/src/handler/EventListener.ts +0 -44
  96. package/src/handler/ble.ts +0 -1485
  97. package/src/handler/lan.ts +0 -409
  98. package/src/handler/socket.ts +0 -625
  99. package/src/openApiRequest.ts +0 -62
  100. package/src/productConfigFileManage.ts +0 -58
  101. package/src/protocol/Bind.ts +0 -22
  102. package/src/protocol/DeviceInfo.ts +0 -36
  103. package/src/protocol/DiscoverUDP.ts +0 -80
  104. package/src/protocol/GetDeviceStatus.ts +0 -63
  105. package/src/protocol/Login.ts +0 -43
  106. package/src/protocol/Ntp.ts +0 -13
  107. package/src/protocol/OTA/AwaitNoti.ts +0 -14
  108. package/src/protocol/OTA/CheckCanOTA.ts +0 -23
  109. package/src/protocol/OTA/OTAPackPackage.ts +0 -36
  110. package/src/protocol/OTA/OtaComplete.ts +0 -17
  111. package/src/protocol/OTA/PreOTA.ts +0 -47
  112. package/src/protocol/OTA/ResetPosition.ts +0 -14
  113. package/src/protocol/OffLineData.ts +0 -81
  114. package/src/protocol/ProtocolBase.ts +0 -54
  115. package/src/protocol/Reset.ts +0 -15
  116. package/src/protocol/SetReset.ts +0 -11
  117. package/src/protocol/WifiConfig.ts +0 -42
  118. package/src/protocol/dataPoint.ts +0 -769
  119. package/src/protocol/thirdProtocol/YunZhiMianBleProtocolBase.ts +0 -39
  120. package/src/protocol/tool.ts +0 -147
  121. package/src/randomCode.ts +0 -36
  122. package/src/request.ts +0 -22
  123. package/src/sdk.ts +0 -1472
  124. package/src/sentry.ts +0 -55
  125. package/src/services/devices.ts +0 -309
  126. package/src/services/login.ts +0 -15
  127. package/src/services/ota.ts +0 -30
  128. package/src/services/tool.ts +0 -10
  129. package/src/services/uploadP0.ts +0 -56
  130. package/src/sleep.ts +0 -2
  131. package/src/types/index.ts +0 -48
  132. package/src/utils.ts +0 -419
  133. package/src/wechatApi.ts +0 -268
  134. package/src/wifiConfig/ConfigBase.ts +0 -185
  135. package/src/wifiConfig/ap.ts +0 -192
  136. package/src/wifiConfig/ble.ts +0 -436
  137. package/src/wifiConfig/ble_ailCloud.ts +0 -554
  138. package/yarn-error.log +0 -6901
package/src/utils.ts DELETED
@@ -1,419 +0,0 @@
1
- import { IProductInfo } from './sdk';
2
- import { GizwitsWxBlueToothDevice } from './handler/ble';
3
- import GizLog from './GizLog';
4
- import { lib } from 'crypto-js/core';
5
-
6
- export function ab2hex(buffer: ArrayBuffer) {
7
- let hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
8
- return ('00' + bit.toString(16)).slice(-2);
9
- });
10
- return hexArr.join('');
11
- }
12
-
13
- export function compareWXSDKVersion(v1: string, v2: string) {
14
- const v1Arr = v1.split('.');
15
- const v2Arr = v2.split('.');
16
- const len = Math.max(v1.length, v2.length);
17
-
18
- while (v1Arr.length < len) {
19
- v1Arr.push('0');
20
- }
21
- while (v2Arr.length < len) {
22
- v2Arr.push('0');
23
- }
24
-
25
- for (let i = 0; i < len; i++) {
26
- const num1 = parseInt(v1[i]);
27
- const num2 = parseInt(v2[i]);
28
-
29
- if (num1 > num2) {
30
- return 1;
31
- } else if (num1 < num2) {
32
- return -1;
33
- }
34
- }
35
- return 0;
36
- }
37
-
38
- export const isError = (err: unknown): err is IError => {
39
- return err != null && typeof (err as IError).errorCode === 'symbol';
40
- };
41
-
42
- export const wrapErrorInfo = (errorMessage: string) => ({
43
- errorCode: errorMessage,
44
- errorMessage,
45
- });
46
-
47
- export const unionBy = <T>(array: T[], key: string) => {
48
- return array.reduce<T[]>((acc, item) => {
49
- const keyValue = item[key];
50
- if (!acc.some(i => i[key] === keyValue)) {
51
- acc.push(item);
52
- }
53
- return acc;
54
- }, []);
55
- };
56
-
57
- interface IWXDevicesResult {
58
- success: true;
59
- bleDevices: WechatMiniprogram.BlueToothDevice[];
60
- }
61
- export function isWXDevicesResult(res: unknown): res is IWXDevicesResult {
62
- return (
63
- (res as IWXDevicesResult).success &&
64
- Object.prototype.toString.call((res as IWXDevicesResult).bleDevices) === '[object Array]'
65
- );
66
- }
67
-
68
- // hex转ArrayBuffer
69
- export function str2Buf(arr: string) {
70
- var length = arr.length;
71
- var buffer = new ArrayBuffer(length + 2);
72
- var dataview = new DataView(buffer);
73
- for (let i = 0; i < length; i++) {
74
- dataview.setUint8(i, parseInt(arr[i], 16));
75
- }
76
- return buffer;
77
- }
78
-
79
- // 把协议导出的数据转换为可以发送给蓝牙的数据
80
- export const numberArray2Uint8Array = (numArr: number[]) => {
81
- const buffer = new ArrayBuffer(numArr.length);
82
- const uint8Array = new Uint8Array(buffer);
83
- for (let i = 0; i < buffer.byteLength; i++) {
84
- uint8Array[i] = numArr[i];
85
- }
86
- return uint8Array;
87
- };
88
-
89
- const oldParseAdv = (advertisData: ArrayBuffer, pks: string[]) => {
90
- let pkUintArray = advertisData.slice(advertisData.byteLength - 16);
91
- let macUintArray = advertisData.slice(0, advertisData.byteLength - 16);
92
- let productKey = ab2hex(pkUintArray);
93
-
94
- if (pks.find(item => item === productKey)) {
95
- // 存在
96
- const mac = ab2hex(macUintArray);
97
- return { productKey, mac };
98
- } else {
99
- // 由于小程序安卓只接收ff type的广播数据,会乱序,所以这里需要做一次判断
100
- pkUintArray = advertisData.slice(0, 16);
101
- macUintArray = advertisData.slice(16);
102
- productKey = ab2hex(pkUintArray);
103
- const mac = ab2hex(macUintArray);
104
- return { productKey, mac };
105
- }
106
- };
107
- const parseAdv = (advertisData: ArrayBuffer, pks: string[]) => {
108
- if (!advertisData || advertisData.byteLength === 0) {
109
- return {
110
- bleWorkStatus: 0,
111
- mac: '',
112
- productKey: '',
113
- };
114
- }
115
-
116
- let index = 0;
117
- let mac = '';
118
- let productKey = '';
119
- let bleWorkStatus = 1;
120
-
121
- const u8Array = new Uint8Array(advertisData);
122
-
123
- while (true) {
124
- if (index > advertisData.byteLength - 1) {
125
- break;
126
- }
127
- const len = u8Array[index];
128
- if (len <= 0 || !len) {
129
- break;
130
- }
131
- if (advertisData.byteLength < len + index + 1) {
132
- break;
133
- }
134
-
135
- const tmpBytes = advertisData.slice(index + 1, index + len + 1);
136
- if (len >= 6 && len <= 8) {
137
- mac = ab2hex(tmpBytes);
138
- if (mac.length == 16) {
139
- mac = mac.substring(0, 15);
140
- }
141
- }
142
-
143
- if (len == 16) {
144
- const pk = ab2hex(tmpBytes).toLowerCase();
145
- if (pks.find(item => item === pk)) {
146
- productKey = pk;
147
- }
148
- }
149
- if (len == 1) {
150
- bleWorkStatus = new Uint8Array(tmpBytes)[0];
151
- }
152
- index += 1 + len;
153
- }
154
- return { bleWorkStatus, mac, productKey };
155
- };
156
-
157
- export const advertisData2PkAndMac = (advertisData: ArrayBuffer, pks: string[]) => {
158
- if (advertisData && advertisData.byteLength >= 22 && advertisData.byteLength <= 24) {
159
- return { ...oldParseAdv(advertisData, pks), bleWorkStatus: 1 };
160
- }
161
- if (advertisData && advertisData.byteLength > 24) {
162
- return parseAdv(advertisData, pks);
163
- }
164
- return { mac: '', productKey: '', bleWorkStatus: 1 };
165
- };
166
-
167
- export const isSameDevice = (deviceA: IDevice, deviceB: IDevice) => {
168
- return (
169
- deviceA.mac.toLocaleLowerCase() === deviceB.mac.toLocaleLowerCase() && deviceA.productKey === deviceB.productKey
170
- );
171
- };
172
-
173
- export const merageBleLocalDevices = (mainDevice: IDevice[], localDevice: IDevice[]) => {
174
- mainDevice.map(device => {
175
- // 重置成离线
176
- device.isBleOnline = false;
177
- device.bleWorkStatus = 0;
178
- });
179
- localDevice.map(localD => {
180
- const target = mainDevice.find(device => isSameDevice(device, localD));
181
- if (!target) {
182
- // 没有则插入这条本地设备
183
- mainDevice.push(localD);
184
- } else {
185
- target.isBleOnline = true;
186
- target.bleDeviceID = localD.bleDeviceID;
187
- // 蓝牙设备比较特殊,有广播类型 广播类型是写在本地设备属性里面的,但是又不属于已经连接的设备,先骚处理一下
188
- target.connectType = localD.connectType;
189
- target.bleWorkStatus = localD.bleWorkStatus;
190
- }
191
- });
192
- return mainDevice;
193
- };
194
-
195
- export const merageLanLocalDevices = (mainDevice: IDevice[], localDevice: IDevice[]) => {
196
- mainDevice.map(device => {
197
- // 重置成离线
198
- device.isLanOnline = false;
199
- });
200
- localDevice.map(localD => {
201
- const target = mainDevice.find(device => isSameDevice(device, localD));
202
- if (!target) {
203
- // 没有则插入这条本地设备
204
- mainDevice.push(localD);
205
- } else {
206
- target.isLanOnline = true;
207
- }
208
- });
209
- return mainDevice;
210
- };
211
-
212
- type TAdvData = {
213
- productKey: string;
214
- mac: string;
215
- bleWorkStatus: number;
216
- };
217
-
218
- export const BTDevice2GDevice = (BTDevice: GizwitsWxBlueToothDevice, pks: string[]) => {
219
- let advData: TAdvData = {
220
- productKey: '',
221
- mac: '',
222
- bleWorkStatus: 0,
223
- };
224
-
225
- let device: IDevice = {
226
- did: '',
227
- productKey: '',
228
- mac: '',
229
- bleWorkStatus: 0,
230
- connectType: 'NONE',
231
- isBleOnline: true,
232
- isLanOnline: false,
233
- isOnline: false,
234
- name: BTDevice.name,
235
- isBind: false,
236
- bleDeviceID: BTDevice.deviceId,
237
- ctime: new Date().getTime(),
238
- RSSI: BTDevice.RSSI as number,
239
- };
240
-
241
- switch (BTDevice.communicationType) {
242
- case 'BLE_BROADCAST': {
243
- try {
244
- GizLog.log('parse BLE_BROADCAST');
245
- const broadcastCmdData = parseBroadcastData(ab2numbers(BTDevice.advertisData));
246
- advData.productKey = broadcastCmdData.data.join('');
247
- advData.mac = broadcastCmdData.mac;
248
- device.connectType = 'BLE_BROADCAST';
249
- } catch (error) { }
250
- break;
251
- }
252
- default: {
253
- advData = advertisData2PkAndMac(BTDevice.advertisData, pks);
254
- break;
255
- }
256
- }
257
-
258
- device = {
259
- ...device,
260
- ...advData,
261
- };
262
-
263
- return device;
264
- };
265
-
266
- // 如果都不存在 就去连接大循环
267
- export const getFirstConnectType = (device: IDevice, type?: TConnectType): TConnectType => {
268
- if (!type) {
269
- if (device.isLanOnline) return 'LAN';
270
- if (device.isBleOnline) return 'BLE';
271
- return 'WAN';
272
- } else {
273
- if (type === 'WAN') return 'WAN';
274
-
275
- switch (type) {
276
- case 'BLE': {
277
- return device.isBleOnline ? 'BLE' : 'NONE';
278
- }
279
- case 'LAN': {
280
- return device.isLanOnline ? 'LAN' : 'NONE';
281
- }
282
- }
283
- }
284
-
285
- return 'WAN';
286
- };
287
-
288
- export const getProductInfoThroughPK = (pk: string, productInfos: IProductInfo[]) => {
289
- return productInfos.find(item => item.productKey === pk);
290
- };
291
-
292
- export const mergeObject = (obj1: any, obj2: any) => {
293
- for (let key in obj2) {
294
- if (obj2[key] == null || obj2[key] === '') continue;
295
- obj1[key] = obj2[key];
296
- }
297
- return obj1;
298
- };
299
- export function hex2ab(str) {
300
- const res = [];
301
- for (let i = 0; i < str.length; i += 2) {
302
- var hex = str.slice(i, i + 2);
303
- res.push(parseInt(hex, 16));
304
- }
305
- return new Uint8Array(res);
306
- }
307
-
308
- // 0x94 ack 和上报
309
- // 0x19 设备信息广播
310
- type BroadcastCmd = 0x19 | 0x94;
311
- type TBoradcastRes = {
312
- mac: string;
313
- cmd: BroadcastCmd;
314
- data: string[];
315
- };
316
- export function parseBroadcastData(data: number[]) {
317
- data = data.slice(0, 25);
318
- if (data.length != 25) {
319
- throw new Error('数据不合法');
320
- }
321
- const mac = `${number2hex(data[0])}${number2hex(data[1])}`;
322
- const sum = data[2];
323
- if (sum !== (data.slice(3).reduce((a, b) => a + b, 0) & 255)) {
324
- throw new Error('校验和不合法');
325
- }
326
- const cmd = number2hex(data[3]);
327
- const cmdData = data.slice(5, 5 + data[4]).map(item => number2hex(item));
328
-
329
- return {
330
- mac,
331
- cmd: parseInt(cmd, 16) as BroadcastCmd,
332
- data: cmdData,
333
- } as TBoradcastRes;
334
- }
335
-
336
- export function ab2numbers(buffer: ArrayBuffer) {
337
- return Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
338
- return bit;
339
- });
340
- }
341
-
342
- function number2hex(num: number, digits = 2) {
343
- return `${new Array(digits).fill(0).join('')}${num.toString(16)}`.slice(-digits);
344
- }
345
-
346
- let BASE_SN = 0;
347
- const getSn = () => {
348
- const cur = BASE_SN;
349
- BASE_SN = (BASE_SN + 1) & 255;
350
- return cur;
351
- };
352
-
353
- export function encrypt(uuids: number[], key: number) {
354
- let offset = 1;
355
- let nextKey = key;
356
- return uuids.map(uuid => {
357
- const res = (uuid ^ nextKey) & 0xffff;
358
- nextKey = (offset - res) & 0xffff;
359
- offset = offset << 1;
360
- return number2hex(res, 4);
361
- });
362
- }
363
-
364
- // 加密方式生成uuid广播数据
365
- export const convertToServiceUuids = ({ len = null, data = null, index = 0, mac }) => {
366
- const length = len == null ? Math.round(Math.random() * 18) + 1 : len;
367
- const newData =
368
- data == null
369
- ? Array.from({ length }, _ => {
370
- return Math.round(Math.random() * 255);
371
- })
372
- : data;
373
- const sourceData = [0x93, length, ...newData];
374
- const serviceUuids = convertToUuids(mac, getSn(), sourceData);
375
- if ([...new Set(serviceUuids)].length !== serviceUuids.length) {
376
- return convertToServiceUuids({
377
- len: length,
378
- data: newData,
379
- index: index++,
380
- mac,
381
- });
382
- }
383
- return serviceUuids;
384
- };
385
-
386
- export function convertToUuids(mac: number, sn: number, data: number[]) {
387
- if (data.length > 22) {
388
- throw new Error('最大长度为22');
389
- }
390
- const fullData = [...data, ...new Array(22 - data.length).fill(0)];
391
- const sum = data.reduce((a, b) => a + b, 0) & 255;
392
- const secret = ((sn >> 4) << 12) + ((sum >> 4) << 8) + ((sn & 15) << 4) + (sum & 15);
393
- const srcUuids = Array.from({ length: 11 }, (_, i) => {
394
- return (fullData[i * 2] << 8) + fullData[i * 2 + 1];
395
- });
396
- GizLog.log(
397
- '明文',
398
- number2hex(mac, 4),
399
- number2hex((sn << 8) + sum, 4),
400
- srcUuids.map(uuid => number2hex(uuid, 4))
401
- );
402
-
403
- const finalData = [number2hex(mac, 4), number2hex((sn << 8) + sum, 4), ...encrypt(srcUuids, secret)];
404
- // if (wx.getSystemInfoSync().platform === 'ios') {
405
- // return finalData.map((uuid) => `${uuid.slice(2)}${uuid.slice(0, 2)}`);
406
- // }
407
- return finalData.map(uuid => `${uuid.slice(2)}${uuid.slice(0, 2)}`);
408
- }
409
-
410
- // 定义一个函数,用于将 ArrayBuffer 转换为 WordArray
411
- export function arrayBufferToWordArray(arrayBuffer) {
412
- var words = [];
413
- var uint8View = new Uint8Array(arrayBuffer);
414
- for (var i = 0; i < uint8View.length; i += 4) {
415
- var word = (uint8View[i] << 24) | (uint8View[i + 1] << 16) | (uint8View[i + 2] << 8) | uint8View[i + 3];
416
- words.push(word);
417
- }
418
- return lib.WordArray.create(words, uint8View.length);
419
- }
package/src/wechatApi.ts DELETED
@@ -1,268 +0,0 @@
1
- import GizLog from './GizLog';
2
- import sleep from './sleep';
3
-
4
- interface IBluetoothAdapterStateResult {
5
- discovering: boolean;
6
- available: boolean;
7
- }
8
-
9
- export interface IWechatResult {
10
- errMsg: string;
11
- errCode: number;
12
- }
13
-
14
- /**
15
- * 重连
16
- */
17
- export async function retryConnect(deviceId: string, timeout: number = 10 * 1000) {
18
- let res = {
19
- success: false,
20
- };
21
- for (let i = 0; i < 5; i++) {
22
- try {
23
- console.debug('start createBLEConnection');
24
- return await createBLEConnection(deviceId, timeout);
25
- } catch (error) {
26
- res = error;
27
- console.debug('createBLEConnection error retry');
28
- await sleep(1000);
29
- }
30
- }
31
- return res;
32
- }
33
-
34
- export function openBluetoothAdapter() {
35
- return new Promise<IWechatResult>((res, rej) => {
36
- wx.openBluetoothAdapter({
37
- success: res,
38
- fail: rej,
39
- });
40
- });
41
- }
42
-
43
- export function closeBluetoothAdapter() {
44
- return new Promise<IWechatResult>((res, rej) => {
45
- wx.closeBluetoothAdapter({
46
- success: res,
47
- fail: rej,
48
- });
49
- });
50
- }
51
-
52
- export function getBluetoothAdapterState() {
53
- return new Promise<IBluetoothAdapterStateResult>((res, rej) => {
54
- wx.getBluetoothAdapterState({
55
- success: res,
56
- fail: rej,
57
- });
58
- });
59
- }
60
-
61
- export function startBluetoothDevicesDiscovery(allowDuplicatesKey = true) {
62
- return new Promise<IWechatResult>((res, rej) => {
63
- wx.startBluetoothDevicesDiscovery({
64
- success: res,
65
- fail: rej,
66
- allowDuplicatesKey,
67
- powerLevel: 'high',
68
- interval: 200,
69
- });
70
- });
71
- }
72
-
73
- export function getBluetoothDevices() {
74
- return new Promise<WechatMiniprogram.BlueToothDevice[]>((res, rej) => {
75
- wx.getBluetoothDevices({
76
- success: ({ devices }) => res(devices),
77
- fail: rej,
78
- });
79
- });
80
- }
81
-
82
- export function createBLEConnection(deviceId: string, timeout: number) {
83
- return new Promise<IWechatResult>((res, rej) => {
84
- wx.createBLEConnection({
85
- deviceId,
86
- timeout,
87
- success: r => res(r as IWechatResult),
88
- fail: err => {
89
- if (err.errCode === -1) {
90
- res(err);
91
- } else {
92
- rej(err);
93
- }
94
- },
95
- });
96
- });
97
- }
98
-
99
- interface IBLEService {
100
- uuid: string;
101
- isPrimary: boolean;
102
- }
103
-
104
- export function getBLEDeviceServices(deviceId: string) {
105
- return new Promise<IBLEService[]>((res, rej) => {
106
- wx.getBLEDeviceServices({
107
- deviceId,
108
- success: ({ services }) => res(services),
109
- fail: rej,
110
- });
111
- });
112
- }
113
-
114
- interface IBLECharacteristic {
115
- uuid: string;
116
- properties: {
117
- read: boolean;
118
- write: boolean;
119
- notify: boolean;
120
- indicate: boolean;
121
- };
122
- }
123
-
124
- export function getBLEDeviceCharacteristics(deviceId: string, serviceId: string) {
125
- return new Promise<IBLECharacteristic[]>((res, rej) => {
126
- wx.getBLEDeviceCharacteristics({
127
- deviceId,
128
- serviceId,
129
- success: ({ characteristics }) => res(characteristics),
130
- fail: rej,
131
- });
132
- });
133
- }
134
-
135
- export function notifyBLECharacteristicValueChange(
136
- deviceId: string,
137
- serviceId: string,
138
- characteristicId: string,
139
- state: boolean = true
140
- ) {
141
- return new Promise<IWechatResult>((res, rej) => {
142
- wx.notifyBLECharacteristicValueChange({
143
- deviceId,
144
- serviceId,
145
- characteristicId,
146
- state,
147
- success: res,
148
- fail: rej,
149
- });
150
- });
151
- }
152
-
153
- export function writeBLECharacteristicValue(
154
- deviceId: string,
155
- serviceId: string,
156
- characteristicId: string,
157
- value: ArrayBuffer
158
- ) {
159
- return new Promise<IWechatResult>(res => {
160
- wx.writeBLECharacteristicValue({
161
- deviceId,
162
- serviceId,
163
- characteristicId,
164
- value,
165
- complete: res,
166
- });
167
- });
168
- }
169
-
170
- // 全局发送队列,确保任意两个指令之间都有足够间隔
171
- interface QueueItem {
172
- task: () => Promise<void>;
173
- resolve: (value: IWechatResult) => void;
174
- reject: (reason: any) => void;
175
- }
176
- const sendQueue: Array<QueueItem> = [];
177
- let isProcessing = false;
178
- const MIN_PACKET_INTERVAL = 500; // 最小包间隔 ms,iPhone 用较小值
179
- let lastSendTime = 0;
180
-
181
- async function processQueue() {
182
- if (isProcessing || sendQueue.length === 0) return;
183
- isProcessing = true;
184
-
185
- while (sendQueue.length > 0) {
186
- const item = sendQueue.shift();
187
- if (!item) continue;
188
-
189
- // 确保与上一个指令有足够间隔
190
- const now = Date.now();
191
- const timeSinceLast = now - lastSendTime;
192
- if (timeSinceLast < MIN_PACKET_INTERVAL) {
193
- const waitTime = MIN_PACKET_INTERVAL - timeSinceLast;
194
- await sleep(waitTime);
195
- }
196
-
197
- try {
198
- await item.task();
199
- // 指令成功完成后更新最后发送时间
200
- lastSendTime = Date.now();
201
- } catch (err) {
202
- item.reject(err);
203
- }
204
- }
205
-
206
- isProcessing = false;
207
- }
208
-
209
- export function unpackWriteBLECharacteristicValue(
210
- deviceId: string,
211
- serviceId: string,
212
- characteristicId: string,
213
- value: ArrayBuffer
214
- ): Promise<IWechatResult> {
215
- if (!value || value.byteLength === 0) {
216
- return Promise.reject(new Error('value is empty'));
217
- }
218
- const totalBytes = value.byteLength;
219
- const packetCount = Math.ceil(totalBytes / 20);
220
-
221
- return new Promise<IWechatResult>((resolve, reject) => {
222
- const task = async () => {
223
- let pos = 0;
224
- let bytes = totalBytes;
225
- let writeRes: IWechatResult = { errCode: 0, errMsg: 'ok' };
226
- let packetIndex = 0;
227
-
228
- while (bytes > 0) {
229
- await sleep(30); // 每个包前等待 30ms
230
- const tmpBuffer = value.slice(pos, pos + 20);
231
- pos += 20;
232
- bytes -= 20;
233
-
234
- writeRes = await writeBLECharacteristicValue(deviceId, serviceId, characteristicId, tmpBuffer);
235
- GizLog.log('unpackWriteBLECharacteristicValue', packetIndex + 1, writeRes);
236
-
237
- if (writeRes.errCode !== 0) {
238
- break;
239
- }
240
-
241
- packetIndex++;
242
- }
243
-
244
- if (writeRes.errCode !== 0) {
245
- reject(writeRes);
246
- } else {
247
- resolve(writeRes);
248
- }
249
- };
250
-
251
- sendQueue.push({ task, resolve, reject });
252
- processQueue();
253
- });
254
- }
255
-
256
- export async function downloadFile({ url }) {
257
- return new Promise((resFunc, rejFunc) => {
258
- wx.downloadFile({
259
- url: url,
260
- success(res) {
261
- resFunc(res);
262
- },
263
- fail(err) {
264
- rejFunc(err);
265
- },
266
- });
267
- });
268
- }