mini_program_gizwits_sdk 3.0.1 → 3.0.6

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 (53) hide show
  1. package/dist/index.js +3 -3
  2. package/dist/src/errorCode.d.ts +5 -0
  3. package/dist/src/globalData.d.ts +2 -0
  4. package/dist/src/openApiRequest.d.ts +9 -0
  5. package/dist/src/productConfigFileManage.d.ts +12 -0
  6. package/dist/src/protocol/Bind.d.ts +7 -0
  7. package/dist/src/protocol/DataPoint.d.ts +52 -0
  8. package/dist/src/protocol/GetDeviceStatus.d.ts +5 -0
  9. package/dist/src/protocol/Login.d.ts +12 -0
  10. package/dist/src/protocol/ProtocolBase.d.ts +11 -0
  11. package/dist/src/protocol/WifiConfig.d.ts +6 -0
  12. package/dist/src/protocol/tool.d.ts +9 -0
  13. package/dist/src/randomCode.d.ts +7 -0
  14. package/dist/src/request.d.ts +1 -0
  15. package/dist/src/services/devices.d.ts +53 -0
  16. package/dist/src/services/login.d.ts +8 -0
  17. package/dist/src/services/tool.d.ts +4 -0
  18. package/dist/src/sleep.d.ts +2 -0
  19. package/dist/src/socket.d.ts +107 -0
  20. package/dist/src/utils.d.ts +29 -0
  21. package/dist/src/wechatApi.d.ts +33 -0
  22. package/dist/src/wifiConfig/ConfigBase.d.ts +26 -0
  23. package/dist/src/wifiConfig/ap.d.ts +21 -0
  24. package/dist/src/wifiConfig/ble.d.ts +40 -0
  25. package/global.d.ts +28 -0
  26. package/index.ts +7 -0
  27. package/package.json +6 -3
  28. package/src/ble.ts +566 -0
  29. package/src/errorCode.ts +60 -0
  30. package/src/global.d.ts +42 -0
  31. package/src/globalData.ts +9 -0
  32. package/src/openApiRequest.ts +103 -0
  33. package/src/productConfigFileManage.ts +44 -0
  34. package/src/protocol/Bind.ts +22 -0
  35. package/src/protocol/GetDeviceStatus.ts +61 -0
  36. package/src/protocol/Login.ts +43 -0
  37. package/src/protocol/ProtocolBase.ts +53 -0
  38. package/src/protocol/WifiConfig.ts +41 -0
  39. package/src/protocol/dataPoint.ts +663 -0
  40. package/src/protocol/tool.ts +91 -0
  41. package/src/randomCode.ts +36 -0
  42. package/src/request.ts +22 -0
  43. package/src/sdk.ts +811 -0
  44. package/src/services/devices.ts +210 -0
  45. package/src/services/login.ts +15 -0
  46. package/src/services/tool.ts +10 -0
  47. package/src/sleep.ts +2 -0
  48. package/src/socket.ts +449 -0
  49. package/src/utils.ts +215 -0
  50. package/src/wechatApi.ts +179 -0
  51. package/src/wifiConfig/ConfigBase.ts +183 -0
  52. package/src/wifiConfig/ap.ts +193 -0
  53. package/src/wifiConfig/ble.ts +417 -0
