mini_program_gizwits_sdk 3.7.0-kuka → 3.7.0

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 (63) hide show
  1. package/README.md +96 -25
  2. package/{index.ts → dist/index.d.ts} +3 -3
  3. package/dist/index.js +5 -5
  4. package/global.d.ts +3 -19
  5. package/package.json +5 -5
  6. package/yarn-error.log +34 -34
  7. package/src/GizLog.ts +0 -51
  8. package/src/aepApi/aepApiRequest.ts +0 -61
  9. package/src/crc/calculators/crc16modbus.ts +0 -36
  10. package/src/crc/calculators/crc32.ts +0 -47
  11. package/src/crc/crc16modbus.ts +0 -3
  12. package/src/crc/crc32.ts +0 -4
  13. package/src/crc/create_buffer.ts +0 -7
  14. package/src/crc/define_crc.ts +0 -9
  15. package/src/crc/index.ts +0 -10
  16. package/src/crc/package.json +0 -3
  17. package/src/crc/types.ts +0 -10
  18. package/src/errorCode.ts +0 -84
  19. package/src/global.d.ts +0 -53
  20. package/src/globalData.ts +0 -9
  21. package/src/handler/EventListener.ts +0 -44
  22. package/src/handler/ble.ts +0 -1485
  23. package/src/handler/lan.ts +0 -409
  24. package/src/handler/socket.ts +0 -625
  25. package/src/openApiRequest.ts +0 -62
  26. package/src/productConfigFileManage.ts +0 -58
  27. package/src/protocol/Bind.ts +0 -22
  28. package/src/protocol/DeviceInfo.ts +0 -36
  29. package/src/protocol/DiscoverUDP.ts +0 -80
  30. package/src/protocol/GetDeviceStatus.ts +0 -63
  31. package/src/protocol/Login.ts +0 -43
  32. package/src/protocol/Ntp.ts +0 -13
  33. package/src/protocol/OTA/AwaitNoti.ts +0 -14
  34. package/src/protocol/OTA/CheckCanOTA.ts +0 -23
  35. package/src/protocol/OTA/OTAPackPackage.ts +0 -36
  36. package/src/protocol/OTA/OtaComplete.ts +0 -17
  37. package/src/protocol/OTA/PreOTA.ts +0 -47
  38. package/src/protocol/OTA/ResetPosition.ts +0 -14
  39. package/src/protocol/OffLineData.ts +0 -81
  40. package/src/protocol/ProtocolBase.ts +0 -54
  41. package/src/protocol/Reset.ts +0 -15
  42. package/src/protocol/SetReset.ts +0 -11
  43. package/src/protocol/WifiConfig.ts +0 -42
  44. package/src/protocol/dataPoint.ts +0 -769
  45. package/src/protocol/thirdProtocol/YunZhiMianBleProtocolBase.ts +0 -39
  46. package/src/protocol/tool.ts +0 -147
  47. package/src/randomCode.ts +0 -36
  48. package/src/request.ts +0 -22
  49. package/src/sdk.ts +0 -1472
  50. package/src/sentry.ts +0 -55
  51. package/src/services/devices.ts +0 -309
  52. package/src/services/login.ts +0 -15
  53. package/src/services/ota.ts +0 -30
  54. package/src/services/tool.ts +0 -10
  55. package/src/services/uploadP0.ts +0 -56
  56. package/src/sleep.ts +0 -2
  57. package/src/types/index.ts +0 -48
  58. package/src/utils.ts +0 -419
  59. package/src/wechatApi.ts +0 -210
  60. package/src/wifiConfig/ConfigBase.ts +0 -185
  61. package/src/wifiConfig/ap.ts +0 -192
  62. package/src/wifiConfig/ble.ts +0 -436
  63. package/src/wifiConfig/ble_ailCloud.ts +0 -554
