mini_program_gizwits_sdk 3.4.9 → 3.4.12

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.
@@ -10,7 +10,12 @@ import {
10
10
  getBLEDeviceCharacteristics, getBLEDeviceServices, getBluetoothAdapterState, getBluetoothDevices,
11
11
  notifyBLECharacteristicValueChange, retryConnect, startBluetoothDevicesDiscovery, unpackWriteBLECharacteristicValue
12
12
  } from '../wechatApi';
13
- import ConfigBase from "./ConfigBase";
13
+ import ConfigBase, { ConfigEventData } from "./ConfigBase";
14
+
15
+ type EnableAndGetBluetoothDevicesRes = Promise<
16
+ | { success: false; err: IError }
17
+ | { success: true; bleDevices?: IDevice[] }
18
+ >;
14
19
 
15
20
  interface IArgs {
16
21
  bleDeviceId: string;
@@ -18,174 +23,11 @@ interface IArgs {
18
23
  serviceUUIDSuffix?: string;
19
24
  characteristicUUIDSuffix?: string;
20
25
  bleHandle: BleHandle;
26
+ eventCallBack: (event: ConfigEventData) => void, // 配网回调
21
27
  }
22
28
 
23
29
  const configAck = '0000000303000002';
24
30
 
25
- export function sendBLEConfigCmd({
26
- bleDeviceId,
27
- arrayBuffer,
28
- serviceUUIDSuffix = 'abf0',
29
- characteristicUUIDSuffix = 'abf7',
30
- bleHandle
31
- }: IArgs) {
32
- let sendInterval = null;
33
- let closeTimeout = null;
34
-
35
- const checkInterrupt = () => {
36
- if (closeTimeout === null) {
37
- sendInterval && clearInterval(sendInterval);
38
- return true;
39
- }
40
- return false;
41
- }
42
-
43
- return new Promise<boolean>(async (resolve, reject) => {
44
- try {
45
- GizLog.debug(
46
- 'GIZ_SDK: ssid info: ', arrayBuffer
47
- );
48
- // 设置超时
49
- closeTimeout = setTimeout(() => {
50
- sendInterval && clearInterval(sendInterval);
51
- // 发送超时 返回失败
52
- closeTimeout = null;
53
- resolve(false);
54
- }, 5 * 1000)
55
- GizLog.debug(
56
- 'GIZ_SDK: createBLEConnection start: ', bleDeviceId
57
- );
58
- await bleHandle.disableScan()
59
-
60
- const connectData = await retryConnect(bleDeviceId, 10 * 1000);
61
- bleHandle.enableScan();
62
-
63
- GizLog.debug(
64
- 'GIZ_SDK: createBLEConnection end, res:', connectData
65
- );
66
- const services = await getBLEDeviceServices(bleDeviceId);
67
- GizLog.debug(
68
- 'GIZ_SDK: getBLEDeviceServices end, res:', services
69
- );
70
- const service = services.find((s) =>
71
- s.uuid.split('-')[0].toLowerCase().endsWith(serviceUUIDSuffix)
72
- );
73
- if (!service) {
74
- // 获取蓝牙设备服务异常
75
- GizLog.debug(
76
- 'GIZ_SDK: get ble device services fail',
77
- bleDeviceId,
78
- services
79
- );
80
- resolve(false);
81
- return;
82
- }
83
-
84
- const characteristics = await getBLEDeviceCharacteristics(
85
- bleDeviceId,
86
- service.uuid
87
- );
88
- GizLog.debug(
89
- 'GIZ_SDK: getBLEDeviceCharacteristics end, res:', characteristics
90
- );
91
- const characteristic = characteristics.find((c) =>
92
- c.uuid.split('-')[0].toLowerCase().endsWith(characteristicUUIDSuffix)
93
- );
94
- if (!characteristic) {
95
- // 获取蓝牙设备特征值异常
96
- GizLog.debug(
97
- 'GIZ_SDK: get ble device characteristics fail',
98
- bleDeviceId,
99
- characteristics
100
- );
101
- resolve(false);
102
- return;
103
- }
104
-
105
- if (
106
- !characteristic.properties.notify &&
107
- !characteristic.properties.indicate
108
- ) {
109
- GizLog.debug(
110
- 'GIZ_SDK: the ble device characteristic not support notify or indicate',
111
- bleDeviceId,
112
- characteristic
113
- );
114
- // 该设备不支持 notify & indicate 操作
115
- resolve(false);
116
- return;
117
- }
118
-
119
- GizLog.debug(
120
- 'GIZ_SDK: check characteristic and service success',
121
- );
122
-
123
- await notifyBLECharacteristicValueChange(
124
- bleDeviceId,
125
- service.uuid,
126
- characteristic.uuid
127
- );
128
-
129
- // 这里有个问题,模组好像不一定每次都会回
130
- const handleBLECharacteristicValueChange = (res: WechatMiniprogram.OnBLECharacteristicValueChangeListenerResult) => {
131
- const hexString = ab2hex(res.value);
132
- GizLog.debug('GIZ_SDK: 收到设备返回ack', hexString)
133
- if (hexString === configAck) {
134
- // 发送成功
135
- bleHandle.removeEventListener("GizBleDeviceData", handleBLECharacteristicValueChange)
136
- resolve(true);
137
- }
138
- };
139
-
140
- bleHandle.addEventListener("GizBleDeviceData", handleBLECharacteristicValueChange)
141
-
142
- // 订阅特征值变化
143
- // wx.onBLECharacteristicValueChange(handleBLECharacteristicValueChange);
144
-
145
- GizLog.debug(
146
- 'GIZ_SDK: on notifyBLECharacteristicValueChange success',
147
- );
148
-
149
- if (checkInterrupt()) return;
150
-
151
- await unpackWriteBLECharacteristicValue(
152
- bleDeviceId,
153
- service.uuid,
154
- characteristic.uuid,
155
- arrayBuffer
156
- );
157
- sendInterval = setInterval(() => {
158
- if (checkInterrupt()) return;
159
- unpackWriteBLECharacteristicValue(
160
- bleDeviceId,
161
- service.uuid,
162
- characteristic.uuid,
163
- arrayBuffer
164
- );
165
- }, 2000)
166
-
167
- // if (res.errCode === 0) {
168
- // resolve(true);
169
- // } else{
170
- // resolve(false);
171
- // }
172
- GizLog.debug('GIZ_SDK: unpackWriteBLECharacteristicValue end');
173
- } catch (error) {
174
- reject(false);
175
- GizLog.debug('GIZ_SDK: sendBLEConfigCmd error', error);
176
- }
177
- })
178
- .catch((error) => {
179
- GizLog.debug('GIZ_SDK: sendBLEConfigCmd error', error);
180
- })
181
- .finally(() => {
182
- // 关闭连接
183
- closeTimeout && clearTimeout(closeTimeout);
184
- sendInterval && clearInterval(sendInterval);
185
- wx.closeBLEConnection({ deviceId: bleDeviceId });
186
- });
187
- }
188
-
189
31
  interface configBLEDeviceParams {
190
32
  ssid: string;
191
33
  password: string;
@@ -198,42 +40,243 @@ interface ISetDeviceOnboardingDeployProps {
198
40
  timeout: number;
199
41
  isBind: boolean;
200
42
  softAPSSIDPrefix: string;
43
+ eventCallBack: (event: ConfigEventData) => void; // 配网回调
201
44
  }
202
45
 
203
46
 
204
47
  class BLEConfig extends ConfigBase {
205
48
  bleHandle: BleHandle;
206
49
 
207
- constructor(ssid: string, bssid: string, password: string, specialProductKeys: string[], specialProductKeySecrets: string[],bleHandle: BleHandle) {
50
+ constructor(
51
+ ssid: string, bssid: string,
52
+ password: string, specialProductKeys: string[],
53
+ specialProductKeySecrets: string[],
54
+ bleHandle: BleHandle,
55
+ ) {
208
56
  super(ssid, bssid, password,specialProductKeys,specialProductKeySecrets)
209
57
  this.bleHandle = bleHandle;
210
58
  }
59
+
60
+ sendBLEConfigCmd = ({
61
+ bleDeviceId,
62
+ arrayBuffer,
63
+ serviceUUIDSuffix = 'abf0',
64
+ characteristicUUIDSuffix = 'abf7',
65
+ bleHandle,
66
+ eventCallBack
67
+ }: IArgs) => {
68
+ let sendInterval = null;
69
+ let closeTimeout = null;
70
+
71
+ const checkInterrupt = () => {
72
+ if (closeTimeout === null) {
73
+ sendInterval && clearInterval(sendInterval);
74
+ return true;
75
+ }
76
+ return !this.hasTimeoutHandler();
77
+ }
78
+
79
+ return new Promise<boolean>(async (resolve, reject) => {
80
+ try {
81
+ GizLog.debug(
82
+ 'GIZ_SDK: ssid info: ', arrayBuffer
83
+ );
84
+ // 设置超时
85
+ closeTimeout = setTimeout(() => {
86
+ sendInterval && clearInterval(sendInterval);
87
+ // 发送超时 返回失败
88
+ closeTimeout = null;
89
+ resolve(false);
90
+ }, 5 * 1000)
91
+ GizLog.debug(
92
+ 'GIZ_SDK: createBLEConnection start: ', bleDeviceId
93
+ );
94
+ await bleHandle.disableScan()
95
+
96
+ const connectData = await retryConnect(bleDeviceId, 10 * 1000);
97
+
98
+ eventCallBack?.({
99
+ event: "GIZ_CONNECT_SUCCESS",
100
+ deviceID: bleDeviceId
101
+ })
102
+
103
+ bleHandle.enableScan();
104
+
105
+ GizLog.debug(
106
+ 'GIZ_SDK: createBLEConnection end, res:', connectData
107
+ );
108
+ const services = await getBLEDeviceServices(bleDeviceId);
109
+ GizLog.debug(
110
+ 'GIZ_SDK: getBLEDeviceServices end, res:', services
111
+ );
112
+ const service = services.find((s) =>
113
+ s.uuid.split('-')[0].toLowerCase().endsWith(serviceUUIDSuffix)
114
+ );
115
+ if (!service) {
116
+ // 获取蓝牙设备服务异常
117
+ GizLog.debug(
118
+ 'GIZ_SDK: get ble device services fail',
119
+ bleDeviceId,
120
+ services
121
+ );
122
+ resolve(false);
123
+ return;
124
+ }
125
+
126
+ const characteristics = await getBLEDeviceCharacteristics(
127
+ bleDeviceId,
128
+ service.uuid
129
+ );
130
+ GizLog.debug(
131
+ 'GIZ_SDK: getBLEDeviceCharacteristics end, res:', characteristics
132
+ );
133
+ const characteristic = characteristics.find((c) =>
134
+ c.uuid.split('-')[0].toLowerCase().endsWith(characteristicUUIDSuffix)
135
+ );
136
+ if (!characteristic) {
137
+ // 获取蓝牙设备特征值异常
138
+ GizLog.debug(
139
+ 'GIZ_SDK: get ble device characteristics fail',
140
+ bleDeviceId,
141
+ characteristics
142
+ );
143
+ resolve(false);
144
+ return;
145
+ }
146
+
147
+ if (
148
+ !characteristic.properties.notify &&
149
+ !characteristic.properties.indicate
150
+ ) {
151
+ GizLog.debug(
152
+ 'GIZ_SDK: the ble device characteristic not support notify or indicate',
153
+ bleDeviceId,
154
+ characteristic
155
+ );
156
+ // 该设备不支持 notify & indicate 操作
157
+ resolve(false);
158
+ return;
159
+ }
160
+
161
+ GizLog.debug(
162
+ 'GIZ_SDK: check characteristic and service success',
163
+ );
164
+
165
+
166
+ await notifyBLECharacteristicValueChange(
167
+ bleDeviceId,
168
+ service.uuid,
169
+ characteristic.uuid
170
+ );
171
+
172
+ eventCallBack?.({
173
+ event: "GIZ_CONFIG_SEND_SUCCESS",
174
+ deviceID: bleDeviceId
175
+ })
176
+
177
+ // 这里有个问题,模组好像不一定每次都会回
178
+ const handleBLECharacteristicValueChange = (res: WechatMiniprogram.OnBLECharacteristicValueChangeListenerResult) => {
179
+ const hexString = ab2hex(res.value);
180
+ GizLog.debug('GIZ_SDK: 收到设备返回ack', hexString)
181
+ eventCallBack({
182
+ event: "GIZ_CONFIG_RECV_SUCCESS",
183
+ deviceID: bleDeviceId
184
+ })
185
+ if (hexString === configAck) {
186
+ // 发送成功
187
+ bleHandle.removeEventListener("GizBleDeviceData", handleBLECharacteristicValueChange)
188
+ resolve(true);
189
+ }
190
+ };
191
+
192
+ bleHandle.addEventListener("GizBleDeviceData", handleBLECharacteristicValueChange)
193
+
194
+ // 订阅特征值变化
195
+ // wx.onBLECharacteristicValueChange(handleBLECharacteristicValueChange);
196
+
197
+ GizLog.debug(
198
+ 'GIZ_SDK: on notifyBLECharacteristicValueChange success',
199
+ );
200
+
201
+ if (checkInterrupt()) return;
202
+
203
+ await unpackWriteBLECharacteristicValue(
204
+ bleDeviceId,
205
+ service.uuid,
206
+ characteristic.uuid,
207
+ arrayBuffer
208
+ );
209
+ sendInterval = setInterval(() => {
210
+ if (checkInterrupt()) return;
211
+ unpackWriteBLECharacteristicValue(
212
+ bleDeviceId,
213
+ service.uuid,
214
+ characteristic.uuid,
215
+ arrayBuffer
216
+ );
217
+ }, 2000)
218
+
219
+ // if (res.errCode === 0) {
220
+ // resolve(true);
221
+ // } else{
222
+ // resolve(false);
223
+ // }
224
+ GizLog.debug('GIZ_SDK: unpackWriteBLECharacteristicValue end');
225
+ } catch (error) {
226
+ reject(false);
227
+ GizLog.debug('GIZ_SDK: sendBLEConfigCmd error', error);
228
+ }
229
+ })
230
+ .catch((error) => {
231
+ GizLog.debug('GIZ_SDK: sendBLEConfigCmd error', error);
232
+ })
233
+ .finally(() => {
234
+ // 关闭连接
235
+ closeTimeout && clearTimeout(closeTimeout);
236
+ sendInterval && clearInterval(sendInterval);
237
+ this.bleHandle.disConnectDevice(bleDeviceId)
238
+ });
239
+ }
240
+
241
+
211
242
  destroy = () => {
212
243
  this.cleanTimeout();
213
244
  }
214
- isValidBleDevice = (
215
- bleDevice: WechatMiniprogram.BlueToothDevice,
216
- softAPSSIDPrefix?: string
217
- ) => {
218
- if (!bleDevice || !bleDevice.advertisData) {
219
- // 无效蓝牙设备或者蓝牙设备广播数据为空,返回失败
245
+ isValidBleDevice = (device:IDevice, softAPSSIDPrefix?: string) => {
246
+ if (device.bleWorkStatus === 0) return false;
247
+ if (!this.specialProductKeys.includes(device.productKey)) {
220
248
  return false;
221
249
  }
222
250
 
223
- const {productKey, mac} = advertisData2PkAndMac(bleDevice.advertisData, this.specialProductKeys)
224
-
225
-
226
- if (!this.specialProductKeys.includes(productKey)) {
227
- // 不在PK列表
228
- return false;
229
- }
230
- GizLog.debug(`GIZ_SDK: isValidBleDevice mac: ${mac} pk: ${productKey} name: ${bleDevice.name}`)
231
- GizLog.debug(`GIZ_SDK: softAPSSIDPrefix: ${softAPSSIDPrefix} ismatch : ${bleDevice.name && bleDevice.name.startsWith(softAPSSIDPrefix)}`)
251
+ GizLog.debug(`GIZ_SDK: isValidBleDevice mac: ${device.mac} pk: ${device.productKey} name: ${device.name}`)
252
+ GizLog.debug(`GIZ_SDK: softAPSSIDPrefix: ${softAPSSIDPrefix} ismatch : ${device.name && device.name.startsWith(softAPSSIDPrefix)}`)
232
253
  return (
233
254
  !softAPSSIDPrefix ||
234
- (bleDevice.name && bleDevice.name.startsWith(softAPSSIDPrefix))
235
- );
236
- };
255
+ (device.name && device.name.startsWith(softAPSSIDPrefix))
256
+ )
257
+ }
258
+ // isValidBleDevice = (
259
+ // bleDevice: WechatMiniprogram.BlueToothDevice,
260
+ // softAPSSIDPrefix?: string
261
+ // ) => {
262
+ // if (!bleDevice || !bleDevice.advertisData) {
263
+ // // 无效蓝牙设备或者蓝牙设备广播数据为空,返回失败
264
+ // return false;
265
+ // }
266
+ // const {productKey, mac, bleWorkStatus} = advertisData2PkAndMac(bleDevice.advertisData, this.specialProductKeys)
267
+ // if (!this.specialProductKeys.includes(productKey)) {
268
+ // // 不在PK列表
269
+ // return false;
270
+ // }
271
+ // // 判断广播包是否可以配网
272
+ // if (bleWorkStatus !== 1) return;
273
+ // GizLog.debug(`GIZ_SDK: isValidBleDevice mac: ${mac} pk: ${productKey} name: ${bleDevice.name}`)
274
+ // GizLog.debug(`GIZ_SDK: softAPSSIDPrefix: ${softAPSSIDPrefix} ismatch : ${bleDevice.name && bleDevice.name.startsWith(softAPSSIDPrefix)}`)
275
+ // return (
276
+ // !softAPSSIDPrefix ||
277
+ // (bleDevice.name && bleDevice.name.startsWith(softAPSSIDPrefix))
278
+ // );
279
+ // };
237
280
 
238
281
 
239
282
  enableBluetoothDevicesDescovery = async (): Promise<
@@ -263,19 +306,17 @@ class BLEConfig extends ConfigBase {
263
306
 
264
307
  enableAndGetBluetoothDevices = async (
265
308
  softAPSSIDPrefix?: string
266
- ): Promise<
267
- | { success: false; err: IError }
268
- | { success: true; bleDevices?: WechatMiniprogram.BlueToothDevice[] }
269
- > => {
309
+ ): EnableAndGetBluetoothDevicesRes => {
270
310
  const discoveryRes = await this.enableBluetoothDevicesDescovery();
271
311
  if (!discoveryRes.success) {
272
312
  return discoveryRes;
273
313
  }
274
314
  GizLog.debug('GIZ_SDK: start enableAndGetBluetoothDevices');
275
315
 
276
- const bleDevices: WechatMiniprogram.BlueToothDevice[] = (
277
- await getBluetoothDevices()
278
- ).filter((d) => this.isValidBleDevice(d, softAPSSIDPrefix));
316
+ // const bleDevices: WechatMiniprogram.BlueToothDevice[] = (
317
+ // await getBluetoothDevices()
318
+ // ).filter((d) => this.isValidBleDevice(d, softAPSSIDPrefix));
319
+ const bleDevices: IDevice[] = this.bleHandle.scanList.filter(d => this.isValidBleDevice(d, softAPSSIDPrefix))
279
320
  GizLog.debug('GIZ_SDK: getBluetoothDevices success', bleDevices);
280
321
  return {
281
322
  success: true,
@@ -286,8 +327,17 @@ class BLEConfig extends ConfigBase {
286
327
  timeout,
287
328
  isBind = true,
288
329
  softAPSSIDPrefix,
330
+ eventCallBack = (e) => {},
289
331
  }: ISetDeviceOnboardingDeployProps) => {
332
+ this.eventCallBack = eventCallBack;
290
333
  return new Promise<IResult<IDevice[]>>(async (res, rej) => {
334
+
335
+ // 清空扫描缓存
336
+ this.bleHandle.scanList = [];
337
+ this.eventCallBack?.({
338
+ event: "GIZ_CONFIG_START",
339
+ deviceID: null
340
+ })
291
341
  const ssid = this.ssid;
292
342
  const password = this.password;
293
343
  this.destroy();
@@ -360,24 +410,27 @@ class BLEConfig extends ConfigBase {
360
410
  return rej(enableAndGetRes);
361
411
  }
362
412
 
363
- const { bleDevices } = enableAndGetRes;
413
+ let bleDevices: IDevice[] = enableAndGetRes.bleDevices as IDevice[];
364
414
 
365
415
  GizLog.debug('GIZ_SDK: enableAndGetBluetoothDevices success, target devices: ', bleDevices);
366
416
 
367
- const handleFoundDevices = async ({
368
- devices,
369
- }: {
370
- devices: WechatMiniprogram.BlueToothDevice[];
371
- }) => {
372
- this.hasTimeoutHandler()
373
- ? Array.prototype.push.apply(
374
- bleDevices,
375
- devices.filter((d) => this.isValidBleDevice(d, softAPSSIDPrefix))
376
- )
377
- : wx.offBluetoothDeviceFound(()=>{});
378
- };
379
-
380
- wx.onBluetoothDeviceFound(handleFoundDevices);
417
+ // const handleFoundDevices = async ({
418
+ // devices,
419
+ // }: {
420
+ // devices: WechatMiniprogram.BlueToothDevice[];
421
+ // }) => {
422
+ // if(this.hasTimeoutHandler()) {
423
+ // Array.prototype.push.apply(
424
+ // bleDevices,
425
+ // devices.filter((d) => this.isValidBleDevice(d, softAPSSIDPrefix))
426
+ // )
427
+ // } else {
428
+ // wx.offBluetoothDeviceFound(()=>{});
429
+ // }
430
+ // };
431
+
432
+ // wx.onBluetoothDeviceFound(handleFoundDevices);
433
+ await startBluetoothDevicesDiscovery(true);
381
434
 
382
435
  const appendPassword = this.appendExtendData(password)
383
436
  const uint8Array = WifiConfig.pack(ssid,appendPassword);
@@ -386,30 +439,36 @@ class BLEConfig extends ConfigBase {
386
439
  if (!this.hasTimeoutHandler()) {
387
440
  return;
388
441
  }
389
- const bleDevice = bleDevices.shift();
442
+ const bleDevice = bleDevices.shift() as IDevice;
390
443
  if (bleDevice) {
444
+ this.eventCallBack?.({
445
+ event: "GIZ_DISCOVER_SUCCESS",
446
+ deviceID: bleDevice.bleDeviceID
447
+ })
391
448
  GizLog.debug('GIZ_SDK: startConfigDevice, target device: ', bleDevice);
392
449
  }
393
450
 
394
- const success =
395
- bleDevice &&
396
- (await sendBLEConfigCmd({
397
- bleDeviceId: bleDevice.deviceId,
451
+ let success = false;
452
+ if (bleDevice) {
453
+ success = await this.sendBLEConfigCmd({
454
+ bleDeviceId: bleDevice.bleDeviceID,
398
455
  arrayBuffer: uint8Array.buffer,
399
- bleHandle: this.bleHandle
400
- }));
456
+ bleHandle: this.bleHandle,
457
+ eventCallBack: this.eventCallBack
458
+ }) === true
459
+ }
401
460
 
402
461
  if (!success) {
403
462
  // 如果校验设备或者发送不成功,重试下一个设备
404
463
  await sleep(500);
405
- await startBluetoothDevicesDiscovery();
464
+ bleDevices = this.bleHandle.scanList.filter((d) => this.isValidBleDevice(d, softAPSSIDPrefix));;
406
465
  await startConfigDevice();
407
466
  return;
408
467
  }
409
468
 
410
469
  // 如果有一个设备发送成功,则不再发现新设备
411
470
  GizLog.debug("GIZ_SDK: offBluetoothDeviceFound ready search device")
412
- wx.offBluetoothDeviceFound(() => {});
471
+ // wx.offBluetoothDeviceFound(() => {});
413
472
  };
414
473
 
415
474
  // 开始大循环搜索