package/src/sdk.ts ADDED
@@ -0,0 +1,811 @@
1
+ import { setGlobalData, getGlobalData } from './globalData';
2
+ import { BleHandle } from './ble';
3
+ import GizwitsWS from './socket';
4
+
5
+ import ApConfig from './wifiConfig/ap';
6
+ import BLEConfig from './wifiConfig/ble';
7
+ import { errorCode } from '..';
8
+ import { AnonymousLogin, ILoginRes } from './services/login';
9
+ import {
10
+ bindMac,
11
+ getBindingList,
12
+ IOpenApiDevice,
13
+ ISafeRegisterReturn,
14
+ IUnbindReturn,
15
+ safeRegister,
16
+ unbindDevice,
17
+ } from './services/devices';
18
+ import {
19
+ getFirstConnectType,
20
+ getProductInfoThroughPK,
21
+ isSameDevice,
22
+ merageBleLocalDevices,
23
+ merageLanLocalDevices,
24
+ numberArray2Uint8Array,
25
+ } from './utils';
26
+ import productConfigFileManage from './productConfigFileManage';
27
+ import { IDataPointConfig, pack, unpack } from './protocol/DataPoint';
28
+ import { fillString, hexStrint2byte } from './protocol/tool';
29
+
30
+ // 接口返回格式
31
+ interface ISDKResult<T> {
32
+ data?: T;
33
+ err?: IError;
34
+ success: boolean;
35
+ }
36
+ export interface ISetCommonDeviceOnboardingDeployProps {
37
+ ssid: string;
38
+ password: string;
39
+ timeout: number;
40
+ isBind?: boolean;
41
+ mode?: 0 | 3; // 0 AP 3 BLE
42
+ softAPSSIDPrefix?: string;
43
+ }
44
+
45
+ export interface ISetDeviceOnboardingDeployProps
46
+ extends ISetCommonDeviceOnboardingDeployProps {
47
+ softAPSSIDPrefix: string;
48
+ }
49
+
50
+ export interface IRandomCodesResult {
51
+ random_code: string;
52
+ product_key: string;
53
+ mac: string;
54
+ did: string;
55
+ user_id: string;
56
+ timestamp: number;
57
+ type: string;
58
+ wifi_soft_ver: string;
59
+ lan_proto_ver: string;
60
+ }
61
+
62
+ interface IBindRemoteDeviceParams {
63
+ productKey: string;
64
+ mac: string;
65
+ beOwner?: boolean;
66
+ alias?: string;
67
+ }
68
+
69
+ interface IDeviceStatusNoti {
70
+ device: IDevice;
71
+ connectType: TConnectType;
72
+ }
73
+ interface IDeviceAttrsNoti {
74
+ device: IDevice;
75
+ data: object;
76
+ }
77
+
78
+ export interface TListenerType {
79
+ GizDeviceListNotifications: TDeviceListNotifications;
80
+ GizDeviceStatusNotifications: TDeviceStatusNotifications;
81
+ GizDeviceAttrsNotifications: TDeviceAttrsNotifications;
82
+ onScanListChange: OnScanListChange;
83
+ onBleHandleError: OnBleHandleError;
84
+ }
85
+
86
+ type TDeviceListNotifications = (devices: IDevice[]) => void;
87
+ type TDeviceStatusNotifications = (data: IDeviceStatusNoti) => void;
88
+ type TDeviceAttrsNotifications = (data: IDeviceAttrsNoti) => void;
89
+ type OnScanListChange = (devices: IDevice[]) => void;
90
+ type OnBleHandleError = (error: IError) => void;
91
+
92
+ interface IDeviceSafetyRegisterParams {
93
+ mac: string;
94
+ productKey: string;
95
+ }
96
+
97
+ interface IDeviceSafetyParams extends IDeviceSafetyRegisterParams {
98
+ isReset: boolean;
99
+ }
100
+ export interface IResult<T> {
101
+ success: boolean;
102
+ data?: T;
103
+ err?: IError;
104
+ }
105
+
106
+ interface ICloudServiceInfo {
107
+ openAPIInfo: string;
108
+ siteInfo: string;
109
+ }
110
+
111
+ export type TimeoutHandle = ReturnType<typeof setTimeout> | null;
112
+ export type IntervalHandle = ReturnType<typeof setInterval> | null;
113
+ export interface IProductInfo {
114
+ productKey: string;
115
+ productSecrets: string;
116
+ }
117
+ interface GizwitsSdkOption {
118
+ appID: string;
119
+ appSecret: string;
120
+ productInfo: IProductInfo[];
121
+ cloudServiceInfo?: any;
122
+ token?: string;
123
+ uid?: string;
124
+ offlineThreshold?: number;
125
+ }
126
+
127
+ class SDK {
128
+ private version = '3.0.5';
129
+ private listenerMap: any = {};
130
+
131
+ // 云端获取的设备列表
132
+ private _deviceList: IDevice[] = [];
133
+ private get devieList() {
134
+ return this._deviceList;
135
+ }
136
+ private set devieList(data: IDevice[]) {
137
+ // TODO 覆盖的时候 需要保留netStatus
138
+ this._deviceList = data;
139
+
140
+ // TODO 判断是否发生改变
141
+ this.notiDeviveList();
142
+ }
143
+ // 云端获取的设备列表
144
+
145
+ // ble device
146
+ private _bleDevices: IDevice[] = [];
147
+ public get bleDevices() {
148
+ return this._bleDevices;
149
+ }
150
+ public set bleDevices(data: IDevice[]) {
151
+ this._bleDevices = data;
152
+
153
+ this.notiDeviveList();
154
+ }
155
+ // ble device
156
+
157
+ // udp device
158
+ private _udpDevices: IDevice[] = [];
159
+ private get udpDevices() {
160
+ return this._udpDevices;
161
+ }
162
+ private set udpDevices(data: IDevice[]) {
163
+ this._udpDevices = data;
164
+ this.notiDeviveList();
165
+ }
166
+ // udp device
167
+
168
+ private get allDevices() {
169
+ let newDevices = merageBleLocalDevices(
170
+ [...this.devieList],
171
+ this.bleDevices
172
+ );
173
+ newDevices = merageLanLocalDevices(newDevices, this.udpDevices);
174
+ /**
175
+ * 只能有一种通讯方式
176
+ * 依次LAN BLE WAN
177
+ * 现在没有局域网,先跳过
178
+ */
179
+ this.bleHandle.connectedList.map((item) => {
180
+ const index = newDevices.findIndex(
181
+ (device) => device.bleDeviceID === item.deviceId
182
+ );
183
+ if (index !== -1) {
184
+ newDevices[index].connectType = 'BLE';
185
+ }
186
+ });
187
+ return newDevices;
188
+ }
189
+
190
+ private set allDevice(data: IDevice[]) {
191
+ this.allDevice = data;
192
+ this.notiDeviveList();
193
+ }
194
+
195
+ private get bleScanDevice() {
196
+ return this.bleDevices.filter((item) => item.isBleOnline === true);
197
+ }
198
+
199
+ // private set bleScanDevice(data: IDevice[]){
200
+ // this.bleDevices = data;
201
+ // }
202
+
203
+ private productInfo: IProductInfo[] = [];
204
+ // private cloudServiceInfo: any;
205
+ // 保存当前执行中的配网handle
206
+
207
+ private currentWifiConfigHandle: any;
208
+
209
+ private _bleHandle: BleHandle;
210
+ private autoScanInterval: IntervalHandle = null;
211
+
212
+ private _gizSocket: GizwitsWS;
213
+ private offlineThreshold?: number;
214
+
215
+ constructor({
216
+ appID,
217
+ appSecret,
218
+ productInfo,
219
+ cloudServiceInfo,
220
+ token,
221
+ uid,
222
+ offlineThreshold,
223
+ }: GizwitsSdkOption) {
224
+ // this.appID = appID;
225
+ // this.appSecret = appSecret;
226
+ this.productInfo = productInfo;
227
+ // this.token = token;
228
+ // this.uid = uid;
229
+ // this.cloudServiceInfo = null;
230
+
231
+ // 保存相关信息
232
+ setGlobalData('appID', appID);
233
+ setGlobalData('appSecret', appSecret);
234
+ setGlobalData('productInfo', productInfo);
235
+ setGlobalData('token', token);
236
+ setGlobalData('uid', uid);
237
+
238
+ /**
239
+ * 同时也设置域名信息
240
+ */
241
+ this.setDomain(cloudServiceInfo);
242
+
243
+ this.offlineThreshold = offlineThreshold;
244
+
245
+ console.debug(`init sdk success, current version: ${this.version}`);
246
+ }
247
+
248
+ private get bleHandle() {
249
+ // 初始化蓝牙能力
250
+ if (!this._bleHandle) {
251
+ this._bleHandle = new BleHandle({
252
+ pks: this.specialProductKeys,
253
+ globalListenerMap: this.listenerMap,
254
+ gizSdk: this,
255
+ offlineThreshold: this.offlineThreshold,
256
+ });
257
+ }
258
+ return this._bleHandle;
259
+ }
260
+
261
+ private get socketHandle() {
262
+ if (!this._gizSocket) {
263
+ this._gizSocket = new GizwitsWS({
264
+ appID: getGlobalData('appID'),
265
+ token: getGlobalData('token'),
266
+ uid: getGlobalData('uid'),
267
+ });
268
+ this._gizSocket.subscribeDeviceStatus(this.handleSockerDeviceData);
269
+ }
270
+ return this._gizSocket;
271
+ }
272
+
273
+ get specialProductKeys() {
274
+ return this.productInfo.map((item) => item.productKey ?? '');
275
+ }
276
+
277
+ get specialProductKeySecrets() {
278
+ return this.productInfo.map((item) => item.productSecrets ?? '');
279
+ }
280
+
281
+ private handleBleDeviceData = async (
282
+ curDevice: WechatMiniprogram.OnBLECharacteristicValueChangeCallbackResult,
283
+ hexString: string
284
+ ) => {
285
+ const target = this.allDevices.find(
286
+ (item) => item.bleDeviceID === curDevice.deviceId
287
+ );
288
+ if (target) {
289
+ const data = await unpack(hexStrint2byte(hexString), target.productKey);
290
+ // 如果有kydata 则上报
291
+ if (data?.kvData && this.listenerMap['GizDeviceAttrsNotifications']) {
292
+ this.listenerMap['GizDeviceAttrsNotifications'].map((item) => {
293
+ item({
294
+ device: target,
295
+ data: data?.kvData,
296
+ });
297
+ });
298
+ }
299
+ }
300
+ };
301
+
302
+ private handleSockerDeviceData: IOnDeviceStatusChanged = (data) => {
303
+ const target = this.allDevices.find((item) => item.did === data.did);
304
+ if (!target) {
305
+ return;
306
+ }
307
+ if (this.listenerMap['GizDeviceAttrsNotifications']) {
308
+ this.listenerMap['GizDeviceAttrsNotifications'].map((item) => {
309
+ item({
310
+ device: target,
311
+ ...('attrs' in data ? { data: data.attrs } : { raw: data.raw }),
312
+ });
313
+ });
314
+ }
315
+ };
316
+
317
+ private notiDeviveList = () => {
318
+ // 找到所有挂载的列表通知
319
+ this.listenerMap['GizDeviceListNotifications']?.map((notifyFn) => {
320
+ notifyFn(this.allDevices);
321
+ });
322
+
323
+ this.listenerMap['onScanListChange']?.map((notifyFn) => {
324
+ console.log('this.scanBleDevice', this.bleScanDevice);
325
+ notifyFn(this.bleScanDevice);
326
+ });
327
+ };
328
+
329
+ /**
330
+ * @description 开启后台自动扫描
331
+ */
332
+ public startAutoScan = () => {
333
+ if (this.autoScanInterval) {
334
+ clearInterval(this.autoScanInterval);
335
+ }
336
+ this.autoScanInterval = setInterval(async () => {
337
+ const data = await this.bleHandle.startScan(() => {}, 6000);
338
+ console.log('auto scan result', data);
339
+ this.bleDevices = data.scanList;
340
+ }, 6000);
341
+ };
342
+
343
+ /**
344
+ * @description 停止后台自动扫描
345
+ */
346
+
347
+ public stopAutoScan = () => {
348
+ if (this.autoScanInterval) {
349
+ clearInterval(this.autoScanInterval);
350
+ }
351
+ };
352
+
353
+ /**
354
+ * @description 更改设备列表中的元信息,包括设备mac,设备在线状态等
355
+ */
356
+ public setDeviceMeta = <K extends keyof IDevice>(
357
+ curDev: IDevice,
358
+ key: K,
359
+ value: IDevice[K]
360
+ ) => {
361
+ const target = this.allDevices.find((dev) => dev.mac === curDev.mac);
362
+ if (!target || this.allDevices.length === 0) {
363
+ return;
364
+ }
365
+ target[key] = value;
366
+ console.log('setDeviceMeta', this.allDevices);
367
+ this.notiDeviveList();
368
+ };
369
+
370
+ getVersion = () => {
371
+ return {
372
+ success: true,
373
+ data: this.version,
374
+ };
375
+ };
376
+
377
+ /**
378
+ * 初始化蓝牙能力
379
+ * @returns {Promise<{success: boolean, err: string}>}
380
+ */
381
+ public initBle = async (): Promise<ISDKResult<null>> => {
382
+ const permissionData = await this.bleHandle.checkPermission();
383
+ if (!permissionData.success) {
384
+ console.error('init BLE Error', permissionData);
385
+ return {
386
+ success: false,
387
+ err: errorCode.GIZ_SDK_BLE_BLUETOOTH_FUNCTION_NOT_TURNED_ON,
388
+ };
389
+ }
390
+
391
+ this.bleHandle.addDeviceListener('ALL', this.handleBleDeviceData);
392
+ console.debug('init BLE succcess', permissionData);
393
+ return { success: true };
394
+ };
395
+
396
+ /**
397
+ * @description 扫描附近的机智云ble设备
398
+ * @param delay 超时时间
399
+ * @returns {success:boolean,data:IDevice[]}
400
+ */
401
+ public scanBleDevice = async (
402
+ delay: number
403
+ ): Promise<ISDKResult<IDevice[]>> => {
404
+ console.log('start scanBleDevice');
405
+ this.bleHandle.scanList = [];
406
+ const data = await this.bleHandle.startScan((deviceList) => {
407
+ this.bleDevices = deviceList;
408
+ }, delay);
409
+ console.debug('scanBleDevice', data);
410
+ return {
411
+ success: true,
412
+ data: data.scanList,
413
+ };
414
+ };
415
+
416
+ write = async (device: IDevice, attrs: object) => {
417
+ console.log('待发送指令:', device, attrs);
418
+ const target = this.allDevices.find((item) => isSameDevice(item, device));
419
+ if (!target) {
420
+ return { success: false, message: 'target is undefind' };
421
+ }
422
+ if (target.connectType !== 'NONE') {
423
+ switch (target.connectType) {
424
+ case 'BLE': {
425
+ const value = await pack(attrs, target.productKey);
426
+ if (value) {
427
+ console.log('write cmd', value, attrs);
428
+ this.bleHandle.write(
429
+ target.bleDeviceID as string,
430
+ numberArray2Uint8Array(value).buffer
431
+ );
432
+ } else {
433
+ // 解码失败
434
+ }
435
+
436
+ break;
437
+ }
438
+ case 'WAN': {
439
+ this.socketHandle.writeData(target, attrs);
440
+ }
441
+ }
442
+ }
443
+ };
444
+
445
+ getProductConfig = async (
446
+ pk: string
447
+ ): Promise<ISDKResult<IDataPointConfig>> => {
448
+ const data = await productConfigFileManage.getConfigFile(pk);
449
+ if (data) {
450
+ return {
451
+ success: true,
452
+ data,
453
+ };
454
+ }
455
+ return {
456
+ success: false,
457
+ };
458
+ };
459
+
460
+ stopScanBleDevice = () => {
461
+ this.bleHandle.stopScan();
462
+ };
463
+
464
+ // 微信匿名登陆
465
+ login = async (openID: string): Promise<ISDKResult<ILoginRes>> => {
466
+ const data = await AnonymousLogin({ uid: openID });
467
+ if (data.success) {
468
+ setGlobalData('token', data.data?.token);
469
+ setGlobalData('uid', data.data?.uid);
470
+ }
471
+ return data;
472
+ };
473
+
474
+ getDeviceStatus = async (device: IDevice, attrNames?: string[]) => {
475
+ // 根据PK和mac 找到设备,确认他的连接类型,再用不同的渠道下发
476
+ const target = this.allDevices.find((item) => isSameDevice(item, device));
477
+ if (!target) {
478
+ return { success: false, message: 'target is undefind' };
479
+ }
480
+ switch (target.connectType) {
481
+ case 'BLE': {
482
+ return await this.bleHandle.getDeviceStatus(
483
+ target.bleDeviceID as string,
484
+ target.productKey,
485
+ target.rootDeviceId,
486
+ attrNames
487
+ );
488
+ }
489
+ case 'WAN':
490
+ return this.socketHandle.readStatus(target, attrNames);
491
+ default: {
492
+ return {
493
+ success: false,
494
+ message: 'Device connectType is unsupported',
495
+ };
496
+ }
497
+ }
498
+ };
499
+
500
+ /**
501
+ * 发起设备订阅
502
+ * @param device 待订阅设备
503
+ * @param connectType 设备连接类型
504
+ * @param _autoGetDeviceStatus 自动获取设备状态
505
+ * @returns
506
+ */
507
+ subscribe = async (
508
+ device: IDevice,
509
+ connectType?: TConnectType,
510
+ _autoGetDeviceStatus: boolean = true
511
+ ) => {
512
+ const type: TConnectType = getFirstConnectType(device, connectType);
513
+ switch (type) {
514
+ case 'BLE': {
515
+ // 连接BLE
516
+ const target = this.bleDevices.find((item) =>
517
+ isSameDevice(item, device)
518
+ );
519
+ if (!target) {
520
+ return { success: false };
521
+ }
522
+ const data = await this.bleHandle.connectDevice(target.bleDeviceID);
523
+ if (data.success) {
524
+ this.setDeviceMeta(target, 'connectType', 'BLE');
525
+ setTimeout(() => {
526
+ this.getDeviceStatus(target);
527
+ }, 500);
528
+ } else {
529
+ this.bleHandle.disConnectDevice(target.bleDeviceID);
530
+ }
531
+ return data;
532
+ }
533
+ case 'WAN': {
534
+ // 大循环设备
535
+ const data = this.socketHandle.connectDevice(device);
536
+ if (data.success) {
537
+ this.setDeviceMeta(device, 'connectType', 'WAN');
538
+ }
539
+ return data;
540
+ }
541
+ }
542
+ return {
543
+ success: false,
544
+ };
545
+ };
546
+
547
+ /**
548
+ *
549
+ * @param device 待取消订阅设备
550
+ * @returns 取消订阅结果
551
+ */
552
+ unSubscribe = async (device: IDevice) => {
553
+ switch (device.connectType) {
554
+ case 'BLE': {
555
+ const disconnectRes = await this.bleHandle.disConnectDevice(
556
+ device.bleDeviceID as string
557
+ );
558
+ if (disconnectRes.success) {
559
+ this.setDeviceMeta(device, 'connectType', 'NONE');
560
+ }
561
+ return disconnectRes;
562
+ }
563
+ }
564
+ return {
565
+ success: false,
566
+ };
567
+ };
568
+
569
+ /**
570
+ * 绑定注册到云端的设备
571
+ * 设备必须要注册到云端才能正常绑定
572
+ */
573
+ bindRemoteDevice = async ({
574
+ mac,
575
+ productKey,
576
+ alias,
577
+ beOwner,
578
+ }: IBindRemoteDeviceParams): Promise<ISDKResult<IOpenApiDevice>> => {
579
+ const target = getProductInfoThroughPK(productKey, this.productInfo);
580
+ if (target) {
581
+ const data = await bindMac({
582
+ mac,
583
+ productKey,
584
+ productSecret: target.productSecrets,
585
+ alias,
586
+ beOwner,
587
+ });
588
+ // 绑定成功主动获取设备列表
589
+ this.getBindingList();
590
+ return data;
591
+ }
592
+ return {
593
+ success: false,
594
+ err: errorCode.GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIFY,
595
+ };
596
+ };
597
+
598
+ unbindDevice = async ({
599
+ devices,
600
+ }: {
601
+ devices: IDevice[];
602
+ }): Promise<ISDKResult<IUnbindReturn>> => {
603
+ const data = await unbindDevice({ devices });
604
+ // 主动刷新列表
605
+ if (data.success) {
606
+ this.getBindingList();
607
+ }
608
+ return data;
609
+ };
610
+
611
+ deviceSafetyRegister = async ({
612
+ mac,
613
+ productKey,
614
+ }: IDeviceSafetyRegisterParams): Promise<ISDKResult<ISafeRegisterReturn>> => {
615
+ return await this.deviceSafetyApi({ mac, productKey, isReset: false });
616
+ };
617
+ deviceSafetyUnbind = async ({
618
+ mac,
619
+ productKey,
620
+ }: IDeviceSafetyRegisterParams): Promise<ISDKResult<ISafeRegisterReturn>> => {
621
+ return await this.deviceSafetyApi({ mac, productKey, isReset: true });
622
+ };
623
+
624
+ /**
625
+ * 配网接口
626
+ * setDeviceOnboardingDeploy方法不可重复调用
627
+ */
628
+ setDeviceOnboardingDeploy = async ({
629
+ ssid,
630
+ password,
631
+ mode = 0,
632
+ timeout,
633
+ isBind = true,
634
+ softAPSSIDPrefix,
635
+ }: ISetDeviceOnboardingDeployProps): Promise<ISDKResult<IDevice[]>> => {
636
+ if (this.currentWifiConfigHandle) {
637
+ return {
638
+ success: false,
639
+ err: errorCode.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING,
640
+ };
641
+ }
642
+ const sTime = new Date().getTime();
643
+ console.debug('GIZ_SDK: 配网开始时间:' + sTime);
644
+ try {
645
+ switch (mode) {
646
+ case 0: {
647
+ this.currentWifiConfigHandle = new ApConfig(
648
+ ssid,
649
+ password,
650
+ this.specialProductKeys,
651
+ this.specialProductKeySecrets
652
+ );
653
+ const data =
654
+ await this.currentWifiConfigHandle.setDeviceOnboardingDeploy({
655
+ timeout,
656
+ isBind,
657
+ softAPSSIDPrefix,
658
+ });
659
+ this.currentWifiConfigHandle = null;
660
+ const eTime = new Date().getTime();
661
+ console.debug('GIZ_SDK: 配网结束时间:' + eTime);
662
+ console.debug('GIZ_SDK: 配网用时:' + (eTime - sTime));
663
+ return data;
664
+ }
665
+ case 3: {
666
+ this.currentWifiConfigHandle = new BLEConfig(
667
+ ssid,
668
+ password,
669
+ this.specialProductKeys,
670
+ this.specialProductKeySecrets
671
+ );
672
+ const data =
673
+ await this.currentWifiConfigHandle.setDeviceOnboardingDeploy({
674
+ timeout,
675
+ isBind,
676
+ softAPSSIDPrefix,
677
+ });
678
+ this.currentWifiConfigHandle = null;
679
+ const eTime = new Date().getTime();
680
+ console.debug('GIZ_SDK: 配网结束时间:' + eTime);
681
+ console.debug('GIZ_SDK: 配网用时:' + (eTime - sTime));
682
+ return data;
683
+ }
684
+ }
685
+ } catch (error) {
686
+ console.error(error);
687
+ if (
688
+ (error as ISDKResult<IDevice[]>).err &&
689
+ (error as ISDKResult<IDevice[]>).err!.errorCode
690
+ ) {
691
+ return error as ISDKResult<IDevice[]>;
692
+ }
693
+ return {
694
+ success: false,
695
+ err: errorCode.GIZ_SDK_OTHERWISE,
696
+ };
697
+ } finally {
698
+ this.currentWifiConfigHandle = null;
699
+ }
700
+ };
701
+
702
+ /**
703
+ * 设置域名
704
+ */
705
+ private setDomain = (cloudServiceInfo: ICloudServiceInfo) => {
706
+ const openAPIInfo =
707
+ (cloudServiceInfo && cloudServiceInfo.openAPIInfo) || 'api.gizwits.com';
708
+
709
+ const siteInfo =
710
+ (cloudServiceInfo && cloudServiceInfo.siteInfo) || 'site.gizwits.com';
711
+
712
+ const newData = { ...(cloudServiceInfo || {}), openAPIInfo, siteInfo };
713
+ setGlobalData('cloudServiceInfo', newData);
714
+ };
715
+
716
+ private deviceSafetyApi = async ({
717
+ mac,
718
+ productKey,
719
+ isReset,
720
+ }: IDeviceSafetyParams): Promise<ISDKResult<ISafeRegisterReturn>> => {
721
+ const target = getProductInfoThroughPK(productKey, this.productInfo);
722
+ if (target) {
723
+ return await safeRegister({
724
+ productKey,
725
+ productSecret: target.productSecrets,
726
+ mac,
727
+ isReset,
728
+ passcode: '1234567890',
729
+ });
730
+ }
731
+ return {
732
+ success: false,
733
+ err: errorCode.GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIFY,
734
+ };
735
+ };
736
+
737
+ // 内部刷新设备列表的方法
738
+ public getBindingList = async () => {
739
+ const data = await getBindingList();
740
+ this.devieList = data.data || [];
741
+ };
742
+
743
+ /**
744
+ * 刷新云端设备列表
745
+ * 并合并数据
746
+ */
747
+ public getDevices = async (): Promise<ISDKResult<IDevice[]>> => {
748
+ // merage
749
+ await this.getBindingList();
750
+ // 简单粗暴的先合并
751
+ return {
752
+ success: true,
753
+ data: this.allDevices,
754
+ };
755
+ };
756
+
757
+ /**
758
+ * 停止配网
759
+ */
760
+ stopDeviceOnboardingDeploy = (): void => {
761
+ if (this.currentWifiConfigHandle) {
762
+ this.currentWifiConfigHandle.stopDeviceOnboardingDeploy();
763
+ this.currentWifiConfigHandle = null;
764
+ }
765
+ };
766
+
767
+ /**
768
+ * 移除事件监听
769
+ * @param type 事件监听名称,详见下表
770
+ * @param func 事件监听回调
771
+ * @returns
772
+ */
773
+ public removeEventListener = <K extends keyof TListenerType>(
774
+ type: K,
775
+ func: TListenerType[K]
776
+ ) => {
777
+ if (this.listenerMap[type]) {
778
+ const index = this.listenerMap[type].indexOf(func);
779
+ if (index !== -1) {
780
+ // 删除数组中的这一行
781
+ this.listenerMap[type].splice(index, 1);
782
+ return {
783
+ success: true,
784
+ };
785
+ }
786
+ }
787
+ return {
788
+ success: false,
789
+ // err: errorCode.GIZ_SDK_BLE_BLUETOOTH_FUNCTION_NOT_TURNED_ON
790
+ };
791
+ };
792
+
793
+ public addEventListener = async <K extends keyof TListenerType>(
794
+ type: K,
795
+ func: TListenerType[K]
796
+ ) => {
797
+ if (!this.listenerMap[type]) {
798
+ // 创建一个新的
799
+ this.listenerMap[type] = [];
800
+ }
801
+
802
+ if (this.listenerMap[type].indexOf(func) === -1) {
803
+ this.listenerMap[type].push(func);
804
+ }
805
+ return {
806
+ success: true,
807
+ };
808
+ };
809
+ }
810
+
811
+ export default SDK;