mini_program_gizwits_sdk 3.6.4 → 3.6.5

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