mini_program_gizwits_sdk 3.2.30 → 3.3.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.
package/src/sdk.ts CHANGED
@@ -1,17 +1,12 @@
1
- import { getGlobalData, setGlobalData } from './globalData';
1
+ import { setGlobalData, getGlobalData } from './globalData';
2
2
  import { BleHandle } from './handler/ble';
3
3
  import GizwitsWS from './handler/socket';
4
4
 
5
- import { errorCode } from '..';
6
- import sdkConfig from '../package.json';
5
+ import ApConfig from './wifiConfig/ap';
6
+ import BLEConfig from './wifiConfig/ble';
7
7
  import GizLog, { TLogType } from './GizLog';
8
- import { LanHandle } from './handler/lan';
9
- import productConfigFileManage from './productConfigFileManage';
10
- import { formatEnum, IDataPointConfig, pack, unpack } from './protocol/DataPoint';
11
- import Ntp from './protocol/Ntp';
12
- import { CancelSync, DeletePackage, RequestSync, SyncPackage } from './protocol/OffLineData';
13
- import ProtocolBase from './protocol/ProtocolBase';
14
- import { arrayToString, hexStrint2byte } from './protocol/tool';
8
+ import { errorCode } from '..';
9
+ import { AnonymousLogin, ILoginRes } from './services/login';
15
10
  import {
16
11
  bindMac,
17
12
  editBindInfo,
@@ -20,21 +15,28 @@ import {
20
15
  ISafeRegisterReturn,
21
16
  IUnbindReturn,
22
17
  safeRegister,
23
- unbindDevice
18
+ unbindDevice,
24
19
  } from './services/devices';
25
- import { AnonymousLogin, ILoginRes } from './services/login';
26
- import { uploadP0 } from './services/uploadP0';
27
- import sleep from './sleep';
28
20
  import {
29
21
  getFirstConnectType,
30
22
  getProductInfoThroughPK,
31
23
  isSameDevice,
32
24
  merageBleLocalDevices,
33
25
  merageLanLocalDevices,
34
- numberArray2Uint8Array
26
+ numberArray2Uint8Array,
35
27
  } from './utils';
36
- import ApConfig from './wifiConfig/ap';
37
- import BLEConfig from './wifiConfig/ble';
28
+ import productConfigFileManage from './productConfigFileManage';
29
+ import { formatEnum, IDataPointConfig, pack, unpack } from './protocol/DataPoint';
30
+ import { arrayToString, hexStrint2byte } from './protocol/tool';
31
+ import { LanHandle } from './handler/lan';
32
+ import ProtocolBase from './protocol/ProtocolBase';
33
+ import { CancelSync, DeletePackage, RequestSync, SyncPackage } from './protocol/OffLineData';
34
+ import { uploadP0 } from './services/uploadP0';
35
+ import sleep from './sleep';
36
+ import Ntp from './protocol/Ntp';
37
+ import sdkConfig from '../package.json';
38
+ import Reset from './protocol/Reset';
39
+ import SetReset from './protocol/SetReset';
38
40
 
39
41
  const version = sdkConfig.version;
40
42
  interface SyncCallBackParams {
@@ -252,7 +254,7 @@ class GizwitsMiniSDK {
252
254
 
253
255
  private _bleHandle: BleHandle;
254
256
  private _lanHandle: LanHandle;
255
-
257
+
256
258
  // private autoScanInterval: IntervalHandle = null;
257
259
 
258
260
  private _gizSocket: GizwitsWS;
@@ -348,7 +350,7 @@ class GizwitsMiniSDK {
348
350
 
349
351
  const { appID, token, cloudServiceInfo = {openAPIInfo: ''} } = props;
350
352
  const openAPIInfo = (cloudServiceInfo && cloudServiceInfo.openAPIInfo) || 'api.gizwits.com';
351
- if (appID !== getGlobalData('appID') ||
353
+ if (appID !== getGlobalData('appID') ||
352
354
  token !== getGlobalData('token') ||
353
355
  openAPIInfo !== getGlobalData('cloudServiceInfo').openAPIInfo
354
356
  ) {
@@ -405,7 +407,7 @@ class GizwitsMiniSDK {
405
407
  }
406
408
  }
407
409
  private handleBleDeviceData = async (
408
- curDevice: WechatMiniprogram.OnBLECharacteristicValueChangeListenerResult,
410
+ curDevice: WechatMiniprogram.OnBLECharacteristicValueChangeCallbackResult,
409
411
  hexString: string
410
412
  ) => {
411
413
  const target = this.allDevices.find(
@@ -426,7 +428,7 @@ class GizwitsMiniSDK {
426
428
  if (productConfig) {
427
429
  const uploadTime = parseInt(`${Date.now() / 1000}`, 10)
428
430
  uploadP0({
429
- device: target,
431
+ device: target,
430
432
  data: [
431
433
  {
432
434
  raw: hexString,
@@ -438,7 +440,7 @@ class GizwitsMiniSDK {
438
440
  GizLog.debug("设备上报数据:timestemp", new Date(uploadTime * 1000).toLocaleString(), data)
439
441
  })
440
442
  }
441
-
443
+
442
444
  }
443
445
  const data = await unpack(hexStrint2byte(hexString), target.productKey);
444
446
  // 如果有kydata 则上报
@@ -452,6 +454,32 @@ class GizwitsMiniSDK {
452
454
  }
453
455
  break
454
456
  }
457
+ case '0062': {
458
+ // 蓝牙重置命令,app代理设备进行重置
459
+ const resetInfo = new Reset(bleBytesData)
460
+ GizLog.debug("收到代理重置事件", resetInfo)
461
+
462
+ if (resetInfo.status === 1) {
463
+ // 需要重置
464
+ this.deviceSafetyApi({
465
+ mac: target.mac,
466
+ productKey: target.productKey,
467
+ isReset: true
468
+ }).then(async data => {
469
+ GizLog.debug("代理重置结果", data)
470
+ if (data.success && data.data.successDevices.length > 0) {
471
+ // 回写数据
472
+ GizLog.debug("重置成功,回写数据")
473
+ await this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(SetReset.pack(0)).buffer)
474
+ }
475
+ })
476
+ }
477
+ break;
478
+ }
479
+ case '0064': {
480
+ // 回写重置结果ack,暂时先忽略
481
+ break;
482
+ }
455
483
  case '0052': {
456
484
  // 设备回复是否允许同步数据
457
485
  const requestSyncData = new RequestSync(bleBytesData)
@@ -493,7 +521,7 @@ class GizwitsMiniSDK {
493
521
  try {
494
522
  GizLog.debug("设备上报离线数据:timestemp", new Date(syncPackageData.timestemp * 1000).toLocaleString())
495
523
  } catch (error) {
496
-
524
+
497
525
  }
498
526
 
499
527
  const productConfig = this.productInfo.find(item => item.productKey === this.syncDevice.productKey)
@@ -510,7 +538,7 @@ class GizwitsMiniSDK {
510
538
  })
511
539
  GizLog.debug("上传离线数据结果", uploadRes)
512
540
  }
513
-
541
+
514
542
  this.syncCurrnetNum += 1;
515
543
  // 通知设备删除
516
544
  this.syncDataCallBack({
@@ -529,7 +557,7 @@ class GizwitsMiniSDK {
529
557
  } else {
530
558
  // 结束同步
531
559
  GizLog.debug("send cancel sync to device")
532
- this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(CancelSync.pack()).buffer)
560
+ this.bleHandle.write(curDevice.deviceId, numberArray2Uint8Array(CancelSync.pack()).buffer)
533
561
  this.syncDataCallBack({
534
562
  event: "SYNC_END",
535
563
  })
@@ -576,7 +604,7 @@ class GizwitsMiniSDK {
576
604
  const isOnline = (data as IDeviceStatusChangedProps).attrs.is_online;
577
605
  this.setDeviceMeta(target, 'isOnline', isOnline);
578
606
  }
579
-
607
+
580
608
  if (this.listenerMap['GizDeviceAttrsNotifications']) {
581
609
 
582
610
  // 需要把枚举 拓展格式化回来
@@ -900,7 +928,7 @@ class GizwitsMiniSDK {
900
928
  try {
901
929
  res({success: false, message: 'timeout'})
902
930
  } catch (error) {
903
-
931
+
904
932
  }
905
933
  }, 3000)
906
934
  })
@@ -1022,9 +1050,9 @@ class GizwitsMiniSDK {
1022
1050
  switch (type) {
1023
1051
  case 'BLE': {
1024
1052
  // 连接BLE
1025
- const data = await this.bleHandle.connectDevice(target);
1053
+ const data = await this.bleHandle.connectDevice(target.bleDeviceID);
1026
1054
  if (data.success) {
1027
-
1055
+
1028
1056
  // 蓝牙设备比较特殊,在get 里面从bleHandle里找到连接的设备,再把connectType 设置成BLE,所以这里更新metaData 要强制更新并推送
1029
1057
  this.setDeviceMeta(target, 'connectType', 'BLE', true);
1030
1058
  setTimeout(() => {
@@ -1270,8 +1298,6 @@ class GizwitsMiniSDK {
1270
1298
  public getBindingList = async () => {
1271
1299
  const data = await getBindingList();
1272
1300
  this.deviceList = data.data || [];
1273
- // 推送
1274
- this.notiDeviceList();
1275
1301
  return data;
1276
1302
  };
1277
1303
 
@@ -1375,4 +1401,4 @@ class GizwitsMiniSDK {
1375
1401
  this.keepScanTimer && clearInterval(this.keepScanTimer);
1376
1402
  };
1377
1403
  }
1378
- export default GizwitsMiniSDK;
1404
+ export default GizwitsMiniSDK;
@@ -1,10 +1,10 @@
1
+ import { enc, AES, mode, pad } from 'crypto-js';
1
2
  import openApiRequest, { IServiceResult } from '../openApiRequest';
2
3
  import getRandomCodes from '../randomCode';
3
4
  import { IRandomCodesResult } from '../sdk';
4
5
  import { psKeySign } from './tool';
5
6
  // eslint-disable-next-line import/no-commonjs
6
7
  // const CryptoJS = require('crypto-js');
7
- import { enc, AES, mode, pad } from 'crypto-js';
8
8
 
9
9
  export interface IOpenApiDevice {
10
10
  product_key: string;
@@ -26,6 +26,59 @@ interface IDeviceRes {
26
26
  devices: IOpenApiDevice[];
27
27
  }
28
28
 
29
+ // 云端aes 特殊解码
30
+ class Padding {
31
+ /**
32
+ * Pads data using the algorithm defined in PKCS #5/7.
33
+ *
34
+ * @param data The data to pad.
35
+ * @param blockSize The multiple that the data should be padded to.
36
+ *
37
+ * @example
38
+ *
39
+ * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
40
+ */
41
+ pad = (data, blockSize) => {
42
+ }
43
+
44
+
45
+ /**
46
+ * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
47
+ *
48
+ * @param data The data to unpad.
49
+ *
50
+ * @example
51
+ *
52
+ * CryptoJS.pad.Pkcs7.unpad(wordArray);
53
+ */
54
+ unpad = (data) => {
55
+ const AES_BLOCK_LEN = 16;
56
+ const len = data.sigBytes;
57
+ let readed = 0;
58
+ let repeat = 1;
59
+ const stringData= data.toString(enc.Utf8);
60
+ while(readed + AES_BLOCK_LEN <= len)
61
+ {
62
+ readed += AES_BLOCK_LEN;
63
+ }
64
+ for(let i = 0; i < (AES_BLOCK_LEN - 2) / 2; i++)
65
+ {
66
+ const start = readed - i * 2;
67
+ if(stringData.substring(start, start - 2) == stringData.substring(start - 2, start - 4))
68
+ {
69
+ repeat++;
70
+ }
71
+ else
72
+ {
73
+ readed -= repeat * 2;
74
+
75
+ break;
76
+ }
77
+ }
78
+ data.sigBytes = readed;
79
+ }
80
+ }
81
+
29
82
  export const getBindingList = async (): Promise<IServiceResult<IDevice[]>> => {
30
83
  const data = await openApiRequest<IDeviceRes>(
31
84
  '/app/bindings?show_disabled=0&limit=1000&skip=0',
@@ -195,12 +248,23 @@ export async function safeRegister({
195
248
  false
196
249
  );
197
250
  if (data.success) {
198
- // 解码
251
+ const successDevices = unPackSafeRegisterRes({productSecret, iv, data: data.data});
252
+ const failedDevices = [];
253
+
254
+ const targetDevice = successDevices.find(item => item.mac === mac);
255
+ if (!targetDevice) {
256
+ // 不存在
257
+ failedDevices.push({
258
+ mac,
259
+ })
260
+ }
261
+
262
+ // TODO 解码
199
263
  return {
200
264
  success: true,
201
265
  data: {
202
- successDevices: [],
203
- failedDevices: [],
266
+ successDevices,
267
+ failedDevices,
204
268
  },
205
269
  };
206
270
  }
@@ -210,6 +274,30 @@ export async function safeRegister({
210
274
  };
211
275
  }
212
276
 
277
+ const unPackSafeRegisterRes = ({productSecret, data, iv}: {productSecret: string, data: string, iv: any}) => {
278
+ const aesKey = enc.Hex.parse(productSecret)
279
+ const bodyHex = enc.Hex.parse(data)
280
+ let resEncrypted = AES.decrypt(enc.Base64.stringify(bodyHex), aesKey, { iv: iv, mode: mode.ECB, padding: new Padding() });
281
+ const resString = resEncrypted.toString(enc.Utf8);
282
+ const newData = [];
283
+ resString.split(',').map(item => {
284
+ const tmp = item.split('&');
285
+ const mac = tmp[0].replace('mac=', '');
286
+ const did = tmp[1].replace('did=', '');
287
+ newData.push({
288
+ mac, did
289
+ })
290
+ })
291
+ return newData;
292
+ }
293
+
294
+ // const unPackSafeRegister = unPackSafeRegisterRes({
295
+ // productSecret: 'aaa0840301e04748adaf9fcd160e7508',
296
+ // iv: enc.Hex.parse(''),
297
+ // data: '56ab36690dcb1e42bc3e69dab30c2e670c2188dfb76cb5a2f12986d18eb069f0f63d3c89ab069f3573ef81ca02936ad4'
298
+ // })
299
+ // console.log('unPackSafeRegisterunPackSafeRegister', unPackSafeRegister)
300
+
213
301
  interface IRenameProps {
214
302
  name?: string;
215
303
  did: string;
@@ -2,15 +2,21 @@ import errorCode from "../errorCode";
2
2
  import { IRandomCodesResult, IResult } from "../sdk";
3
3
  import { ab2hex, advertisData2PkAndMac, isWXDevicesResult } from '../utils';
4
4
 
5
- import GizLog from "../GizLog";
6
- import { BleHandle } from "../handler/ble";
7
- import WifiConfig from "../protocol/WifiConfig";
8
- import sleep from "../sleep";
9
5
  import {
10
- getBLEDeviceCharacteristics, getBLEDeviceServices, getBluetoothAdapterState, getBluetoothDevices,
11
- notifyBLECharacteristicValueChange, retryConnect, startBluetoothDevicesDiscovery, unpackWriteBLECharacteristicValue
6
+ getBluetoothAdapterState,
7
+ startBluetoothDevicesDiscovery,
8
+ getBluetoothDevices,
9
+ notifyBLECharacteristicValueChange,
10
+ unpackWriteBLECharacteristicValue,
11
+ getBLEDeviceServices,
12
+ getBLEDeviceCharacteristics,
13
+ retryConnect,
12
14
  } from '../wechatApi';
15
+ import sleep from "../sleep";
13
16
  import ConfigBase from "./ConfigBase";
17
+ import WifiConfig from "../protocol/WifiConfig";
18
+ import GizLog from "../GizLog";
19
+ import { BleHandle } from "../handler/ble";
14
20
 
15
21
  interface IArgs {
16
22
  bleDeviceId: string;
@@ -56,10 +62,10 @@ export function sendBLEConfigCmd({
56
62
  'GIZ_SDK: createBLEConnection start: ', bleDeviceId
57
63
  );
58
64
  await bleHandle.disableScan()
59
-
65
+
60
66
  const connectData = await retryConnect(bleDeviceId, 10 * 1000);
61
67
  bleHandle.enableScan();
62
-
68
+
63
69
  GizLog.debug(
64
70
  'GIZ_SDK: createBLEConnection end, res:', connectData
65
71
  );
@@ -125,9 +131,9 @@ export function sendBLEConfigCmd({
125
131
  service.uuid,
126
132
  characteristic.uuid
127
133
  );
128
-
134
+
129
135
  // 这里有个问题,模组好像不一定每次都会回
130
- const handleBLECharacteristicValueChange = (res: WechatMiniprogram.OnBLECharacteristicValueChangeListenerResult) => {
136
+ const handleBLECharacteristicValueChange = (res: WechatMiniprogram.OnBLECharacteristicValueChangeCallbackResult) => {
131
137
  const hexString = ab2hex(res.value);
132
138
  GizLog.debug('GIZ_SDK: 收到设备返回ack', hexString)
133
139
  if (hexString === configAck) {
@@ -147,7 +153,7 @@ export function sendBLEConfigCmd({
147
153
  );
148
154
 
149
155
  if (checkInterrupt()) return;
150
-
156
+
151
157
  await unpackWriteBLECharacteristicValue(
152
158
  bleDeviceId,
153
159
  service.uuid,
@@ -163,7 +169,7 @@ export function sendBLEConfigCmd({
163
169
  arrayBuffer
164
170
  );
165
171
  }, 2000)
166
-
172
+
167
173
  // if (res.errCode === 0) {
168
174
  // resolve(true);
169
175
  // } else{
@@ -219,7 +225,7 @@ class BLEConfig extends ConfigBase {
219
225
  // 无效蓝牙设备或者蓝牙设备广播数据为空,返回失败
220
226
  return false;
221
227
  }
222
-
228
+
223
229
  const {productKey, mac} = advertisData2PkAndMac(bleDevice.advertisData, this.specialProductKeys)
224
230
 
225
231
 
@@ -243,7 +249,7 @@ class BLEConfig extends ConfigBase {
243
249
  // await closeBluetoothAdapter();
244
250
  // await openBluetoothAdapter();
245
251
  // } catch (error) {
246
-
252
+
247
253
  // }
248
254
  const stateRes = await getBluetoothAdapterState();
249
255
  if (!stateRes.available) {
@@ -374,7 +380,7 @@ class BLEConfig extends ConfigBase {
374
380
  bleDevices,
375
381
  devices.filter((d) => this.isValidBleDevice(d, softAPSSIDPrefix))
376
382
  )
377
- : wx.offBluetoothDeviceFound();
383
+ : wx.offBluetoothDeviceFound(handleFoundDevices);
378
384
  };
379
385
 
380
386
  wx.onBluetoothDeviceFound(handleFoundDevices);
@@ -408,7 +414,7 @@ class BLEConfig extends ConfigBase {
408
414
 
409
415
  // 如果有一个设备发送成功,则不再发现新设备
410
416
  GizLog.debug("GIZ_SDK: offBluetoothDeviceFound ready search device")
411
- wx.offBluetoothDeviceFound();
417
+ wx.offBluetoothDeviceFound(handleFoundDevices);
412
418
  };
413
419
 
414
420
  // 开始大循环搜索
@@ -427,4 +433,4 @@ class BLEConfig extends ConfigBase {
427
433
  };
428
434
  }
429
435
 
430
- export default BLEConfig;
436
+ export default BLEConfig;
@@ -1,11 +0,0 @@
1
- type EventType = "BleDeviceConnectStart" | "BleDeviceConnectEnd" | "BleDeviceConnectBind" | "BleDeviceConnectLogin" | "BleDeviceConnectFinish";
2
- type FailureType = Omit<EventType, 'BleDeviceConnectStart' | 'BleDeviceConnectFinish'>;
3
- interface IProps {
4
- device: IDevice;
5
- eventID: string;
6
- eventType: EventType;
7
- success: boolean;
8
- failureType?: FailureType;
9
- }
10
- export declare function reportEvent({ device, eventID, eventType, success, failureType }: IProps): Promise<import("../openApiRequest").IServiceResult<any>>;
11
- export {};
@@ -1,116 +0,0 @@
1
- import { version } from '../../package.json';
2
- import { getGlobalData } from "../globalData";
3
- import openApiRequest from '../openApiRequest';
4
-
5
- interface MobileInfo {
6
- brand: string;
7
- model: string; // 设备型号。新机型刚推出一段时间会显示unknown,微信会尽快进行适配。
8
- pixelRatio: number;
9
- systemVersion: string; // 操作系统版本
10
- platform: string; // 客户端平台
11
- }
12
-
13
- interface AppInfo {
14
- wxSdkVersion: string; // 客户端基础库版本
15
- gizwitsSdkVersion: string; // Gizwits SDK 版本
16
- appID: string; // gizwitsAppID
17
- bluetoothEnabled?: boolean; // 蓝牙是否可用
18
- locationEnabled?: boolean; // 定位是否可用
19
- wifiEnabled?: boolean; // wifi是否可用
20
- }
21
-
22
- // 统计每天设备活跃数
23
- // 统计设备失败原因
24
- // 统计设备连接时长
25
- // 统计连接每个阶段时长
26
-
27
- type EventType = "BleDeviceConnectStart" | "BleDeviceConnectEnd" | "BleDeviceConnectBind" | "BleDeviceConnectLogin" | "BleDeviceConnectFinish";
28
- type FailureType = Omit<EventType, 'BleDeviceConnectStart' | 'BleDeviceConnectFinish'>
29
-
30
- interface Event {
31
- origin: "MINI-WX",
32
- mobileInfo: MobileInfo,
33
- userInfo: null,
34
- appInfo: AppInfo,
35
- eventID: string,
36
- eventType: EventType,
37
- monitorTarget: {
38
- device: {
39
- mac: string;
40
- did: string;
41
- productKey: string;
42
- },
43
- success: boolean;
44
- failureType?: FailureType
45
- },
46
- time: Date,
47
- timeStamp: Number,
48
- }
49
-
50
- class BaseInfo {
51
- mobile: MobileInfo;
52
- app: AppInfo;
53
- constructor() {
54
- wx.getSystemInfoAsync({
55
- success: (res) => {
56
- this.app = {
57
- wxSdkVersion: res.SDKVersion,
58
- gizwitsSdkVersion: version,
59
- appID: 'unknown',
60
- bluetoothEnabled: res.bluetoothEnabled,
61
- locationEnabled: res.locationEnabled,
62
- wifiEnabled: res.wifiEnabled,
63
- };
64
-
65
- this.mobile = {
66
- brand: res.brand,
67
- model: res.model,
68
- pixelRatio: res.pixelRatio,
69
- systemVersion: res.system,
70
- platform: res.platform,
71
- };
72
- },
73
- });
74
- }
75
-
76
- updateAppId(appId: string) {
77
- this.app.appID = appId;
78
- }
79
- }
80
-
81
- const baseInfo = new BaseInfo();
82
-
83
- interface IProps {
84
- device: IDevice;
85
- eventID: string;
86
- eventType: EventType,
87
- success: boolean;
88
- failureType?: FailureType
89
- }
90
-
91
- export async function reportEvent({ device, eventID, eventType, success, failureType }: IProps) {
92
- baseInfo.updateAppId(getGlobalData('appID') || 'unknown');
93
- const path = `/v2/products/${device.productKey}/devices/bluetooth-connect-data`;
94
- const curDate = new Date();
95
-
96
- const eventData: Event = {
97
- origin: "MINI-WX",
98
- mobileInfo: baseInfo.mobile,
99
- userInfo: null,
100
- appInfo: baseInfo.app,
101
- eventID,
102
- eventType,
103
- monitorTarget: {
104
- device,
105
- success,
106
- failureType,
107
- },
108
- time: curDate,
109
- timeStamp: Math.floor(curDate.getTime() / 1000),
110
- }
111
-
112
- return openApiRequest<any>(path, {
113
- data: eventData,
114
- method: 'POST',
115
- }, true);
116
- }