package/src/sdk.ts DELETED
@@ -1,1472 +0,0 @@
1
- import { setGlobalData, getGlobalData } from './globalData';
2
- import { BleHandle } from './handler/ble';
3
- import GizwitsWS from './handler/socket';
4
-
5
- import ApConfig from './wifiConfig/ap';
6
- import BLEConfig from './wifiConfig/ble';
7
- import BLEAliConfig from './wifiConfig/ble_ailCloud';
8
- import GizLog, { TLogType } from './GizLog';
9
- import errorCode from './errorCode';
10
- import { AnonymousLogin, ILoginRes } from './services/login';
11
- import {
12
- bindMac,
13
- editBindInfo,
14
- getBindingList,
15
- IOpenApiDevice,
16
- ISafeRegisterReturn,
17
- IUnbindReturn,
18
- safeRegister,
19
- unbindDevice,
20
- } from './services/devices';
21
- import {
22
- getFirstConnectType,
23
- getProductInfoThroughPK,
24
- isSameDevice,
25
- merageBleLocalDevices,
26
- merageLanLocalDevices,
27
- numberArray2Uint8Array,
28
- } from './utils';
29
- import productConfigFileManage from './productConfigFileManage';
30
- import { formatEnum, IDataPointConfig, pack, unpack } from './protocol/DataPoint';
31
- import { arrayToString, hexStrint2byte } from './protocol/tool';
32
- import { LanHandle } from './handler/lan';
33
- import ProtocolBase from './protocol/ProtocolBase';
34
- import { CancelSync, DeletePackage, RequestSync, SyncPackage } from './protocol/OffLineData';
35
- import { uploadP0 } from './services/uploadP0';
36
- import sleep from './sleep';
37
- import Ntp from './protocol/Ntp';
38
- import Reset from './protocol/Reset';
39
- import SetReset from './protocol/SetReset';
40
- import { IOTAType, OTAEventCallback, OTAProgressEventCallback } from './types';
41
-
42
- interface SyncCallBackParams {
43
- event: TSyncEvnet;
44
- currentNum?: number;
45
- totalNum?: number;
46
- message?: string;
47
- }
48
- type TSyncEvnet = 'SYNC_START' | 'SYNC_END' | 'SYNC_FAIL' | 'SYNC_CANCEL' | 'SYNC_PROGRESS';
49
- export type SyncCallBack = (data: SyncCallBackParams) => void;
50
-
51
- // 接口返回格式
52
- export interface ISDKResult<T> {
53
- data?: T;
54
- err?: IError;
55
- message?: string;
56
- success: boolean;
57
- }
58
- export interface ISetCommonDeviceOnboardingDeployProps {
59
- ssid: string;
60
- password: string;
61
- timeout: number;
62
- isBind?: boolean;
63
- mode?: 0 | 3 | 10; // 0 AP 3 BLE 10 BLE Ali
64
- softAPSSIDPrefix?: string;
65
- }
66
-
67
- export interface ISetDeviceOnboardingDeployProps extends ISetCommonDeviceOnboardingDeployProps {
68
- softAPSSIDPrefix: string;
69
- productKeys?: string[];
70
- }
71
-
72
- export interface IRandomCodesResult {
73
- random_code: string;
74
- product_key: string;
75
- mac: string;
76
- did: string;
77
- user_id: string;
78
- timestamp: number;
79
- type: string;
80
- wifi_soft_ver: string;
81
- lan_proto_ver: string;
82
- }
83
-
84
- interface IBindRemoteDeviceParams {
85
- productKey: string;
86
- mac: string;
87
- beOwner?: boolean;
88
- alias?: string;
89
- }
90
-
91
- interface IDeviceStatusNoti {
92
- device: IDevice;
93
- connectType: TConnectType;
94
- }
95
- interface IDeviceAttrsNoti {
96
- device: IDevice;
97
- data: object;
98
- }
99
- interface IBleDeviceDataNoti {
100
- device: IDevice;
101
- data: object;
102
- }
103
-
104
- export interface TListenerType {
105
- GizDeviceListNotifications: TDeviceListNotifications;
106
- GizDeviceStatusNotifications: TDeviceStatusNotifications;
107
- GizDeviceAttrsNotifications: TDeviceAttrsNotifications;
108
- onScanListChange: OnScanListChange;
109
- onBleHandleError: OnBleHandleError;
110
- onBleDeviceDataNotifications: TBleDeviceDataNotifications;
111
- }
112
-
113
- type TDeviceListNotifications = (devices: IDevice[]) => void;
114
- type TDeviceStatusNotifications = (data: IDeviceStatusNoti) => void;
115
- type TDeviceAttrsNotifications = (data: IDeviceAttrsNoti) => void;
116
- type OnScanListChange = (devices: IDevice[]) => void;
117
- type OnBleHandleError = (error: IError) => void;
118
- type TBleDeviceDataNotifications = (data: IBleDeviceDataNoti) => void;
119
-
120
- interface IDeviceSafetyRegisterParams {
121
- mac: string;
122
- productKey: string;
123
- }
124
-
125
- interface IDeviceSafetyParams extends IDeviceSafetyRegisterParams {
126
- isReset: boolean;
127
- }
128
- export interface IResult<T> {
129
- success: boolean;
130
- data?: T;
131
- err?: IError;
132
- }
133
-
134
- interface ICloudServiceInfo {
135
- openAPIInfo: string;
136
- aepInfo: string;
137
- }
138
-
139
- export type TimeoutHandle = ReturnType<typeof setTimeout> | null;
140
- export type IntervalHandle = ReturnType<typeof setInterval> | null;
141
- export interface IProductInfo {
142
- productKey: string;
143
- productSecret: string;
144
- }
145
- interface GizwitsSdkOption {
146
- appID: string;
147
- appSecret: string;
148
- productInfo: IProductInfo[];
149
- cloudServiceInfo?: ICloudServiceInfo;
150
- token?: string;
151
- uid?: string;
152
- offlineThreshold?: number;
153
- }
154
-
155
- class GizwitsMiniSDK {
156
- private version = '3.6.6-kuka';
157
- private listenerMap: any = {};
158
- private keepScanTimer: any = null;
159
-
160
- // 云端获取的设备列表
161
- private _deviceList: IDevice[] = [];
162
- private get deviceList() {
163
- return this._deviceList;
164
- }
165
- private set deviceList(data: IDevice[]) {
166
- // TODO 覆盖的时候 需要保留netStatus
167
- this._deviceList = data;
168
-
169
- // TODO 判断是否发生改变
170
- this.notiDeviceList();
171
- }
172
- // 云端获取的设备列表
173
-
174
- // ble device
175
- private _bleDevices: IDevice[] = [];
176
- public get bleDevices() {
177
- return this._bleDevices;
178
- }
179
- public set bleDevices(data: IDevice[]) {
180
- this._bleDevices = data;
181
-
182
- this.notiDeviceList();
183
- }
184
- // ble device
185
-
186
- // udp device
187
- private _lanDevices: IDevice[] = [];
188
- private get lanDevices() {
189
- return this._lanDevices;
190
- }
191
- private set lanDevices(data: IDevice[]) {
192
- this._lanDevices = data;
193
- this.notiDeviceList();
194
- }
195
- // udp device
196
-
197
- private get allDevices() {
198
- let newDevices = merageBleLocalDevices([...this.deviceList], this.bleDevices);
199
- newDevices = merageLanLocalDevices(newDevices, this.lanDevices);
200
- /**
201
- * 只能有一种通讯方式
202
- * 依次LAN BLE WAN
203
- * 现在没有局域网,先跳过
204
- */
205
- this.bleHandle.connectedList.map(item => {
206
- const index = newDevices.findIndex(device => device.bleDeviceID === item.deviceId);
207
- if (index !== -1) {
208
- newDevices[index].connectType = 'BLE';
209
- }
210
- });
211
-
212
- const connectionMap = this.socketHandle._connections;
213
-
214
- Object.keys(connectionMap).forEach(wsInfo => {
215
- const conn = connectionMap[wsInfo];
216
- if (conn) {
217
- conn._subDids.forEach(did => {
218
- const index = newDevices.findIndex(device => device.did === did);
219
- if (index !== -1) {
220
- newDevices[index].connectType = 'WAN';
221
- }
222
- });
223
- }
224
- });
225
-
226
- const lanConnected = this.lanHandle.connectedList;
227
- lanConnected.map(item => {
228
- const index = newDevices.findIndex(device => device.mac === item.mac && device.productKey === item.productKey);
229
- if (index !== -1) {
230
- newDevices[index].connectType = 'LAN';
231
- }
232
- });
233
- console.log('newDevices', newDevices);
234
- return newDevices;
235
- }
236
-
237
- // private set allDevice(data: IDevice[]) {
238
- // this.allDevice = data;
239
- // this.notiDeviceList();
240
- // }
241
-
242
- private get bleScanDevice() {
243
- return this.bleDevices.filter(item => item.isBleOnline === true);
244
- }
245
-
246
- // private set bleScanDevice(data: IDevice[]){
247
- // this.bleDevices = data;
248
- // }
249
-
250
- private productInfo: IProductInfo[] = [];
251
- // private cloudServiceInfo: any;
252
- // 保存当前执行中的配网handle
253
-
254
- private currentWifiConfigHandle: any;
255
-
256
- private _bleHandle: BleHandle;
257
- private _lanHandle: LanHandle;
258
-
259
- // private autoScanInterval: IntervalHandle = null;
260
-
261
- private _gizSocket: GizwitsWS;
262
- private offlineThreshold?: number;
263
-
264
- // 离线同步
265
- private syncDataCallBack?: SyncCallBack = null;
266
- private syncDataLengthCallback?: any;
267
- private syncTotalNum: number = 0;
268
- private syncCurrnetNum: number = 0;
269
- private syncDataTimoutTimer: any = null;
270
- private SYNC_TIMEOUT: number = 4 * 60 * 1000;
271
- private syncDevice?: IDevice;
272
-
273
- constructor({ appID, appSecret, productInfo, cloudServiceInfo, token, uid, offlineThreshold }: GizwitsSdkOption) {
274
- this.productInfo = productInfo;
275
- // 保存相关信息
276
- setGlobalData('appID', appID);
277
- setGlobalData('appSecret', appSecret);
278
- setGlobalData('productInfo', productInfo);
279
- setGlobalData('token', token);
280
- setGlobalData('uid', uid);
281
-
282
- /**
283
- * 同时也设置域名信息
284
- */
285
- this.setDomain(cloudServiceInfo);
286
-
287
- this.offlineThreshold = offlineThreshold;
288
-
289
- GizLog.warn(`init sdk success, current version: ${this.version}`);
290
-
291
- /**
292
- * lan 比较特殊
293
- * 初始化sdk的时候就要开始扫描设备
294
- */
295
- this.initLan();
296
- }
297
-
298
- private get bleHandle() {
299
- // 初始化蓝牙能力
300
- if (!this._bleHandle) {
301
- this._bleHandle = new BleHandle({
302
- pks: this.specialProductKeys,
303
- offlineThreshold: this.offlineThreshold,
304
- });
305
- }
306
- return this._bleHandle;
307
- }
308
-
309
- private get lanHandle() {
310
- if (!this._lanHandle) {
311
- this._lanHandle = new LanHandle({
312
- pks: this.specialProductKeys,
313
- });
314
- }
315
- return this._lanHandle;
316
- }
317
-
318
- private get socketHandle() {
319
- if (!this._gizSocket) {
320
- this._gizSocket = new GizwitsWS({
321
- appID: getGlobalData('appID'),
322
- token: getGlobalData('token'),
323
- uid: getGlobalData('uid'),
324
- });
325
- this._gizSocket.subscribeDeviceStatus(this.handleSocketDeviceData);
326
- this._gizSocket.subscribeBindingChanged(this.getBindingList);
327
- this._gizSocket.subscribeSocketStatus(this.handleSocketStatus);
328
- }
329
- return this._gizSocket;
330
- }
331
-
332
- get specialProductKeys() {
333
- return this.productInfo.map(item => item.productKey ?? '');
334
- }
335
-
336
- get specialProductKeySecrets() {
337
- return this.productInfo.map(item => item.productSecret ?? '');
338
- }
339
-
340
- private handleBleError = e => {
341
- if (this.listenerMap['onBleHandleError']) {
342
- this.listenerMap['onBleHandleError'].map(item => {
343
- item(e);
344
- });
345
- }
346
- };
347
-
348
- private handleBleDevices = (devices: IDevice[]) => {
349
- this.bleDevices = devices;
350
- // this.notiDeviceList();
351
- };
352
-
353
- handleLanDevices = (devices: IDevice[]) => {
354
- this.lanDevices = devices;
355
- };
356
-
357
- private handleLanDeviceData = async (mac: string, hexString: string) => {
358
- const target = this.allDevices.find(item => item.mac === mac);
359
- if (target) {
360
- const data = await unpack(hexStrint2byte(hexString), target.productKey);
361
- // 如果有kydata 则上报
362
- if (data?.kvData && this.listenerMap['GizDeviceAttrsNotifications']) {
363
- this.listenerMap['GizDeviceAttrsNotifications'].map(item => {
364
- item({
365
- device: target,
366
- data: data?.kvData,
367
- });
368
- });
369
- }
370
- }
371
- };
372
-
373
- private getBleProductProtocalType = (device: IDevice) => {
374
- if (
375
- device.productKey === '67a95f560e464453be079c5723a4a85c' ||
376
- device.productKey === '0b58c73f12064eb897aa005cf43d6a1b' ||
377
- device.productKey === '4b286229884f4711bcdbaefdfb5f76b9'
378
- ) {
379
- return 'direct';
380
- }
381
- return 'normal';
382
- };
383
-
384
- private handleBleDeviceData = async (
385
- curDevice: WechatMiniprogram.OnBLECharacteristicValueChangeCallbackResult,
386
- hexString: string
387
- ) => {
388
- const target = this.allDevices.find(item => item.bleDeviceID === curDevice.deviceId);
389
- if (target) {
390
- if (this.getBleProductProtocalType(target) === 'direct') {
391
- // 如果产品类型是直接传输型的,直接通知蓝牙原始数据
392
- const bleBytesData = hexStrint2byte(hexString);
393
- if (this.listenerMap['onBleDeviceDataNotifications']) {
394
- this.listenerMap['onBleDeviceDataNotifications'].map(item => {
395
- item({
396
- device: target,
397
- data: bleBytesData,
398
- });
399
- });
400
- }
401
- return;
402
- }
403
- const bleBytesData = hexStrint2byte(hexString);
404
- const parseData = new ProtocolBase(bleBytesData);
405
- GizLog.warn('===收到蓝牙数据===', new Date().getTime());
406
- switch (parseData.cmd) {
407
- case '0093':
408
- case '0094':
409
- case '0090':
410
- case '0091': {
411
- // 设备上报的指令,上传给后台
412
- console.debug('handleBleDeviceData', hexString, target);
413
- if (target.passcode) {
414
- const productConfig = this.productInfo.find(item => item.productKey === target.productKey);
415
- if (productConfig) {
416
- const uploadTime = parseInt(`${Date.now() / 1000}`, 10);
417
- uploadP0({
418
- device: target,
419
- data: [
420
- {
421
- raw: hexString,
422
- created_at: uploadTime,
423
- },
424
- ],
425
- productSecret: productConfig.productSecret,
426
- }).then(data => {
427
- GizLog.debug('设备上报数据:timestemp', new Date(uploadTime * 1000).toLocaleString(), data);
428
- });
429
- }
430
- }
431
- const data = await unpack(hexStrint2byte(hexString), target.productKey);
432
- // 如果有kydata 则上报
433
- if (data?.kvData && this.listenerMap['GizDeviceAttrsNotifications']) {
434
- this.listenerMap['GizDeviceAttrsNotifications'].map(item => {
435
- item({
436
- device: target,
437
- data: data?.kvData,
438
- });
439
- });
440
- }
441
- break;
442
- }
443
- case '0062': {
444
- // 蓝牙重置命令,app代理设备进行重置
445
- const resetInfo = new Reset(bleBytesData);
446
- GizLog.debug('收到代理重置事件', resetInfo);
447
-
448
- if (resetInfo.status === 1) {
449
- // 需要重置
450
- this.deviceSafetyApi({
451
- mac: target.mac,
452
- productKey: target.productKey,
453
- isReset: true,
454
- }).then(async data => {
455
- GizLog.debug('代理重置结果', data);
456
- if (data.success && data.data.successDevices.length > 0) {
457
- // 回写数据
458
- GizLog.debug('重置成功,回写数据');
459
- await this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(SetReset.pack(0)).buffer);
460
- }
461
- });
462
- }
463
- break;
464
- }
465
- case '0052': {
466
- // 设备回复是否允许同步数据
467
- const requestSyncData = new RequestSync(bleBytesData);
468
- GizLog.debug('设备回复是否允许同步, state:', requestSyncData.state);
469
-
470
- this.syncDataLengthCallback &&
471
- this.syncDataLengthCallback({ success: requestSyncData.state == 0, data: requestSyncData.len });
472
-
473
- if (!this.syncDataCallBack) break;
474
- if (requestSyncData.state === 0) {
475
- // 开始同步
476
- this.syncCurrnetNum = 0;
477
- this.syncTotalNum = requestSyncData.len;
478
- this.syncDataCallBack({
479
- event: 'SYNC_START',
480
- totalNum: this.syncTotalNum,
481
- currentNum: this.syncCurrnetNum,
482
- });
483
- // 读取第0条
484
- GizLog.debug('查询第一条离线数据');
485
- await this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(SyncPackage.pack(0)).buffer);
486
- } else {
487
- GizLog.debug('设备返回状态为1,同步失败');
488
-
489
- // 同步失败
490
- this.syncDataCallBack({
491
- event: 'SYNC_FAIL',
492
- });
493
- }
494
- break;
495
- }
496
- case '0054': {
497
- if (!this.syncDataCallBack) break;
498
- // 设备上报需要同步的数据
499
- GizLog.debug('设备上报离线数据');
500
-
501
- const syncPackageData = new SyncPackage(bleBytesData);
502
- const deletePackageCmd = DeletePackage.pack(syncPackageData.id);
503
- GizLog.debug('设备上报离线数据:payload', syncPackageData.payload);
504
- try {
505
- GizLog.debug('设备上报离线数据:timestemp', new Date(syncPackageData.timestemp * 1000).toLocaleString());
506
- } catch (error) {}
507
-
508
- const productConfig = this.productInfo.find(item => item.productKey === this.syncDevice.productKey);
509
- if (productConfig) {
510
- const uploadRes = await uploadP0({
511
- device: this.syncDevice,
512
- data: [
513
- {
514
- raw: arrayToString(syncPackageData.payload),
515
- created_at: syncPackageData.timestemp,
516
- },
517
- ],
518
- productSecret: productConfig.productSecret,
519
- });
520
- GizLog.debug('上传离线数据结果', uploadRes);
521
- }
522
-
523
- this.syncCurrnetNum += 1;
524
- // 通知设备删除
525
- this.syncDataCallBack({
526
- event: 'SYNC_PROGRESS',
527
- totalNum: this.syncTotalNum,
528
- currentNum: this.syncCurrnetNum,
529
- });
530
-
531
- GizLog.debug('通知设备删除:', syncPackageData.id);
532
- await this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(deletePackageCmd).buffer);
533
- await sleep(100);
534
- // 查询新数据
535
- if (syncPackageData.id < this.syncTotalNum - 1) {
536
- GizLog.debug('查询新数据:', syncPackageData.id + 1);
537
- await this.bleHandle.write(
538
- curDevice.deviceId,
539
- numberArray2Uint8Array(SyncPackage.pack(syncPackageData.id + 1)).buffer
540
- );
541
- } else {
542
- // 结束同步
543
- GizLog.debug('send cancel sync to device');
544
- this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(CancelSync.pack()).buffer);
545
- this.syncDataCallBack({
546
- event: 'SYNC_END',
547
- });
548
- // 清除相关数据
549
- this.cleanSyncDeviceData();
550
- }
551
- break;
552
- }
553
- case '0058': {
554
- if (!this.syncDataCallBack) break;
555
- // 设备上报停止同步
556
-
557
- const cancelData = new CancelSync(bleBytesData);
558
- GizLog.debug('设备上报停止同步 state:', cancelData.state);
559
-
560
- if (cancelData.state === 0) {
561
- // 同步完成
562
- this.syncDataCallBack({
563
- event: 'SYNC_END',
564
- });
565
- } else {
566
- this.syncDataCallBack({
567
- event: 'SYNC_FAIL',
568
- });
569
- }
570
- // 清除相关数据
571
- this.cleanSyncDeviceData();
572
- break;
573
- }
574
- case '0060': {
575
- // NTP回复
576
- break;
577
- }
578
- }
579
- }
580
- };
581
-
582
- private handleSocketDeviceData: IOnDeviceStatusChanged = async data => {
583
- const target = this.allDevices.find(item => item.did === data.did);
584
- if (!target) {
585
- return;
586
- }
587
- if ((data as IDeviceStatusChangedProps).attrs && (data as IDeviceStatusChangedProps).attrs.is_online != null) {
588
- const isOnline = (data as IDeviceStatusChangedProps).attrs.is_online;
589
- this.setDeviceMeta(target, 'isOnline', isOnline);
590
- }
591
-
592
- if (this.listenerMap['GizDeviceAttrsNotifications']) {
593
- // 需要把枚举 拓展格式化回来
594
- if ((data as IDeviceStatusChangedProps).attrs) {
595
- (data as IDeviceStatusChangedProps).attrs = await formatEnum(
596
- (data as IDeviceStatusChangedProps).attrs,
597
- target.productKey,
598
- 'int'
599
- );
600
- }
601
- this.listenerMap['GizDeviceAttrsNotifications'].map(item => {
602
- item({
603
- device: target,
604
- ...('attrs' in data ? { data: data.attrs } : { raw: data.raw }),
605
- });
606
- });
607
- }
608
- };
609
-
610
- private handleSocketStatus: IOnSocketStatusChanged = (dids, enabled) => {
611
- const devices = this.allDevices.filter(item => dids.includes(item.did) && item.connectType === 'WAN');
612
- GizLog.log('handleSocketStatus', dids, enabled);
613
- devices.forEach(item => {
614
- this.setDeviceMeta(item, 'connectType', enabled ? 'WAN' : 'NONE');
615
- });
616
- };
617
-
618
- private notiDeviceList = () => {
619
- // 找到所有挂载的列表通知
620
- this.listenerMap['GizDeviceListNotifications']?.map(notifyFn => {
621
- notifyFn(this.allDevices);
622
- });
623
-
624
- this.listenerMap['onScanListChange']?.map(notifyFn => {
625
- notifyFn(this.bleScanDevice);
626
- });
627
- };
628
-
629
- private initLan = () => {
630
- try {
631
- this.lanHandle.init();
632
- this.lanHandle.addEventListener('GizLanDeviceList', this.handleLanDevices);
633
- this.lanHandle.addEventListener('GizLanDeviceData', this.handleLanDeviceData);
634
- } catch (error) {
635
- GizLog.error('init lan error', error);
636
- }
637
- };
638
-
639
- /**
640
- * @description 开启后台自动扫描
641
- */
642
- public startAutoScan = (services?: string[]) => {
643
- // 保持autoscan 运行 因为一些蓝牙的操作会导致搜索终止
644
- const autoTime = 9000;
645
-
646
- // 已经启动
647
- if (this.keepScanTimer) {
648
- GizLog.warn('startAutoScan already started');
649
- return;
650
- }
651
- this.keepScanTimer = setInterval(async () => {
652
- // 检查是否在搜索中
653
- // const data = await getBluetoothAdapterState();
654
- // if (!data.discovering) {
655
- // this.bleHandle.startScan((deviceList) => {
656
- // this.bleDevices = deviceList;
657
- // }, -1);
658
- // }
659
- this.bleHandle.startScan(
660
- deviceList => {
661
- this.bleDevices = deviceList;
662
- },
663
- -1,
664
- services
665
- );
666
- }, autoTime);
667
- this.bleHandle.startScan(
668
- deviceList => {
669
- this.bleDevices = deviceList;
670
- },
671
- -1,
672
- services
673
- );
674
- };
675
-
676
- /**
677
- * @description 停止后台自动扫描
678
- */
679
-
680
- public stopAutoScan = () => {
681
- this.keepScanTimer && clearInterval(this.keepScanTimer);
682
- this.keepScanTimer = null;
683
- this.bleHandle.stopScan();
684
- };
685
-
686
- /**
687
- * @description 更改设备列表中的元信息,包括设备mac,设备在线状态等
688
- */
689
- public setDeviceMeta = <K extends keyof IDevice>(
690
- curDev: IDevice,
691
- key: K,
692
- value: IDevice[K],
693
- force: boolean = false
694
- ) => {
695
- const target = this.allDevices.find(dev => dev.mac === curDev.mac);
696
- if (!target || this.allDevices.length === 0) {
697
- return;
698
- }
699
- if (curDev[key] !== value || force) {
700
- target[key] = value;
701
- this.notiDeviceList();
702
- }
703
- };
704
-
705
- getVersion = () => {
706
- return {
707
- success: true,
708
- data: this.version,
709
- };
710
- };
711
-
712
- /**
713
- * 初始化蓝牙能力
714
- * @returns {Promise<{success: boolean, err: string}>}
715
- */
716
- public initBle = async (): Promise<ISDKResult<null>> => {
717
- const permissionData = await this.bleHandle.checkPermission();
718
- if (!permissionData.success) {
719
- GizLog.error('init BLE Error', new Error(JSON.stringify(permissionData)));
720
- return {
721
- success: false,
722
- err: errorCode.GIZ_SDK_BLE_BLUETOOTH_FUNCTION_NOT_TURNED_ON,
723
- };
724
- }
725
-
726
- this.bleHandle.addEventListener('GizBleDeviceData', this.handleBleDeviceData);
727
- this.bleHandle.addEventListener('GizBleDeviceList', this.handleBleDevices);
728
- this.bleHandle.addEventListener('GizBleError', this.handleBleError);
729
- GizLog.debug('init BLE succcess', permissionData);
730
- return { success: true };
731
- };
732
-
733
- /**
734
- * @description 扫描附近的机智云ble设备
735
- * @param delay 超时时间
736
- * @returns {success:boolean,data:IDevice[]}
737
- */
738
- public scanBleDevice = async (delay: number, services?: string[]): Promise<ISDKResult<IDevice[]>> => {
739
- this.bleHandle.scanList = [];
740
- const data = await this.bleHandle.startScan(
741
- deviceList => {
742
- this.bleDevices = deviceList;
743
- },
744
- delay,
745
- services
746
- );
747
- return {
748
- success: true,
749
- data: data.scanList,
750
- };
751
- };
752
-
753
- write = async (device: IDevice, attrs: object) => {
754
- const target = this.allDevices.find(item => isSameDevice(item, device));
755
- if (!target) {
756
- return { success: false, message: 'target is undefind' };
757
- }
758
- if (target.connectType !== 'NONE') {
759
- const { data: value, raw } = await pack(attrs, target.productKey);
760
- switch (target.connectType) {
761
- case 'BLE_BROADCAST':
762
- // 广播的方式发数据 Action+Flags+DataPoints
763
- return await this.bleHandle.writeBoradcast(target.bleDeviceID, raw.cmd);
764
- case 'BLE': {
765
- if (value) {
766
- return await this.bleHandle.write(target.bleDeviceID, numberArray2Uint8Array(value).buffer);
767
- } else {
768
- // 解码失败
769
- return {
770
- success: false,
771
- };
772
- }
773
- }
774
- case 'WAN': {
775
- // 枚举要转换成枚举值
776
- const newAttrs = await formatEnum(attrs, target.productKey, 'string');
777
-
778
- return this.socketHandle.writeData(target, newAttrs);
779
- }
780
- case 'LAN': {
781
- return this.lanHandle.write(target, numberArray2Uint8Array(value).buffer);
782
- }
783
- }
784
- }
785
- return {
786
- success: false,
787
- };
788
- };
789
-
790
- // 发送原始数据
791
- writeRaw = async (device: IDevice, data: number[]) => {
792
- const target = this.allDevices.find(item => isSameDevice(item, device));
793
- if (!target) {
794
- return { success: false, message: 'target is undefind' };
795
- }
796
- if (target.connectType !== 'NONE') {
797
- switch (target.connectType) {
798
- case 'BLE_BROADCAST':
799
- // 广播的方式发数据 Action+Flags+DataPoints
800
- return await this.bleHandle.writeBoradcast(target.bleDeviceID, data);
801
- case 'BLE': {
802
- if (data) {
803
- return await this.bleHandle.write(target.bleDeviceID, numberArray2Uint8Array(data).buffer);
804
- } else {
805
- // 解码失败
806
- return {
807
- success: false,
808
- };
809
- }
810
- }
811
- case 'WAN': {
812
- return this.socketHandle.send(target.did, data);
813
- }
814
- case 'LAN': {
815
- return this.lanHandle.write(target, numberArray2Uint8Array(data).buffer);
816
- }
817
- }
818
- }
819
- return {
820
- success: false,
821
- };
822
- };
823
-
824
- // 设置设备的时间戳
825
- setDeviceTimeStamp = async (device: IDevice) => {
826
- const target = this.allDevices.find(item => isSameDevice(item, device));
827
- if (!target) {
828
- return { success: false, message: 'target is undefind' };
829
- }
830
-
831
- const data = Ntp.pack();
832
-
833
- switch (target.connectType) {
834
- case 'BLE': {
835
- return this.bleHandle.write(device.bleDeviceID, numberArray2Uint8Array(data).buffer);
836
- }
837
- }
838
- return {
839
- success: false,
840
- message: 'the connectType not support set timestamp',
841
- };
842
- };
843
-
844
- // 同步蓝牙设备的离线数据
845
- syncDeviceData = async (device: IDevice, callback: SyncCallBack = () => {}) => {
846
- const target = this.allDevices.find(item => isSameDevice(item, device));
847
- if (!target) {
848
- return { success: false, message: 'target is undefind' };
849
- }
850
- if (!target.isBind) {
851
- return { success: false, message: 'Only the bound devices are supported' };
852
- }
853
-
854
- if (this.syncDevice) {
855
- return {
856
- success: false,
857
- message: 'Synchronizing',
858
- };
859
- }
860
-
861
- this.syncDevice = { ...target };
862
-
863
- switch (target.connectType) {
864
- case 'BLE': {
865
- GizLog.debug('start syncDeviceData', device);
866
- this.syncDataCallBack = callback;
867
- this.syncDataTimoutTimer = setTimeout(() => {
868
- this.syncDataCallBack({
869
- event: 'SYNC_FAIL',
870
- message: 'sync timeout',
871
- });
872
- this.cleanSyncDeviceData();
873
- }, this.SYNC_TIMEOUT);
874
- // 设置超时
875
- const data = RequestSync.pack();
876
- // 发送开始同步的指令
877
- GizLog.debug('sent RequestSync data');
878
- return this.bleHandle.write(device.bleDeviceID, numberArray2Uint8Array(data).buffer);
879
- }
880
- }
881
- return {
882
- success: false,
883
- message: 'the connectType not support sync data',
884
- };
885
- };
886
-
887
- // 查询设备里面还有多少数据需要同步
888
- queryNeedSyncDataLength = async (device: IDevice): Promise<ISDKResult<number>> => {
889
- const target = this.allDevices.find(item => isSameDevice(item, device));
890
- if (!target) {
891
- return { success: false, message: 'target is undefind' };
892
- }
893
- if (!target.isBind) {
894
- return { success: false, message: 'Only the bound devices are supported' };
895
- }
896
- switch (target.connectType) {
897
- case 'BLE': {
898
- const data = RequestSync.pack();
899
- // 发送开始同步的指令
900
- this.syncDevice = { ...target };
901
- GizLog.debug('sent RequestSync data len');
902
- this.bleHandle.write(device.bleDeviceID, numberArray2Uint8Array(data).buffer);
903
- return new Promise(res => {
904
- this.syncDataLengthCallback = res;
905
- setTimeout(() => {
906
- try {
907
- res({ success: false, message: 'timeout' });
908
- } catch (error) {}
909
- }, 3000);
910
- });
911
- }
912
- }
913
- return {
914
- success: false,
915
- message: 'the connectType not support sync data',
916
- };
917
- };
918
-
919
- public cancelSyncDeviceData = async () => {
920
- this.cleanSyncDeviceData();
921
- };
922
-
923
- private cleanSyncDeviceData = () => {
924
- if (this.syncDataCallBack) {
925
- this.syncDataCallBack({
926
- event: 'SYNC_CANCEL',
927
- });
928
- this.syncDataCallBack = null;
929
- }
930
- this.syncCurrnetNum = 0;
931
- this.syncTotalNum = 0;
932
- this.syncDevice = null;
933
- this.syncDataTimoutTimer && clearTimeout(this.syncDataTimoutTimer);
934
- };
935
-
936
- getProductConfig = async (pk: string): Promise<ISDKResult<IDataPointConfig>> => {
937
- const data = await productConfigFileManage.getConfigFile(pk);
938
- if (data) {
939
- return {
940
- success: true,
941
- data,
942
- };
943
- }
944
- return {
945
- success: false,
946
- };
947
- };
948
-
949
- stopScanBleDevice = () => {
950
- this.bleHandle.stopScan();
951
- };
952
-
953
- // 微信匿名登陆
954
- login = async (openID: string): Promise<ISDKResult<ILoginRes>> => {
955
- const data = await AnonymousLogin({ uid: openID });
956
- if (data.success) {
957
- setGlobalData('token', data.data?.token);
958
- setGlobalData('uid', data.data?.uid);
959
- this.socketHandle.updateToken({ token: data.data.token, uid: data.data.uid });
960
- }
961
- return data;
962
- };
963
-
964
- getDeviceStatus = async (device: IDevice, attrNames?: string[]) => {
965
- // 根据PK和mac 找到设备,确认他的连接类型,再用不同的渠道下发
966
- const target = this.allDevices.find(item => isSameDevice(item, device));
967
- if (!target) {
968
- return { success: false, message: 'target is undefind' };
969
- }
970
- switch (target.connectType) {
971
- case 'BLE': {
972
- return await this.bleHandle.getDeviceStatus(
973
- target.bleDeviceID as string,
974
- target.productKey,
975
- target.rootDeviceId,
976
- attrNames
977
- );
978
- }
979
- case 'WAN':
980
- return this.socketHandle.readStatus(target, attrNames);
981
- default: {
982
- return {
983
- success: false,
984
- message: 'Device connectType is unsupported',
985
- };
986
- }
987
- }
988
- };
989
-
990
- /**
991
- * 发起设备订阅
992
- * @param device 待订阅设备
993
- * @param connectType 设备连接类型
994
- * @param _autoGetDeviceStatus 自动获取设备状态
995
- * @returns
996
- */
997
- subscribe = async (device: IDevice, connectType?: TConnectType, _autoGetDeviceStatus: boolean = true) => {
998
- GizLog.debug('subscribe device:', device);
999
- let target = this.allDevices.find(item => isSameDevice(item, device));
1000
- if (!target) {
1001
- GizLog.warn('Device Target Not Found');
1002
- GizLog.warn('current devices ', this.allDevices);
1003
- return { success: false, message: 'device not found' };
1004
- }
1005
-
1006
- // 广播模式不需要连接,所以默认是连接状态
1007
- if (target.connectType === 'BLE_BROADCAST') {
1008
- // 广播不需要连接
1009
- return {
1010
- success: true,
1011
- };
1012
- }
1013
-
1014
- const type: TConnectType = getFirstConnectType(target, connectType);
1015
- if (target.connectType !== 'NONE' && target.connectType !== type) {
1016
- // 已经存在 并且不等于即将订阅的类型
1017
- // 先解除订阅
1018
- await this.unSubscribe(target);
1019
- }
1020
- switch (type) {
1021
- case 'BLE': {
1022
- // 连接BLE
1023
- const data = await this.bleHandle.connectDevice(target.bleDeviceID);
1024
- if (data.success) {
1025
- // 蓝牙设备比较特殊,在get 里面从bleHandle里找到连接的设备,再把connectType 设置成BLE,所以这里更新metaData 要强制更新并推送
1026
- this.setDeviceMeta(target, 'connectType', 'BLE', true);
1027
- setTimeout(() => {
1028
- // 蓝牙设备连接成功之后默认设置一次ntp
1029
- this.setDeviceTimeStamp(target);
1030
- }, 250);
1031
- setTimeout(() => {
1032
- this.getDeviceStatus(target);
1033
- }, 500);
1034
- }
1035
- return data;
1036
- }
1037
- case 'WAN': {
1038
- // 大循环设备
1039
- // const target = this.deviceList.find((item) =>
1040
- // isSameDevice(item, device)
1041
- // );
1042
- const data = this.socketHandle.connectDevice(target);
1043
- if (data.success) {
1044
- this.setDeviceMeta(device, 'connectType', 'WAN', true);
1045
- }
1046
- return data;
1047
- }
1048
- case 'LAN': {
1049
- const data = await this.lanHandle.connectDevice(target);
1050
- if (data.success) {
1051
- this.setDeviceMeta(device, 'connectType', 'LAN', true);
1052
- }
1053
- return data;
1054
- }
1055
- }
1056
- return {
1057
- success: false,
1058
- };
1059
- };
1060
-
1061
- /**
1062
- *
1063
- * @param device 待取消订阅设备
1064
- * @returns 取消订阅结果
1065
- */
1066
- unSubscribe = async (device: IDevice) => {
1067
- const target = this.allDevices.find(item => isSameDevice(item, device));
1068
-
1069
- switch (target.connectType) {
1070
- case 'BLE': {
1071
- const disconnectRes = await this.bleHandle.disConnectDevice(target.bleDeviceID as string);
1072
- if (disconnectRes.success) {
1073
- // 更新ctime
1074
- this.setDeviceMeta(target, 'connectType', 'NONE', true);
1075
- }
1076
- return disconnectRes;
1077
- }
1078
- case 'WAN': {
1079
- const res = this.socketHandle.disConnectDevice(target);
1080
- if (res.success) {
1081
- this.setDeviceMeta(target, 'connectType', 'NONE', true);
1082
- }
1083
- return res;
1084
- }
1085
- case 'LAN': {
1086
- const res = this.lanHandle.disConnectDevice(target);
1087
- if (res.success) {
1088
- this.setDeviceMeta(target, 'connectType', 'NONE', true);
1089
- }
1090
- return res;
1091
- }
1092
- }
1093
- return {
1094
- success: false,
1095
- };
1096
- };
1097
-
1098
- /**
1099
- * 绑定注册到云端的设备
1100
- * 设备必须要注册到云端才能正常绑定
1101
- */
1102
- bindRemoteDevice = async ({
1103
- mac,
1104
- productKey,
1105
- alias,
1106
- beOwner,
1107
- }: IBindRemoteDeviceParams): Promise<ISDKResult<IOpenApiDevice>> => {
1108
- const target = getProductInfoThroughPK(productKey, this.productInfo);
1109
- if (target) {
1110
- const data = await bindMac({
1111
- mac,
1112
- productKey,
1113
- productSecret: target.productSecret,
1114
- alias,
1115
- beOwner,
1116
- });
1117
- // 绑定成功主动获取设备列表
1118
- this.getBindingList();
1119
- return data;
1120
- }
1121
- return {
1122
- success: false,
1123
- err: errorCode.GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIFY,
1124
- };
1125
- };
1126
-
1127
- checkUpdate = async ({ device, type }: { device: IDevice; type: IOTAType }) => {
1128
- const target = this.allDevices.find(item => isSameDevice(item, device));
1129
- if (target) {
1130
- if (!target.did) {
1131
- // 设备没有绑定
1132
- return {
1133
- success: false,
1134
- err: errorCode.GIZ_OPENAPI_DEVICE_NOT_BOUND,
1135
- };
1136
- }
1137
- switch (target.connectType) {
1138
- case 'BLE': {
1139
- return this.bleHandle.checkUpdate({ device, type });
1140
- }
1141
- default: {
1142
- return {
1143
- success: false,
1144
- err: errorCode.GIZ_SDK_OTA_DEVICE_NOT_SUPPORT,
1145
- };
1146
- }
1147
- }
1148
- }
1149
- return {
1150
- success: false,
1151
- err: errorCode.GIZ_SDK_DEVICE_NOT_SUBSCRIBED,
1152
- };
1153
- };
1154
-
1155
- getDeviceInfo = async ({ device }: { device: IDevice }) => {
1156
- const target = this.allDevices.find(item => isSameDevice(item, device));
1157
- if (target) {
1158
- if (!target.did) {
1159
- // 设备没有绑定
1160
- return {
1161
- success: false,
1162
- err: errorCode.GIZ_OPENAPI_DEVICE_NOT_BOUND,
1163
- };
1164
- }
1165
- switch (target.connectType) {
1166
- case 'BLE': {
1167
- return this.bleHandle.getDeviceInfo({ deviceId: device.bleDeviceID });
1168
- }
1169
- default: {
1170
- return {
1171
- success: false,
1172
- err: errorCode.GIZ_SDK_OTA_DEVICE_NOT_SUPPORT,
1173
- };
1174
- }
1175
- }
1176
- }
1177
- return {
1178
- success: false,
1179
- err: errorCode.GIZ_SDK_DEVICE_NOT_SUBSCRIBED,
1180
- };
1181
- };
1182
-
1183
- startUpgrade = async ({
1184
- device,
1185
- type,
1186
- onProgress,
1187
- onEvent,
1188
- }: {
1189
- device: IDevice;
1190
- type: IOTAType;
1191
- onProgress: OTAProgressEventCallback;
1192
- onEvent: OTAEventCallback;
1193
- }) => {
1194
- const target = this.allDevices.find(item => isSameDevice(item, device));
1195
- if (target) {
1196
- if (!target.did) {
1197
- // 设备没有绑定
1198
- return {
1199
- success: false,
1200
- err: errorCode.GIZ_OPENAPI_DEVICE_NOT_BOUND,
1201
- };
1202
- }
1203
- switch (target.connectType) {
1204
- case 'BLE': {
1205
- return this.bleHandle.startUpgrade({ device, type, productKey: device.productKey, onProgress, onEvent });
1206
- }
1207
- default: {
1208
- return {
1209
- success: false,
1210
- err: errorCode.GIZ_SDK_OTA_DEVICE_NOT_SUPPORT,
1211
- };
1212
- }
1213
- }
1214
- }
1215
- return {
1216
- success: false,
1217
- err: errorCode.GIZ_SDK_DEVICE_NOT_SUBSCRIBED,
1218
- };
1219
- };
1220
-
1221
- unbindDevice = async ({ devices }: { devices: IDevice[] }): Promise<ISDKResult<IUnbindReturn>> => {
1222
- const data = await unbindDevice({ devices });
1223
- // 主动刷新列表
1224
- if (data.success) {
1225
- this.getBindingList();
1226
- }
1227
- return data;
1228
- };
1229
-
1230
- deviceSafetyRegister = async ({
1231
- mac,
1232
- productKey,
1233
- }: IDeviceSafetyRegisterParams): Promise<ISDKResult<ISafeRegisterReturn>> => {
1234
- return await this.deviceSafetyApi({ mac, productKey, isReset: false });
1235
- };
1236
- deviceSafetyUnbind = async ({
1237
- mac,
1238
- productKey,
1239
- }: IDeviceSafetyRegisterParams): Promise<ISDKResult<ISafeRegisterReturn>> => {
1240
- return await this.deviceSafetyApi({ mac, productKey, isReset: true });
1241
- };
1242
-
1243
- /**
1244
- * 配网接口
1245
- * setDeviceOnboardingDeploy方法不可重复调用
1246
- */
1247
- setDeviceOnboardingDeploy = async ({
1248
- ssid,
1249
- password,
1250
- mode = 0,
1251
- timeout,
1252
- isBind = true,
1253
- softAPSSIDPrefix,
1254
- productKeys,
1255
- }: ISetDeviceOnboardingDeployProps): Promise<ISDKResult<IDevice[]>> => {
1256
- if (this.currentWifiConfigHandle) {
1257
- return {
1258
- success: false,
1259
- err: errorCode.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING,
1260
- };
1261
- }
1262
- const sTime = new Date().getTime();
1263
- GizLog.debug('GIZ_SDK: 配网开始时间:' + sTime);
1264
- try {
1265
- switch (mode) {
1266
- case 0: {
1267
- this.currentWifiConfigHandle = new ApConfig(
1268
- ssid,
1269
- password,
1270
- this.specialProductKeys,
1271
- this.specialProductKeySecrets
1272
- );
1273
- const data = await this.currentWifiConfigHandle.setDeviceOnboardingDeploy({
1274
- timeout,
1275
- isBind,
1276
- softAPSSIDPrefix,
1277
- });
1278
- this.currentWifiConfigHandle = null;
1279
- const eTime = new Date().getTime();
1280
- GizLog.debug('GIZ_SDK: 配网结束时间:' + eTime);
1281
- GizLog.debug('GIZ_SDK: 配网用时:' + (eTime - sTime));
1282
- return data;
1283
- }
1284
- case 3: {
1285
- this.currentWifiConfigHandle = new BLEConfig(
1286
- ssid,
1287
- password,
1288
- this.specialProductKeys,
1289
- this.specialProductKeySecrets,
1290
- this.bleHandle
1291
- );
1292
- const data = await this.currentWifiConfigHandle.setDeviceOnboardingDeploy({
1293
- timeout,
1294
- isBind,
1295
- softAPSSIDPrefix,
1296
- });
1297
- this.currentWifiConfigHandle = null;
1298
- const eTime = new Date().getTime();
1299
- GizLog.debug('GIZ_SDK: 配网结束时间:' + eTime);
1300
- GizLog.debug('GIZ_SDK: 配网用时:' + (eTime - sTime));
1301
- return data;
1302
- }
1303
- case 10: {
1304
- this.currentWifiConfigHandle = new BLEAliConfig(
1305
- ssid,
1306
- password,
1307
- this.specialProductKeys,
1308
- this.specialProductKeySecrets,
1309
- this.bleHandle
1310
- );
1311
- const data = await this.currentWifiConfigHandle.setDeviceOnboardingDeploy({
1312
- timeout,
1313
- isBind,
1314
- softAPSSIDPrefix,
1315
- productKeys,
1316
- });
1317
- this.currentWifiConfigHandle = null;
1318
- const eTime = new Date().getTime();
1319
- GizLog.debug('GIZ_SDK: 配网结束时间:' + eTime);
1320
- GizLog.debug('GIZ_SDK: 配网用时:' + (eTime - sTime));
1321
- return data;
1322
- }
1323
- }
1324
- } catch (error) {
1325
- GizLog.error('GIZ_SDK: setDeviceOnboardingDeploy', new Error(JSON.stringify(error)));
1326
- if ((error as ISDKResult<IDevice[]>).err && (error as ISDKResult<IDevice[]>).err!.errorCode) {
1327
- return error as ISDKResult<IDevice[]>;
1328
- }
1329
- return {
1330
- success: false,
1331
- err: errorCode.GIZ_SDK_OTHERWISE,
1332
- };
1333
- } finally {
1334
- this.currentWifiConfigHandle = null;
1335
- }
1336
- };
1337
-
1338
- /**
1339
- * 设置域名
1340
- */
1341
- private setDomain = (cloudServiceInfo: ICloudServiceInfo) => {
1342
- const openAPIInfo = (cloudServiceInfo && cloudServiceInfo.openAPIInfo) || 'api.gizwits.com';
1343
- const aepInfo = (cloudServiceInfo && cloudServiceInfo.aepInfo) || 'https://gj-app.iotsdk.com/';
1344
-
1345
- const newData = { ...(cloudServiceInfo || {}), openAPIInfo, aepInfo };
1346
- setGlobalData('cloudServiceInfo', newData);
1347
- };
1348
-
1349
- private deviceSafetyApi = async ({
1350
- mac,
1351
- productKey,
1352
- isReset,
1353
- }: IDeviceSafetyParams): Promise<ISDKResult<ISafeRegisterReturn>> => {
1354
- const target = getProductInfoThroughPK(productKey, this.productInfo);
1355
- if (target) {
1356
- return await safeRegister({
1357
- productKey,
1358
- productSecret: target.productSecret,
1359
- mac,
1360
- isReset,
1361
- passcode: '1234567890',
1362
- });
1363
- }
1364
- return {
1365
- success: false,
1366
- err: errorCode.GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIFY,
1367
- };
1368
- };
1369
-
1370
- // 内部刷新设备列表的方法
1371
- public getBindingList = async () => {
1372
- const data = await getBindingList();
1373
- this.deviceList = data.data || [];
1374
- return data;
1375
- };
1376
-
1377
- /**
1378
- * 刷新云端设备列表
1379
- * 并合并数据
1380
- */
1381
- public getDevices = async (): Promise<ISDKResult<IDevice[]>> => {
1382
- // merage
1383
- await this.getBindingList();
1384
- // 简单粗暴的先合并
1385
- return {
1386
- success: true,
1387
- data: this.allDevices,
1388
- };
1389
- };
1390
-
1391
- /**
1392
- * 停止配网
1393
- */
1394
- stopDeviceOnboardingDeploy = (): void => {
1395
- if (this.currentWifiConfigHandle) {
1396
- this.currentWifiConfigHandle.stopDeviceOnboardingDeploy();
1397
- this.currentWifiConfigHandle = null;
1398
- }
1399
- };
1400
-
1401
- /**
1402
- * setLogLevel
1403
- */
1404
- setLogLevel = (level: TLogType) => {
1405
- return GizLog.setLogLevel(level);
1406
- };
1407
-
1408
- public renameDevice = async (device: IDevice, name: string) => {
1409
- if (!name) {
1410
- return {
1411
- success: false,
1412
- message: 'please input device name',
1413
- };
1414
- }
1415
- if (device.isBind) {
1416
- return await editBindInfo({
1417
- did: device.did,
1418
- name: name,
1419
- });
1420
- }
1421
- return {
1422
- success: false,
1423
- message: 'device not bind',
1424
- };
1425
- };
1426
-
1427
- /**
1428
- * 移除事件监听
1429
- * @param type 事件监听名称,详见下表
1430
- * @param func 事件监听回调
1431
- * @returns
1432
- */
1433
- public removeEventListener = <K extends keyof TListenerType>(type: K, func: TListenerType[K]) => {
1434
- if (this.listenerMap[type]) {
1435
- const index = this.listenerMap[type].indexOf(func);
1436
- if (index !== -1) {
1437
- // 删除数组中的这一行
1438
- this.listenerMap[type].splice(index, 1);
1439
- return {
1440
- success: true,
1441
- };
1442
- }
1443
- }
1444
- return {
1445
- success: false,
1446
- // err: errorCode.GIZ_SDK_BLE_BLUETOOTH_FUNCTION_NOT_TURNED_ON
1447
- };
1448
- };
1449
-
1450
- public addEventListener = async <K extends keyof TListenerType>(type: K, func: TListenerType[K]) => {
1451
- if (!this.listenerMap[type]) {
1452
- // 创建一个新的
1453
- this.listenerMap[type] = [];
1454
- }
1455
-
1456
- if (this.listenerMap[type].indexOf(func) === -1) {
1457
- this.listenerMap[type].push(func);
1458
- }
1459
- return {
1460
- success: true,
1461
- };
1462
- };
1463
-
1464
- public destory = () => {
1465
- this.bleHandle.destory();
1466
- this.lanHandle.destory();
1467
- this.socketHandle.destory();
1468
- this.keepScanTimer && clearInterval(this.keepScanTimer);
1469
- this.keepScanTimer = null;
1470
- };
1471
- }
1472
- export default GizwitsMiniSDK;