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
@@ -1,625 +0,0 @@
1
- import errorCode from "../errorCode";
2
- import GizLog from "../GizLog";
3
- import request from "../openApiRequest";
4
- import { compareWXSDKVersion, isError } from '../utils';
5
-
6
- // commType = 'custom' | 'attrs_v4'
7
- // socketType = 'socket' | 'ssl_socket'
8
-
9
-
10
- interface IRespError {
11
- err?: IError;
12
- }
13
-
14
- interface IWriteRes {
15
- success: boolean;
16
- message: string;
17
- }
18
-
19
- interface ICommonProps {
20
- appID: string;
21
- token: string;
22
- uid: string;
23
- }
24
-
25
- interface IGWSProps extends ICommonProps {
26
- limitSocketNum?: boolean;
27
- }
28
-
29
- export default class GizwitsWS {
30
-
31
- appID: string;
32
- token: string;
33
- uid: string;
34
- _maxSocketNum: number;
35
- _bindingDevices: { [did: string]: IDevice } | null = null;
36
- _connections: { [wsInfo: string]: Connection } = {};
37
- _onDeviceStatusChanged?: IOnDeviceStatusChanged;
38
- _onSocketStatusChanged?: IOnSocketStatusChanged;
39
- _onBindingChanged?: IEmptyFn;
40
-
41
- /**
42
- * @param limitSocketNum 是否限制 socket 连接数,如果限制则按照小程序sdk限制最大连接数,否则如果超过小程序限制连接数,微信可能会关闭之前的连接,也可以会有异常。
43
- */
44
- constructor({
45
- appID,
46
- token,
47
- uid,
48
- limitSocketNum = true,
49
- }: IGWSProps) {
50
- this.appID = appID;
51
- this.token = token;
52
- this.uid = uid;
53
- const wxSDKVersion = wx.getSystemInfoSync().SDKVersion
54
- this._maxSocketNum = limitSocketNum
55
- ? compareWXSDKVersion(wxSDKVersion || '1.0.0', '1.7.0') === -1 ? 1 : 5
56
- : 0;
57
- }
58
-
59
- async init() {
60
- try {
61
- const result = await this._getBindingList();
62
- if ((result as IRespError).err?.errorCode) {
63
- return { errorCode: (result as IRespError).err?.errorCode, errorMessage: 'getting binding list failed' };
64
- } else {
65
- this._bindingDevices = (result as IDevice[]).reduce((map, device) => ({ ...map, [device.did]: device }), {});
66
- return null;
67
- }
68
- } catch (error) {
69
- return errorCode.GIZ_SDK_OTHERWISE
70
- }
71
- }
72
-
73
- updateToken = ({token, uid}) => {
74
- this.token = token;
75
- this.uid = uid;
76
- }
77
-
78
- _getDevice = (did: string): IDevice | IError => {
79
- if (this._bindingDevices === null) {
80
- return errorCode.GIZ_SDK_SDK_NOT_INITIALIZED
81
- }
82
-
83
- const device = this._bindingDevices[did];
84
- if (device == null) {
85
- return errorCode.GIZ_OPENAPI_DEVICE_NOT_BOUND;
86
- }
87
- return device;
88
- }
89
-
90
- _getConnect = (device: IDevice): Connection => {
91
- const wsInfo = this._getWebsocketConnInfo(device);
92
- return this._connections[wsInfo];
93
- }
94
-
95
- _getDeviceAndConnect = (did: string): [IDevice, Connection] | IError => {
96
- const device = this._getDevice(did)
97
- if (isError(device)) {
98
- return device;
99
- }
100
- const conn = this._getConnect(device);
101
- if (conn == null) {
102
- return errorCode.GIZ_SDK_DEVICE_NOT_SUBSCRIBED;
103
- }
104
- return [device, conn]
105
- }
106
-
107
- connectDevice = (device: IDevice) => {
108
- const wsInfo = this._getWebsocketConnInfo(device);
109
- let conn = this._connections[wsInfo];
110
- if (conn == null) {
111
- const connNum = Object.keys(this._connections).length;
112
- if (this._maxSocketNum !== 0 && connNum >= this._maxSocketNum) {
113
- return { success: false, errorCode: errorCode.MAX_CONNECT };
114
- }
115
- conn = new Connection({
116
- appID: this.appID,
117
- token: this.token,
118
- uid: this.uid,
119
- wsInfo,
120
- onDeviceStatusChanged: this._handleDeviceStatusChanged,
121
- onBindingChanged: this._handleBindingChanged,
122
- onSocketStatusChanged: this._handleSocketStatusChanged,
123
- });
124
- this._connections[wsInfo] = conn;
125
- }
126
- conn._addSubDid(device.did);
127
- if (conn._websocket == null) {
128
- conn._connectWS();
129
- } else if (conn.ready) {
130
- conn._subDevices([device.did]);
131
- }
132
- return { success: true };
133
- }
134
-
135
- disConnectDevice = (device: IDevice) => {
136
- const wsInfo = this._getWebsocketConnInfo(device);
137
- let conn = this._connections[wsInfo];
138
- if (conn) {
139
- conn._unSubDevices([device.did])
140
- }
141
- return {success: true}
142
- }
143
-
144
- connect = (did: string) => {
145
- const device = this._getDevice(did)
146
- if (isError(device)) {
147
- return device;
148
- }
149
- const res = this.connectDevice(device);
150
- return res.success ? null : res.errorCode;
151
- }
152
-
153
- send = (did: string, raw: number[]) => {
154
- const res = this._getDeviceAndConnect(did);
155
- if (isError(res)) {
156
- return res;
157
- }
158
- return res[1]._send({
159
- cmd: "c2s_raw",
160
- data: {
161
- did: did,
162
- raw
163
- }
164
- });
165
- }
166
-
167
- writeData = (device: IDevice, attrs: ICommonObj) => {
168
- const conn = this._getConnect(device);
169
- const success = conn != null;
170
- if (success) {
171
- return conn._send({
172
- cmd: "c2s_write",
173
- data: {
174
- did: device.did,
175
- attrs
176
- }
177
- });
178
- }
179
- return { success: false };
180
- }
181
-
182
- write = (did: string, attrs: ICommonObj) => {
183
- const res = this._getDeviceAndConnect(did);
184
- if (isError(res)) {
185
- return res;
186
- }
187
- return res[1]._send({
188
- cmd: "c2s_write",
189
- data: {
190
- did: did,
191
- attrs: attrs
192
- }
193
- });
194
- }
195
-
196
- readStatus = (device: IDevice, names?: string[]) => {
197
- const conn = this._getConnect(device);
198
- const success = conn != null;
199
- if (success) {
200
- conn._send({
201
- cmd: "c2s_read",
202
- data: {
203
- did: device.did,
204
- names,
205
- }
206
- });
207
- }
208
- return { success };
209
- }
210
-
211
- read = (did: string, names?: string[]) => {
212
- const res = this._getDeviceAndConnect(did);
213
- if (isError(res)) {
214
- return res;
215
- }
216
- return res[1]._send({
217
- cmd: "c2s_read",
218
- data: {
219
- did: did,
220
- names: names
221
- }
222
- });
223
- }
224
-
225
- destory = () => {
226
- Object.values(this._connections).forEach(conn => conn.destory());
227
- }
228
-
229
- subscribeDeviceStatus = (cb: IOnDeviceStatusChanged) => {
230
- this._onDeviceStatusChanged = cb;
231
- }
232
-
233
- subscribeBindingChanged = (cb: IEmptyFn) => {
234
- this._onBindingChanged = cb;
235
- }
236
-
237
- subscribeSocketStatus = (cb: IOnSocketStatusChanged) => {
238
- this._onSocketStatusChanged = cb;
239
- }
240
-
241
- _handleDeviceStatusChanged: IOnDeviceStatusChanged = (data) => {
242
- // const device = this._getDevice(data.did);
243
- // if (!isError(device)) {
244
- // this._onDeviceStatusChanged && this._onDeviceStatusChanged(data);
245
- // }
246
- this._onDeviceStatusChanged && this._onDeviceStatusChanged(data);
247
- }
248
-
249
- _handleBindingChanged = () => {
250
- this._onBindingChanged && this._onBindingChanged();
251
- }
252
-
253
- _handleSocketStatusChanged: IOnSocketStatusChanged = (...params) => {
254
- this._onSocketStatusChanged && this._onSocketStatusChanged(...params);
255
- }
256
-
257
- _getBindingList = async (limit: number = 20, skip: number = 0, cacheList: IDevice[] = []): Promise<IDevice[] | IRespError> => {
258
- const url = `/app/bindings?show_disabled=0&limit=${limit}&skip=${skip}`;
259
- const { err, data } = await request<{ devices: IDevice[] }>(`${url}`, { method: 'GET' });
260
- if (err) {
261
- return { err };
262
- }
263
- const devices = [...cacheList, ...data?.devices || []]
264
- if (data && data.devices.length === limit) {
265
- return await this._getBindingList(limit, limit + skip, devices);
266
- }
267
- return devices;
268
- }
269
-
270
- _getWebsocketConnInfo = (device) => {
271
- if (device.host) {
272
- return `wss://wx${device.host}`
273
- }
274
- return 'wss://wxstage.gizwits.com';
275
- }
276
-
277
-
278
- }
279
-
280
- interface IConnectProps extends ICommonProps {
281
- wsInfo: string;
282
- onDeviceStatusChanged?: IOnDeviceStatusChanged;
283
- onBindingChanged?: IEmptyFn;
284
- onSocketStatusChanged?: IOnSocketStatusChanged;
285
- }
286
-
287
- export class Connection {
288
- ready: boolean = false;
289
- appID: string;
290
- token: string;
291
- uid: string;
292
- commType: string = 'attrs_v4';
293
- _heartbeatInterval = 60;
294
- _keepaliveTime = 180;
295
- _loginIntveral = 5000;
296
- autoSubscribe = false;
297
- _wsUrl: string;
298
- _websocket: WechatMiniprogram.SocketTask | null = null;
299
- _heartbeatTimerId?: any;
300
- _loginFailedTimes: number = 0;
301
- _subDids: Set<string> = new Set();
302
- _socketRespHandleMap: { [cmd: string]: (resp?: any) => void } = {};
303
- _onDeviceStatusChanged?: IOnDeviceStatusChanged;
304
- _onBindingChanged?: IEmptyFn;
305
- _onSocketStatusChanged?: IOnSocketStatusChanged;
306
- _waitSends: object[] = [];
307
- _checkConnectTimerId?: any;
308
-
309
- constructor({
310
- appID,
311
- token,
312
- uid,
313
- wsInfo,
314
- onDeviceStatusChanged,
315
- onBindingChanged,
316
- onSocketStatusChanged,
317
- }: IConnectProps) {
318
- this.appID = appID;
319
- this.token = token;
320
- this.uid = uid;
321
- this._wsUrl = `${wsInfo}/ws/app/v1`;
322
- this._heartbeatTimerId = undefined;
323
- this._loginFailedTimes = 0;
324
- this._onDeviceStatusChanged = onDeviceStatusChanged;
325
- this._onBindingChanged = onBindingChanged;
326
- this._onSocketStatusChanged = onSocketStatusChanged;
327
- this._socketRespHandleMap = {
328
- pong: this.pongResp,
329
- login_res: this._loginResp,
330
- subscribe_res: this._subscribeResp,
331
- s2c_online_status: this._onlineResp,
332
- s2c_raw: this._rawChangedResp,
333
- s2c_noti: this._statusChangedResp,
334
- s2c_invalid_msg: this._invalidMsgResp,
335
- s2c_binding_changed: this._bindingChangedResp,
336
- }
337
- wx.onNetworkStatusChange(this._networkChange);
338
- wx.onAppShow(this._appShow)
339
- }
340
-
341
- destory = () => {
342
- if (this._heartbeatTimerId) {
343
- clearInterval(this._heartbeatTimerId)
344
- }
345
- if (this._checkConnectTimerId) {
346
- clearInterval(this._checkConnectTimerId)
347
- }
348
- this.close();
349
- }
350
-
351
- _networkChange = async (res: WechatMiniprogram.OnNetworkStatusChangeCallbackResult) => {
352
- GizLog.log('network change', res);
353
- // if (res.isConnected && !this._websocket) {
354
- // // 网络断开重连
355
- // await sleep(100);
356
- // this._connectWS();
357
- // }
358
- }
359
-
360
- _appShow = async () => {
361
- GizLog.log('app show');
362
- // if (!this._websocket) {
363
- // // 从后台切回如果断开连接重新连
364
- // this._connectWS();
365
- // }
366
- }
367
-
368
- _addSubDid = (did) => {
369
- this._subDids.add(did);
370
- }
371
-
372
- _removeSubDid = (did) => {
373
- this._subDids.delete(did);
374
- }
375
-
376
- _connectWS = () => {
377
- GizLog.log('GIZ_SDK: start connect ws')
378
- this._websocket = wx.connectSocket({
379
- url: this._wsUrl,
380
- fail: (res) => {
381
- GizLog.error('GIZ_SDK: connectSocket error', new Error(JSON.stringify(res)));
382
- }
383
- });
384
- this._websocket.onClose(this.handleClose);
385
- this._websocket.onOpen(this.handleOpen);
386
- this._websocket.onError(this.handleError);
387
- this._websocket.onMessage(this.handleMessage);
388
-
389
- // 维持连接
390
- if (!this._checkConnectTimerId) {
391
- this._checkConnectTimerId = setInterval(() => {
392
- if (!this._websocket) {
393
- this._connectWS();
394
- }
395
- }, 1000);
396
- }
397
-
398
- }
399
-
400
- _subDevices = (dids: string[]) => {
401
- const json = {
402
- cmd: "subscribe_req",
403
- data: dids.map(did => ({ did }))
404
- };
405
- this._send(json);
406
- }
407
-
408
- _unSubDevices = (dids: string[]) => {
409
- dids.map(item => this._removeSubDid(item))
410
- }
411
-
412
- _send = (data: object, forced: boolean = false) => {
413
- GizLog.log('GIZ_SDK: Socket send', data, forced);
414
- return new Promise<IWriteRes>((resolve) => {
415
- if (!this._websocket) {
416
- resolve({
417
- success: false,
418
- message: 'Socket not init'
419
- })
420
- return;
421
- }
422
- if (!forced && !this.ready) {
423
- resolve({
424
- success: false,
425
- message: 'Socket not ready'
426
- })
427
- return;
428
- // this._waitSends.push(data);
429
- // resolve({
430
- // success: true,
431
- // message: '',
432
- // })
433
- // GizLog.debug('GIZ_SDK: cache data wait socket ready');
434
- return;
435
- }
436
- if (this._websocket && (forced || this.ready)) {
437
- this._websocket.send({
438
- data: JSON.stringify(data),
439
- complete: (res) => {
440
- GizLog.log('GIZ_SDK: socket send res', res);
441
- // if ([
442
- // 'sendSocketMessage:fail debug invoke no active session',
443
- // 'sendSocketMessage:fail wcwss taskID not exist'
444
- // ].includes(res && res.errMsg)) {
445
- // // 重新connect
446
- // this._websocket && this._websocket.close({});
447
- // this._connectWS();
448
- // }
449
- GizLog.log('resres', res)
450
- let success = false;
451
- if (res.errMsg === "sendSocketMessage:ok") {
452
- success = true
453
- }
454
- resolve({
455
- success,
456
- message: res.errMsg
457
- })
458
-
459
- },
460
- fail: (e) => {
461
- GizLog.error('GIZ_SDK: Socket send error', new Error(JSON.stringify(e)));
462
- resolve({
463
- success: false,
464
- message: e.errMsg
465
- })
466
- }
467
- })
468
- }
469
- })
470
- }
471
-
472
- close = () => {
473
- this.ready = false;
474
- if (this._heartbeatTimerId) {
475
- clearInterval(this._heartbeatTimerId);
476
- }
477
- if (this._websocket) {
478
- this._websocket.close({});
479
- this._websocket = null;
480
- }
481
- this._handleSocketStatusChanged(false);
482
- }
483
-
484
- handleClose = (res: { code: number, reason: string }) => {
485
- GizLog.error('GIZ_SDK: socket close', new Error(JSON.stringify(res)));
486
- this.close();
487
- this._stopPing();
488
- }
489
-
490
- handleOpen = () => {
491
- // socket 打开后执行登录
492
- GizLog.log(' socket open')
493
- this._login();
494
- }
495
-
496
- handleMessage = ({ data }: { data: string | ArrayBuffer }) => {
497
- GizLog.log('GIZ_SDK: message', data);
498
- const res = JSON.parse(data as string);
499
- const handle = this._socketRespHandleMap[res.cmd];
500
- handle && handle(res.data);
501
- }
502
-
503
- handleError = (err: { errMsg: string }) => {
504
- GizLog.error('GIZ_SDK: socket error', new Error(JSON.stringify(err)));
505
- this.close();
506
- this._stopPing();
507
- }
508
-
509
- _login = () => {
510
- const data = {
511
- cmd: 'login_req',
512
- data: {
513
- appid: this.appID,
514
- uid: this.uid,
515
- token: this.token,
516
- p0_type: this.commType,
517
- heartbeat_interval: this._keepaliveTime,
518
- auto_subscribe: this.autoSubscribe
519
- }
520
- }
521
- this._send(data, true);
522
- }
523
-
524
- _tryLoginAgain = () => {
525
- this._loginFailedTimes += 1;
526
- setTimeout(() => {
527
- this._login();
528
- }, this._loginFailedTimes * this._loginIntveral);
529
- }
530
-
531
- _startPing = () => {
532
- this._heartbeatTimerId = setInterval(() => {
533
- this._send({ cmd: 'ping' });
534
-
535
- }, this._heartbeatInterval * 1000);
536
- }
537
-
538
- _stopPing = () => {
539
- this._heartbeatTimerId && clearInterval(this._heartbeatTimerId);
540
- }
541
-
542
- pongResp = () => {
543
- // 不处理
544
- }
545
-
546
- _loginResp = (data) => {
547
- if (data.success == true) {
548
- this._loginFailedTimes = 0;
549
- this.ready = true;
550
- this._startPing();
551
- this._subDevices([...this._subDids]);
552
- this._handleSocketStatusChanged(true);
553
- this._consumeWaitSends();
554
- } else if (this._loginFailedTimes < 3) {
555
- GizLog.log('GIZ_SDK: Login failed, will try again, please wait...');
556
- this._tryLoginAgain();
557
- } else {
558
- GizLog.error('GIZ_SDK: Login failed', new Error('m2m socket login failed'));
559
- this.close();
560
- }
561
- }
562
-
563
- _consumeWaitSends = () => {
564
- let data = this._waitSends.pop()
565
- while (data) {
566
- this._send(data);
567
- data = this._waitSends.pop()
568
- }
569
- }
570
-
571
- _handleSocketStatusChanged = (enabled: boolean) => {
572
- this._onSocketStatusChanged && this._onSocketStatusChanged([...this._subDids], enabled);
573
- }
574
-
575
- _subscribeResp = (data) => {
576
- GizLog.log('GIZ_SDK: subscribe_res', data);
577
- if (data && data.success) {
578
- // 订阅成功设备获取设备状态
579
- data.success.forEach(d => this._send({
580
- cmd: "c2s_read",
581
- data: {
582
- did: d.did,
583
- }
584
- }))
585
- }
586
- GizLog.debug('GIZ_SDK: subscribe_res', data);
587
- }
588
-
589
- _onlineResp = (data: { did: string, online: boolean }) => {
590
- if (!this._isSub(data.did)) return;
591
- this._onDeviceStatusChanged && this._onDeviceStatusChanged({
592
- did: data.did, attrs: { is_online: data.online, ...data }
593
- });
594
- }
595
-
596
- _rawChangedResp = (data: IDeviceRawStatusChangedProps) => {
597
- if (!this._isSub(data.did)) return;
598
- this._onDeviceStatusChanged && this._onDeviceStatusChanged(data);
599
- }
600
-
601
- _statusChangedResp = (data: IDeviceStatusChangedProps) => {
602
- if (!this._isSub(data.did)) return;
603
- this._onDeviceStatusChanged && this._onDeviceStatusChanged(data);
604
- }
605
-
606
- // 检查设备是否订阅
607
- _isSub = (did: string) => {
608
- return this._subDids.has(did);
609
- }
610
-
611
- _invalidMsgResp = (data) => {
612
- if (data.error_code === 1003) {
613
- // 重新登录
614
- this._login();
615
- }
616
- GizLog.error('GIZ_SDK: s2c_invalid_msg', new Error(JSON.stringify(data)));
617
- }
618
-
619
- _bindingChangedResp = (data) => {
620
- if (!data.bind && data.did) {
621
- this._removeSubDid(data.did)
622
- }
623
- this._onBindingChanged && this._onBindingChanged();
624
- }
625
- }
@@ -1,62 +0,0 @@
1
- import request from './request';
2
- import { getGlobalData } from "./globalData";
3
- import errorCode from './errorCode';
4
-
5
- interface IResult<T> {
6
- data: T;
7
- errMsg: string;
8
- statusCode: number;
9
- }
10
-
11
- export interface IServiceResult<T> {
12
- success: boolean;
13
- data?: T;
14
- err?: IError;
15
- }
16
-
17
-
18
- const openApiRequest = async <T>(url: string, options: any, needToken: boolean = true): Promise<IServiceResult<T>> => {
19
- const requestOptions = { ...options };
20
- const headers: any = {
21
- 'Content-Type': 'application/json',
22
- 'X-Gizwits-Application-Id': getGlobalData('appID'),
23
- };
24
-
25
- if (needToken) {
26
- headers['X-Gizwits-User-token'] = getGlobalData('token');
27
- }
28
-
29
- requestOptions.header = { ...headers, ...options.headers };
30
- delete requestOptions.headers;
31
- const openApiUrl = getGlobalData('cloudServiceInfo').openAPIInfo;
32
- const res = await request<IResult<T>>('https://' + openApiUrl + url, requestOptions);
33
- // 统一封装OPEN API的错误码
34
- if (res.statusCode >= 200 && res.statusCode < 300) {
35
- return {
36
- success: true,
37
- data: res.data
38
- }
39
- }
40
-
41
- let baseError = {
42
- success: false,
43
- err: {
44
- errorCode: errorCode.GIZ_SDK_HTTP_REQUEST_FAILED.errorCode,
45
- errorMessage: '',
46
- }
47
- }
48
- try {
49
- baseError = {
50
- success: false,
51
- err: {
52
- errorCode: (res.data as any).error_code,
53
- errorMessage: (res.data as any).error_message,
54
- }
55
- }
56
- } catch (error) {
57
-
58
- }
59
- return baseError;
60
- }
61
-
62
- export default openApiRequest;