From d25c64ea511a28eb343fd0736da4ecfc6ec81f21 Mon Sep 17 00:00:00 2001 From: lvwang2002 Date: Fri, 29 Mar 2024 01:09:57 +0800 Subject: [PATCH] =?UTF-8?q?feature():1.=E4=BF=AE=E6=94=B9dyglucose?= =?UTF-8?q?=E7=9A=84=E6=B6=88=E6=81=AF=E5=8F=91=E9=80=81=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E9=80=82=E9=85=8D=E6=96=B0=E7=89=88=E7=A8=8B=E5=BA=8F=202.?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E7=94=A8=E4=B8=8D=E5=88=B0=E7=9A=84=E8=AF=BB?= =?UTF-8?q?=E5=8D=A1=E5=BA=93=E5=BC=95=E7=94=A8=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ios/RNBTDevice/Device/RNMethodModule.h | 13 +- ios/RNBTDevice/Device/RNMethodModule.mm | 72 +-- src/rn-dy-glucose-driver.js | 621 +++++++++++++----------- 3 files changed, 377 insertions(+), 329 deletions(-) diff --git a/ios/RNBTDevice/Device/RNMethodModule.h b/ios/RNBTDevice/Device/RNMethodModule.h index 4e30029..4bc9a38 100755 --- a/ios/RNBTDevice/Device/RNMethodModule.h +++ b/ios/RNBTDevice/Device/RNMethodModule.h @@ -17,14 +17,15 @@ #import "ENCholesterolDevice.h" #import "RCTEventEmitter.h" -#if TARGET_IPHONE_SIMULATOR//模拟器 +//#if TARGET_IPHONE_SIMULATOR//模拟器 +//真机 @interface RNMethodModule : NSObject -#elif TARGET_OS_IPHONE//真机 -#import "INVSSDK/INVSSDK.h" -#import "INVSSDK/NSString+ThreeDES.h" -@interface RNMethodModule : NSObject -#endif +//#elif TARGET_OS_IPHONE//真机 +//#import "INVSSDK/INVSSDK.h" +//#import "INVSSDK/NSString+ThreeDES.h" +//@interface RNMethodModule : NSObject +//#endif diff --git a/ios/RNBTDevice/Device/RNMethodModule.mm b/ios/RNBTDevice/Device/RNMethodModule.mm index 025bf9b..3f1cdfb 100755 --- a/ios/RNBTDevice/Device/RNMethodModule.mm +++ b/ios/RNBTDevice/Device/RNMethodModule.mm @@ -36,7 +36,7 @@ #if TARGET_IPHONE_SIMULATOR//模拟器 #elif TARGET_OS_IPHONE//真机 - INVSBleTool *_bletool; +// INVSBleTool *_bletool; #endif BLEDevice *_cardDevice; Boolean _isUpdateDeviceList; @@ -66,7 +66,7 @@ RCT_EXPORT_MODULE(); #if TARGET_IPHONE_SIMULATOR//模拟器 #elif TARGET_OS_IPHONE//真机 - _bletool=[[INVSBleTool alloc]init:self]; +// _bletool=[[INVSBleTool alloc]init:self]; #endif @@ -757,7 +757,7 @@ RCT_REMAP_METHOD(stopCardReaderScan, #if TARGET_IPHONE_SIMULATOR//模拟器 #elif TARGET_OS_IPHONE//真机 - [_bletool disconnectBt]; +// [_bletool disconnectBt]; #endif // if(!_cardDevice){ @@ -789,7 +789,7 @@ RCT_EXPORT_METHOD(connectCardReader:(NSString *)uuid #if TARGET_IPHONE_SIMULATOR//模拟器 #elif TARGET_OS_IPHONE//真机 - [_bletool connectBt:[device getPeripheral]]; +// [_bletool connectBt:[device getPeripheral]]; #endif _cardDevice = device; @@ -819,7 +819,7 @@ RCT_EXPORT_METHOD(connectCardReader:(NSString *)uuid #if TARGET_IPHONE_SIMULATOR//模拟器 #elif TARGET_OS_IPHONE//真机 - [_bletool disconnectBt]; +// [_bletool disconnectBt]; #endif return; } @@ -855,37 +855,37 @@ RCT_REMAP_METHOD(readCard, #if TARGET_IPHONE_SIMULATOR//模拟器 #elif TARGET_OS_IPHONE//真机 - if(!_bletool){ - reject(@"400",@"no device",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]); - return; - } - - NSDictionary *obj = [_bletool readCard]; - if(!obj){ - reject(@"400",@"no device",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]); - return; - } - -// NSMutableString *resultContent = [[NSMutableString alloc] init]; - - NSInteger resultFlag = [obj[@"resultFlag"] integerValue]; - if(resultFlag == -1){ - reject(@"400",@"no data",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]); - }else{ - NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithCapacity:10]; - - [info setObject:obj[@"partyName"] forKey:@"name"]; - [info setObject:obj[@"certAddress"] forKey:@"address"]; - [info setObject:obj[@"bornDay"] forKey:@"birth"]; - [info setObject:obj[@"expDate"] forKey:@"end"]; - [info setObject:obj[@"certNumber"] forKey:@"idNo"]; - [info setObject:obj[@"nation"] forKey:@"nation"]; - [info setObject:obj[@"certOrg"] forKey:@"police"]; - [info setObject:obj[@"gender"] forKey:@"sex"]; - [info setObject:obj[@"effDate"] forKey:@"start"]; - - resolve([info copy]); - } +// if(!_bletool){ +// reject(@"400",@"no device",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]); +// return; +// } +// +// NSDictionary *obj = [_bletool readCard]; +// if(!obj){ +// reject(@"400",@"no device",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]); +// return; +// } +// +//// NSMutableString *resultContent = [[NSMutableString alloc] init]; +// +// NSInteger resultFlag = [obj[@"resultFlag"] integerValue]; +// if(resultFlag == -1){ +// reject(@"400",@"no data",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]); +// }else{ +// NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithCapacity:10]; +// +// [info setObject:obj[@"partyName"] forKey:@"name"]; +// [info setObject:obj[@"certAddress"] forKey:@"address"]; +// [info setObject:obj[@"bornDay"] forKey:@"birth"]; +// [info setObject:obj[@"expDate"] forKey:@"end"]; +// [info setObject:obj[@"certNumber"] forKey:@"idNo"]; +// [info setObject:obj[@"nation"] forKey:@"nation"]; +// [info setObject:obj[@"certOrg"] forKey:@"police"]; +// [info setObject:obj[@"gender"] forKey:@"sex"]; +// [info setObject:obj[@"effDate"] forKey:@"start"]; +// +// resolve([info copy]); +// } #endif diff --git a/src/rn-dy-glucose-driver.js b/src/rn-dy-glucose-driver.js index 92fed9f..54112bf 100755 --- a/src/rn-dy-glucose-driver.js +++ b/src/rn-dy-glucose-driver.js @@ -1,6 +1,6 @@ 'use strict'; import React, { Component } from 'react'; -import {NativeModules,DeviceEventEmitter,Platform} from 'react-native'; +import { NativeModules, DeviceEventEmitter, Platform } from 'react-native'; @@ -8,21 +8,21 @@ let MethodModule; if (Platform.OS === 'ios') { MethodModule = NativeModules.RNSanModule; } else { - MethodModule = NativeModules.RNMethodModule; + MethodModule = NativeModules.RNMethodModule; } - - -const OVER_TIME = 5*1000; -const CONNECT_OVER_TIME = 35*1000; + + +const OVER_TIME = 5 * 1000; +const CONNECT_OVER_TIME = 35 * 1000; const COMMAND_TIME_INTERVAL = 200; -const PROGRESS_TIME_INTERVAL =8*1000; +const PROGRESS_TIME_INTERVAL = 8 * 1000; const TAG = 'MY_RNDY'; -if(__DEV__){ +if (__DEV__) { const version = 201704011315; - console.log(TAG,'dyg driver version:',version); + console.log(TAG, 'dyg driver version:', version); } /** 监控的消息参数 */ @@ -35,7 +35,7 @@ const DYG_ON_GET_ALL_DATA = 'DYG_ON_GET_ALL_DATA'; const DYG_ON_START_MONITOR = 'DYG_ON_START_MONITOR'; const DYG_ON_STOP_MONITOR = 'DYG_ON_STOP_MONITOR'; const DYG_ON_UPDATE_NEW_DATA = 'DYG_ON_UPDATE_NEW_DATA'; -const DYG_ON_GET_BATTERY = 'DYG_ON_GET_BATTERY'; +const DYG_ON_GET_BATTERY = 'DYG_ON_GET_BATTERY'; /* =============================== 常量 ======================== */ const START_MONITOR = 1; @@ -57,8 +57,10 @@ const GET_BATTERY = 16; let driver = null; -export default class RNDYGlucoseDriver{ - constructor(){ +export default class RNDYGlucoseDriver { + subscriptionMap = {}; + + constructor() { this._eventMap = { }; @@ -82,8 +84,8 @@ export default class RNDYGlucoseDriver{ } /** 创建 */ - static shareDriver(){ - if(driver === null){ + static shareDriver() { + if (driver === null) { driver = new RNDYGlucoseDriver(); } @@ -91,8 +93,8 @@ export default class RNDYGlucoseDriver{ } /** 开始扫描 */ - startScan(){ - console.log(TAG,'开始扫描!!!!!!'); + startScan() { + console.log(TAG, '开始扫描!!!!!!'); if (Platform.OS === 'ios') { NativeModules.RNMethodModule.startScanDynamicGlucose(); NativeModules.RNMethodModule.forceUpdateDeviceList(); @@ -103,78 +105,78 @@ export default class RNDYGlucoseDriver{ } /** 停止扫描 */ - stopScan(){ + stopScan() { console.log(TAG, '停止扫描'); if (Platform.OS === 'ios') { NativeModules.RNMethodModule.stopScanDynamicGlucose(); - }else if (Platform.OS === 'android'){ + } else if (Platform.OS === 'android') { MethodModule.stopScanDynamicGlucose(); } } - set onUpdateDeviceList(delegate){ - if(typeof delegate !== 'function'){ - throw new Error('update device list must be a function'); + set onUpdateDeviceList(delegate) { + if (typeof delegate !== 'function') { + throw new Error('update device list must be a function'); } this._onUpdateDeviceList = delegate; } - set onUpdateNewData(delegate){ - if(typeof delegate !== 'function'){ - throw new Error('update device list must be a function'); + set onUpdateNewData(delegate) { + if (typeof delegate !== 'function') { + throw new Error('update device list must be a function'); } this._onUpdateNewData = delegate; } /** 开始监控 */ - startMonitor(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + startMonitor(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject(new Error('paras type error')); return; } - console.log(TAG,'start monitor'); - MethodModule.startMonitorDYG(deviceMac,START_MONITOR); - this._eventMap[DYG_ON_START_MONITOR] = (deviceInfo)=>{ - console.log(TAG,'resolve connect'); + console.log(TAG, 'start monitor'); + MethodModule.startMonitorDYG(deviceMac, START_MONITOR); + this._eventMap[DYG_ON_START_MONITOR] = (deviceInfo) => { + console.log(TAG, 'resolve connect'); resolve(deviceInfo.isSuc); - } + } }); const timer = this._timeoutPromise(OVER_TIME); - const mixPromise = Promise.race([devicePromise,timer]); + const mixPromise = Promise.race([devicePromise, timer]); return mixPromise; } /** 停止监控 */ - stopMonitor(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + stopMonitor(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject(new Error('paras type error')); return; } - console.log(TAG,'stop monitor'); - MethodModule.stopMonitorDYG(deviceMac,STOP_MONITOR); - this._eventMap[DYG_ON_STOP_MONITOR] = (deviceInfo)=>{ - console.log(TAG,'resolve stop monitor'); + console.log(TAG, 'stop monitor'); + MethodModule.stopMonitorDYG(deviceMac, STOP_MONITOR); + this._eventMap[DYG_ON_STOP_MONITOR] = (deviceInfo) => { + console.log(TAG, 'resolve stop monitor'); resolve(deviceInfo.isSuc); - } + } }); const timer = this._timeoutPromise(OVER_TIME); - const mixPromise = Promise.race([devicePromise,timer]); + const mixPromise = Promise.race([devicePromise, timer]); return mixPromise; } /** 创建通道 */ - async createAuthChannel(deviceMac){ - return new Promise(async (resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + async createAuthChannel(deviceMac) { + return new Promise(async (resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - try{ + try { if (Platform.OS === 'android') { MethodModule.stopScanDynamicGlucose(); } else if (Platform.OS === 'ios') { @@ -204,8 +206,8 @@ export default class RNDYGlucoseDriver{ } resolve(info); - }catch(e){ - console.log(TAG,e); + } catch (e) { + console.log(TAG, e); if (Platform.OS === 'android') { MethodModule.startScanDynamicGlucose(); } else if (Platform.OS === 'ios') { @@ -214,144 +216,144 @@ export default class RNDYGlucoseDriver{ reject(e); } }); - + } /** 断开除指定设备 */ - disconnecAllDevicestWithout(deviceMac){ + disconnecAllDevicestWithout(deviceMac) { MethodModule.disconnecAllDYGDevicetWithout(deviceMac); } /** 开始连接单独设备 */ - connectDevice(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + connectDevice(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'driver auth'); - MethodModule.connectDynamicGlucose(deviceMac); + console.log(TAG, 'driver auth'); + MethodModule.connectDynamicGlucose(deviceMac); if (Platform.OS === 'android') { MethodModule.forceUpdateDeviceList(); } else if (Platform.OS === 'ios') { NativeModules.RNMethodModule.forceUpdateDeviceList(); } - this._eventMap[DYG_CREATED_CHANNEL] = (deviceInfo)=>{ - console.log(TAG,'resolve connect'); + this._eventMap[DYG_CREATED_CHANNEL] = (deviceInfo) => { + console.log(TAG, 'resolve connect'); resolve(deviceInfo); - } + } }); const timer = this._timeoutPromise(CONNECT_OVER_TIME); - const mixPromise = Promise.race([devicePromise,timer]); + const mixPromise = Promise.race([devicePromise, timer]); return mixPromise; } /** 认证设备 */ - doAuthorization(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + doAuthorization(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'driver start'); - MethodModule.doAuthorizationDYG(deviceMac,START_MONITOR); - this._eventMap[DYG_ON_DO_AUTHORIZATION] = (deviceInfo)=>{ - console.log(TAG,'resolve auth'); + console.log(TAG, 'driver start'); + MethodModule.doAuthorizationDYG(deviceMac, START_MONITOR); + this._eventMap[DYG_ON_DO_AUTHORIZATION] = (deviceInfo) => { + console.log(TAG, 'resolve auth'); resolve(deviceInfo); - } + } }); return this._mixTimeoutPromise(devicePromise); } /** 获得状态 */ - getMonitorStatus(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + getMonitorStatus(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'get monitor status'); - MethodModule.getMonitorStatusDYG(deviceMac,GET_MONITOR_STATUS); - this._eventMap[DYG_ON_GET_MONITOR_STATUS] = (deviceInfo)=>{ - console.log(TAG,'resolve get monitor status'); + console.log(TAG, 'get monitor status'); + MethodModule.getMonitorStatusDYG(deviceMac, GET_MONITOR_STATUS); + this._eventMap[DYG_ON_GET_MONITOR_STATUS] = (deviceInfo) => { + console.log(TAG, 'resolve get monitor status'); resolve(deviceInfo.isStartMonitor); - } + } }); return this._mixTimeoutPromise(devicePromise); } /** 获得名字 */ - getName(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + getName(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'get monitor status'); - MethodModule.getNameDYG(deviceMac,GET_NAME); + console.log(TAG, 'get monitor status'); + MethodModule.getNameDYG(deviceMac, GET_NAME); }); return this._mixTimeoutPromise(devicePromise); } /** 获得版本号 */ - getVersion(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + getVersion(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'get monitor status'); - MethodModule.getVersionDYG(deviceMac,getVersion); + console.log(TAG, 'get monitor status'); + MethodModule.getVersionDYG(deviceMac, getVersion); }); return this._mixTimeoutPromise(devicePromise); } /** 获得序列号 */ - getSN(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + getSN(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'get monitor status'); - MethodModule.getSnDYG(deviceMac,getSN); + console.log(TAG, 'get monitor status'); + MethodModule.getSnDYG(deviceMac, getSN); }); return this._mixTimeoutPromise(devicePromise); } /** 获得电池电量 */ - getBattery(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + getBattery(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'get battery status'); + console.log(TAG, 'get battery status'); - MethodModule.getBatteryDYG(deviceMac,GET_BATTERY); - this._eventMap[DYG_ON_GET_BATTERY] = (deviceInfo)=>{ - console.log(TAG,'resolve '+DYG_ON_GET_BATTERY); - const {value} = deviceInfo; - const percent = (value-2.85)/(2.95-2.85); // 改成2.95貌似比较合适 + MethodModule.getBatteryDYG(deviceMac, GET_BATTERY); + this._eventMap[DYG_ON_GET_BATTERY] = (deviceInfo) => { + console.log(TAG, 'resolve ' + DYG_ON_GET_BATTERY); + const { value } = deviceInfo; + const percent = (value - 2.85) / (2.95 - 2.85); // 改成2.95貌似比较合适 resolve(percent); - } + } }); return this._mixTimeoutPromise(devicePromise); } - calculateDyRoc(index,refValue,values){ - return new Promise(async (resolve,reject)=>{ + calculateDyRoc(index, refValue, values) { + return new Promise(async (resolve, reject) => { const info = { - index:index, - refValue:refValue, - values:values - } + index: index, + refValue: refValue, + values: values + } - try{ + try { const values = await MethodModule.caculateDyRoc(info); resolve(values); - }catch(e){ + } catch (e) { } }) @@ -363,85 +365,97 @@ export default class RNDYGlucoseDriver{ * finish(error,[]); * progress(currentCount,amountCount,[],[]) */ - async getAllData(deviceMac,progress,finish){ - if(typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function'){ + async getAllData(deviceMac, progress, finish) { + if (typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function') { throw new Error('paras type error'); } - console.log(TAG,'get all data'); + console.log(TAG, 'get all data'); let receiveData = null; let dataList = []; let timer = null; - try{ + try { const count = await this.getAllDataCount(deviceMac); - if(count===0){ - finish(null,[]); - return; + if (count === 0) { + finish(null, []); + return; } - - receiveData = (deviceInfo)=>{ - if(deviceInfo.deviceMac !== deviceMac){ + + receiveData = (deviceInfo) => { + if (deviceInfo.deviceMac !== deviceMac) { return; } clearTimeout(timer); dataList = dataList.concat(deviceInfo.dataList); - - if(dataList.length>=count){ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); - finish(null,dataList); - return; - }else{ - progress(dataList.length,count,deviceInfo.dataList,dataList); - } - timer = setTimeout(()=>{ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); + if (dataList.length >= count) { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } + finish(null, dataList); + return; + } else { + progress(dataList.length, count, deviceInfo.dataList, dataList); + } + + timer = setTimeout(() => { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } finish(new Error('receive data time out')) - },PROGRESS_TIME_INTERVAL); + }, PROGRESS_TIME_INTERVAL); }; - - DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA,receiveData); + + this.subscriptionMap[DYG_ON_GET_ALL_DATA] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA, receiveData); await this._commadTimeInterval(COMMAND_TIME_INTERVAL); - MethodModule.getAllDataDYG(deviceMac,GET_ALL_DATA); + MethodModule.getAllDataDYG(deviceMac, GET_ALL_DATA); - timer = setTimeout(()=>{ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); + timer = setTimeout(() => { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } finish(new Error('receive data time out')) - },PROGRESS_TIME_INTERVAL); + }, PROGRESS_TIME_INTERVAL); - }catch(e){ - console.log(TAG,e); + } catch (e) { + console.log(TAG, e); finish(e); - } + } } - async getAllDataFromIndex(deviceMac,index,progress,finish){ - if(typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function'){ + async getAllDataFromIndex(deviceMac, index, progress, finish) { + if (typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function') { throw new Error('paras type error'); } - // index = 45 + // index = 45 - console.log(TAG,'get data from index'); + console.log(TAG, 'get data from index'); let receiveData = null; let dataList = []; let timer = null; - try{ + try { let count = await this.getAllDataCount(deviceMac); - if(count===0 || index>=count){ - finish(null,[]); - return; + if (count === 0 || index >= count) { + finish(null, []); + return; } - - count = count-index; - console.log(TAG,'count:',count); - receiveData = (deviceInfo)=>{ - if(deviceInfo.deviceMac !== deviceMac){ + + count = count - index; + console.log(TAG, 'count:', count); + receiveData = (deviceInfo) => { + if (deviceInfo.deviceMac !== deviceMac) { return; } @@ -449,110 +463,135 @@ export default class RNDYGlucoseDriver{ dataList = dataList.concat(deviceInfo.dataList); console.log(TAG, 'rcv data count', dataList.length); - if(dataList.length>=count){ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); - finish(null,dataList); + if (dataList.length >= count) { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } + finish(null, dataList); return; - }else{ - progress(dataList.length,count,deviceInfo.dataList,dataList); - } + } else { + progress(dataList.length, count, deviceInfo.dataList, dataList); + } + + timer = setTimeout(() => { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } - timer = setTimeout(()=>{ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); finish(new Error('receive data time out')) - },PROGRESS_TIME_INTERVAL); + }, PROGRESS_TIME_INTERVAL); }; - - DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA,receiveData); + + this.subscriptionMap[DYG_ON_GET_ALL_DATA] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA, receiveData); await this._commadTimeInterval(COMMAND_TIME_INTERVAL); - MethodModule.getAllDataFromIndexDYG(deviceMac,GET_ALL_DATA_FROM_INDEX,index); + MethodModule.getAllDataFromIndexDYG(deviceMac, GET_ALL_DATA_FROM_INDEX, index); - timer = setTimeout(()=>{ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); + timer = setTimeout(() => { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } finish(new Error('receive data time out')) - },PROGRESS_TIME_INTERVAL); + }, PROGRESS_TIME_INTERVAL); - }catch(e){ - console.log(TAG,e); + } catch (e) { + console.log(TAG, e); finish(e); - } + } } - async getNumberDataFromIndex(deviceMac,index,number,progress,finish){ - if(typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function'){ + async getNumberDataFromIndex(deviceMac, index, number, progress, finish) { + if (typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function') { throw new Error('paras type error'); } - console.log(TAG,'get data from index'); + console.log(TAG, 'get data from index'); let receiveData = null; let dataList = []; let timer = null; - try{ + try { let count = await this.getAllDataCount(deviceMac); - if(count===0 || index>=count){ - finish(null,[]); - return; + if (count === 0 || index >= count) { + finish(null, []); + return; } - - count = (count-index)>number?number:(count-index); - console.log(TAG,'count:',count); - receiveData = (deviceInfo)=>{ - if(deviceInfo.deviceMac !== deviceMac){ + + count = (count - index) > number ? number : (count - index); + console.log(TAG, 'count:', count); + receiveData = (deviceInfo) => { + if (deviceInfo.deviceMac !== deviceMac) { return; } clearTimeout(timer); dataList = dataList.concat(deviceInfo.dataList); console.log(TAG, 'rcv device data length:', dataList.length); - if(dataList.length>=count){ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); - finish(null,dataList); + if (dataList.length >= count) { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } + finish(null, dataList); return; - }else{ - progress(dataList.length,count,deviceInfo.dataList,dataList); - } + } else { + progress(dataList.length, count, deviceInfo.dataList, dataList); + } - timer = setTimeout(()=>{ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); + timer = setTimeout(() => { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } finish(new Error('receive data time out')); - },PROGRESS_TIME_INTERVAL); + }, PROGRESS_TIME_INTERVAL); }; - - DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA,receiveData); + + this.subscriptionMap[DYG_ON_GET_ALL_DATA] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA, receiveData); await this._commadTimeInterval(COMMAND_TIME_INTERVAL); - MethodModule.getNumberDataFromIndexDYG(deviceMac,GET_NUMBER_DATA_FROM_INDEX,index,count); + MethodModule.getNumberDataFromIndexDYG(deviceMac, GET_NUMBER_DATA_FROM_INDEX, index, count); - timer = setTimeout(()=>{ - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA,receiveData); + timer = setTimeout(() => { + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); + if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) { + this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove(); + delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选,从映射中删除键,避免内存泄漏 + } finish(new Error('receive data time out')); - },PROGRESS_TIME_INTERVAL); + }, PROGRESS_TIME_INTERVAL); - }catch(e){ - console.log(TAG,e); + } catch (e) { + console.log(TAG, e); finish(e); - } + } } /** 得到所有数据数量 */ - getAllDataCount(deviceMac){ - const devicePromise = new Promise((resolve,reject)=>{ - if(typeof deviceMac !== 'string'){ + getAllDataCount(deviceMac) { + const devicePromise = new Promise((resolve, reject) => { + if (typeof deviceMac !== 'string') { reject('paras type error'); return; } - console.log(TAG,'get all data count'); - MethodModule.getAllDataCountDYG(deviceMac,GET_ALL_DATA_COUNT); - this._eventMap[DYG_ON_GET_ALL_DATA_COUNT] = (deviceInfo)=>{ - console.log(TAG,'resolve '+DYG_ON_GET_ALL_DATA_COUNT); + console.log(TAG, 'get all data count'); + MethodModule.getAllDataCountDYG(deviceMac, GET_ALL_DATA_COUNT); + this._eventMap[DYG_ON_GET_ALL_DATA_COUNT] = (deviceInfo) => { + console.log(TAG, 'resolve ' + DYG_ON_GET_ALL_DATA_COUNT); resolve(deviceInfo.count); - } + } }); return this._mixTimeoutPromise(devicePromise); } @@ -565,154 +604,162 @@ export default class RNDYGlucoseDriver{ NativeModules.RNMethodModule.disconnectDevice(deviceMac) } } - - calculateBloodGlucose(index,refValue,values){ - return new Promise(async (resolve,reject)=>{ + + calculateBloodGlucose(index, refValue, values) { + return new Promise(async (resolve, reject) => { const info = { - index:index, - refValue:refValue, - values:values - } + index: index, + refValue: refValue, + values: values + } - try{ + try { const values = await MethodModule.caculateBloodGlucose(info); resolve(values); - }catch(e){ + } catch (e) { } }) - + } - _mixTimeoutPromise(devicePromise){ + _mixTimeoutPromise(devicePromise) { const timer = this._timeoutPromise(OVER_TIME); - const mixPromise = Promise.race([devicePromise,timer]); + const mixPromise = Promise.race([devicePromise, timer]); return mixPromise; } - _timeoutPromise(delay){ - return new Promise((resolve,reject)=>{ - setTimeout(()=>{ + _timeoutPromise(delay) { + return new Promise((resolve, reject) => { + setTimeout(() => { reject(new Error('timeout')); - },delay); + }, delay); }); } - _commadTimeInterval(interval){ - return new Promise((resolve,reject)=>{ - setTimeout(()=>{ + _commadTimeInterval(interval) { + return new Promise((resolve, reject) => { + setTimeout(() => { resolve('command await time out'); - },interval); + }, interval); }); } - - _registerEvent(eventName){ - this._eventMap[eventName] = (deviceInfo)=>{ - console.log(TAG,'resolve '+eventName); - resolve(deviceInfo); - } + + _registerEvent(eventName) { + this._eventMap[eventName] = (deviceInfo) => { + console.log(TAG, 'resolve ' + eventName); + resolve(deviceInfo); + } } - _isFunctionEmpty(event){ - if(event===undefined || event===null){ + _isFunctionEmpty(event) { + if (event === undefined || event === null) { return true; } return false; } - _executeEvent(eventName,deviceInfo){ + _executeEvent(eventName, deviceInfo) { const event = this._eventMap[eventName]; - if(this._isFunctionEmpty(event)){ - return; - } + if (this._isFunctionEmpty(event)) { + return; + } - event(deviceInfo); + event(deviceInfo); this._eventMap[eventName] = null; } /** 监控底层驱动发送的消息 */ - startMonitorDriverEvent(){ - this._createChannel = (deviceInfo)=>{ - console.log(TAG,'created channel'); - this._executeEvent(DYG_CREATED_CHANNEL,deviceInfo); + startMonitorDriverEvent() { + this._createChannel = (deviceInfo) => { + console.log(TAG, 'created channel'); + this._executeEvent(DYG_CREATED_CHANNEL, deviceInfo); }; - DeviceEventEmitter.addListener(DYG_CREATED_CHANNEL,this._createChannel); + this.subscriptionMap['DYG_CREATED_CHANNEL'] = DeviceEventEmitter.addListener(DYG_CREATED_CHANNEL, this._createChannel); - this._onDoAuthorization = (deviceInfo)=>{ - console.log(TAG,'received '+DYG_ON_DO_AUTHORIZATION); - this._executeEvent(DYG_ON_DO_AUTHORIZATION,deviceInfo); + this._onDoAuthorization = (deviceInfo) => { + console.log(TAG, 'received ' + DYG_ON_DO_AUTHORIZATION); + this._executeEvent(DYG_ON_DO_AUTHORIZATION, deviceInfo); }; - DeviceEventEmitter.addListener(DYG_ON_DO_AUTHORIZATION,this._onDoAuthorization); + this.subscriptionMap[DYG_ON_DO_AUTHORIZATION] = DeviceEventEmitter.addListener(DYG_ON_DO_AUTHORIZATION, this._onDoAuthorization); - this._onGetBattery = (deviceInfo)=>{ - console.log(TAG,'received '+DYG_ON_GET_BATTERY); - this._executeEvent(DYG_ON_GET_BATTERY,deviceInfo); + this._onGetBattery = (deviceInfo) => { + console.log(TAG, 'received ' + DYG_ON_GET_BATTERY); + this._executeEvent(DYG_ON_GET_BATTERY, deviceInfo); }; - DeviceEventEmitter.addListener(DYG_ON_GET_BATTERY,this._onGetBattery); + this.subscriptionMap[DYG_ON_GET_BATTERY] = DeviceEventEmitter.addListener(DYG_ON_GET_BATTERY, this._onGetBattery); - this._onGetAllDataCount = (deviceInfo)=>{ - console.log(TAG,'received '+DYG_ON_GET_ALL_DATA_COUNT); - this._executeEvent(DYG_ON_GET_ALL_DATA_COUNT,deviceInfo); + this._onGetAllDataCount = (deviceInfo) => { + console.log(TAG, 'received ' + DYG_ON_GET_ALL_DATA_COUNT); + this._executeEvent(DYG_ON_GET_ALL_DATA_COUNT, deviceInfo); }; - DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA_COUNT,this._onGetAllDataCount); + this.subscriptionMap[DYG_ON_GET_ALL_DATA_COUNT] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA_COUNT, this._onGetAllDataCount); - this._updateDeviceList = (deviceInfos)=>{ + this._updateDeviceList = (deviceInfos) => { // console.log(TAG,deviceInfos); - if(this._onUpdateDeviceList === null){ + if (this._onUpdateDeviceList === null) { return; } - const deviceList = deviceInfos.filter((device)=>{ - return device.deviceName.indexOf('TH-')>=0 + const deviceList = deviceInfos.filter((device) => { + return device.deviceName.indexOf('TH-') >= 0 }); this._onUpdateDeviceList(deviceList); - }; - DeviceEventEmitter.addListener(UPDATE_DEVICE_LIST,this._updateDeviceList); + }; + this.subscriptionMap[UPDATE_DEVICE_LIST] = DeviceEventEmitter.addListener(UPDATE_DEVICE_LIST, this._updateDeviceList); /** 获得当前监控的状态 */ - this._onGetMonitorStatus = (deviceInfo)=>{ - this._executeEvent(DYG_ON_GET_MONITOR_STATUS,deviceInfo); + this._onGetMonitorStatus = (deviceInfo) => { + this._executeEvent(DYG_ON_GET_MONITOR_STATUS, deviceInfo); } - DeviceEventEmitter.addListener(DYG_ON_GET_MONITOR_STATUS,this._onGetMonitorStatus); + this.subscriptionMap[DYG_ON_GET_MONITOR_STATUS] = DeviceEventEmitter.addListener(DYG_ON_GET_MONITOR_STATUS, this._onGetMonitorStatus); /** 获得是否已经开始监控 */ - this._onStartMonitor = (deviceInfo)=>{ - this._executeEvent(DYG_ON_START_MONITOR,deviceInfo); + this._onStartMonitor = (deviceInfo) => { + this._executeEvent(DYG_ON_START_MONITOR, deviceInfo); } - DeviceEventEmitter.addListener(DYG_ON_START_MONITOR,this._onStartMonitor); + this.subscriptionMap[DYG_ON_START_MONITOR] = DeviceEventEmitter.addListener(DYG_ON_START_MONITOR, this._onStartMonitor); - this._onStopMonitor = (deviceInfo)=>{ - this._executeEvent(DYG_ON_STOP_MONITOR,deviceInfo); + this._onStopMonitor = (deviceInfo) => { + this._executeEvent(DYG_ON_STOP_MONITOR, deviceInfo); } - DeviceEventEmitter.addListener(DYG_ON_STOP_MONITOR,this._onStopMonitor); + this.subscriptionMap[DYG_ON_STOP_MONITOR] = DeviceEventEmitter.addListener(DYG_ON_STOP_MONITOR, this._onStopMonitor); + - /** 监听接收到的单条新消息 */ - this._updateNewData = (deviceInfo)=>{ - if(this._onUpdateNewData === null){ + this._updateNewData = (deviceInfo) => { + if (this._onUpdateNewData === null) { return; } - this._onUpdateNewData(deviceInfo.index,deviceInfo.value); + this._onUpdateNewData(deviceInfo.index, deviceInfo.value); } - DeviceEventEmitter.addListener(DYG_ON_UPDATE_NEW_DATA,this._updateNewData); + this.subscriptionMap[DYG_ON_UPDATE_NEW_DATA] = DeviceEventEmitter.addListener(DYG_ON_UPDATE_NEW_DATA, this._updateNewData); } - endMonitorDriverEvent(){ - DeviceEventEmitter.removeListener(DYG_CREATED_CHANNEL,this._createChannel); - DeviceEventEmitter.removeListener(DYG_ON_DO_AUTHORIZATION,this._onDoAuthorization); - DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA_COUNT,this._onGetAllDataCount); - DeviceEventEmitter.removeListener(DYG_ON_GET_MONITOR_STATUS,this._onGetMonitorStatus); - DeviceEventEmitter.removeListener(UPDATE_DEVICE_LIST,this._updateDeviceList); - DeviceEventEmitter.removeListener(DYG_ON_START_MONITOR,this._onStartMonitor); - DeviceEventEmitter.removeListener(DYG_ON_STOP_MONITOR,this._onStopMonitor); - DeviceEventEmitter.removeListener(DYG_ON_UPDATE_NEW_DATA,this._updateNewData); - DeviceEventEmitter.removeListener(DYG_ON_GET_BATTERY,this._onGetBattery); + endMonitorDriverEvent() { + // DeviceEventEmitter.removeListener(DYG_CREATED_CHANNEL,this._createChannel); + // DeviceEventEmitter.removeListener(DYG_ON_DO_AUTHORIZATION,this._onDoAuthorization); + // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA_COUNT,this._onGetAllDataCount); + // DeviceEventEmitter.removeListener(DYG_ON_GET_MONITOR_STATUS,this._onGetMonitorStatus); + // DeviceEventEmitter.removeListener(UPDATE_DEVICE_LIST,this._updateDeviceList); + // DeviceEventEmitter.removeListener(DYG_ON_START_MONITOR,this._onStartMonitor); + // DeviceEventEmitter.removeListener(DYG_ON_STOP_MONITOR,this._onStopMonitor); + // DeviceEventEmitter.removeListener(DYG_ON_UPDATE_NEW_DATA,this._updateNewData); + // DeviceEventEmitter.removeListener(DYG_ON_GET_BATTERY,this._onGetBattery); + + // 移除监听器 + Object.keys(this.subscriptionMap).forEach(key => { + this.subscriptionMap[key].remove(); + }); + + // 清除订阅对象记录,避免内存泄漏 + this.subscriptionMap = {}; } }