From: kfl_614 Date: Fri, 4 Dec 2020 08:55:51 +0000 (+0800) Subject: refactor codes. X-Git-Url: http://git.snicker.com.cn/Users/apple/Desktop/static/gitweb.css?a=commitdiff_plain;h=b0ad43a3d16f8d80b40eaa1d78cf1c2af149bacf;p=protocol_srv.git refactor codes. --- diff --git a/app/src/main/java/com/enqualcomm/support/bean/heartRateStatus.java b/app/src/main/java/com/enqualcomm/support/bean/heartRateStatus.java index 6881146a..e8212c7b 100644 --- a/app/src/main/java/com/enqualcomm/support/bean/heartRateStatus.java +++ b/app/src/main/java/com/enqualcomm/support/bean/heartRateStatus.java @@ -8,40 +8,41 @@ public class heartRateStatus { private String lastTestTime; private int lastBPH; private int lastBPL; - private int lastSpo2=0; - - private int BPH_ref=0; - private int BPL_ref=0; - private int Age=0; - private int Sex=0; - private int sp02_adjust=0; - private int ppg_adjust=0; - private int bph_adjust=0; - private int bpl_adjust=0; - - public int ppg_threshold_max=0; - public int ppg_threshold_min=0; - public int bph_threshold_max=0; - public int bph_threshold_min=0; - public int bpl_threshold_max=0; - public int bpl_threshold_min=0; - - public void setXY_Ref(int refBPH,int refBPL,int refSex,int refAge){ - BPH_ref=refBPH; - BPL_ref=refBPL; - Age=refAge; - Sex=refSex; + private int lastSpo2 = 0; + + private int BPH_ref = 0; + private int BPL_ref = 0; + private int Age = 0; + private int Sex = 0; + private int sp02_adjust = 0; + private int ppg_adjust = 0; + private int bph_adjust = 0; + private int bpl_adjust = 0; + + public int ppg_threshold_max = 0; + public int ppg_threshold_min = 0; + public int bph_threshold_max = 0; + public int bph_threshold_min = 0; + public int bpl_threshold_max = 0; + public int bpl_threshold_min = 0; + + public void setXY_Ref(int refBPH, int refBPL, int refSex, int refAge) { + BPH_ref = refBPH; + BPL_ref = refBPL; + Age = refAge; + Sex = refSex; } - public void setAdjust(int _ppg_adjust,int _bph_adjust,int _bpl_adjust ,int _sp02_adjust){ - ppg_adjust=_ppg_adjust; - bph_adjust=_bph_adjust; - bpl_adjust=_bpl_adjust; - sp02_adjust=_sp02_adjust; + public void setAdjust(int _ppg_adjust, int _bph_adjust, int _bpl_adjust, int _sp02_adjust) { + ppg_adjust = _ppg_adjust; + bph_adjust = _bph_adjust; + bpl_adjust = _bpl_adjust; + sp02_adjust = _sp02_adjust; } private HEARTRATE_WORKINGSTAT currentStat; + public enum HEARTRATE_WORKINGSTAT { HEARTRATE_CLOSED, HEARTRATE_OPEN, @@ -49,99 +50,104 @@ public class heartRateStatus { HEARTRATE_WARED_AND_TESTING, HEARTRATE_TEST_SUCCESS, HEARTRATE_TEST_FAILED, - } ; + } + + ; - public boolean isHeartrRateExists(){ - return ICJniUtils.isPPGavailable()==1; + public boolean isHeartrRateExists() { + return ICJniUtils.isPPGavailable() == 1; } - public HEARTRATE_WORKINGSTAT getHeartrateWorkingStat(){ + public HEARTRATE_WORKINGSTAT getHeartrateWorkingStat() { return currentStat; } - public void setHeartrateStat(HEARTRATE_WORKINGSTAT stat){ + public void setHeartrateStat(HEARTRATE_WORKINGSTAT stat) { currentStat = stat; } - public int getPPG(){ - int ppg=lastHeartrate; - if(ppg_adjust!=0) - ppg+=ppg_adjust; + + public int getPPG() { + int ppg = lastHeartrate; + if (ppg_adjust != 0) + ppg += ppg_adjust; return ppg; } public int getBPH() { - int BPH=lastBPH; - if (BPH_ref>=35 && BPH_ref<200) { + int BPH = lastBPH; + if (BPH_ref >= 35 && BPH_ref < 200) { if (lastBPH > BPH_ref + 20) BPH = BPH_ref + 20; if (lastBPH < BPH_ref - 20) BPH = BPH_ref - 20; } - if (bph_adjust!=0){ - BPH+=bph_adjust; + if (bph_adjust != 0) { + BPH += bph_adjust; } return BPH; } + public int getBPL() { - int BPL=lastBPL; - if(BPL_ref>=35 && BPL_ref<200) { + int BPL = lastBPL; + if (BPL_ref >= 35 && BPL_ref < 200) { if (lastBPL > BPL_ref + 20) BPL = BPL_ref + 20; if (lastBPL < BPL_ref - 20) BPL = BPL_ref - 20; } - if (bpl_adjust!=0){ - BPL+=bpl_adjust; + if (bpl_adjust != 0) { + BPL += bpl_adjust; } return BPL; } - public int getSpo2(){ - int sp02=lastSpo2; - if (sp02_adjust!=0) - sp02+=sp02_adjust; + public int getSpo2() { + int sp02 = lastSpo2; + if (sp02_adjust != 0) + sp02 += sp02_adjust; return sp02; } - public String getTestTime(){ + public String getTestTime() { return lastTestTime; } - public void setLastTestTime(String testtime){ - lastTestTime=testtime; + + public void setLastTestTime(String testtime) { + lastTestTime = testtime; } - public void setLastHeartrate(int value,int bph,int bpl){ - lastHeartrate=value; - lastBPH=bph; - lastBPL=bpl; + public void setLastHeartrate(int value, int bph, int bpl) { + lastHeartrate = value; + lastBPH = bph; + lastBPL = bpl; } - public void setLastHeartrate(int value,int bph,int bpl,int sp02){ - lastHeartrate=value; - lastBPH=bph; - lastBPL=bpl; - lastSpo2=sp02; + public void setLastHeartrate(int value, int bph, int bpl, int sp02) { + lastHeartrate = value; + lastBPH = bph; + lastBPL = bpl; + lastSpo2 = sp02; } -//心率低阀值,低于该阀值上传心率,如果未设置,则留空 + //心率低阀值,低于该阀值上传心率,如果未设置,则留空 //心率高阀值,高于该阀值上传心率,如果未设置,则留空 //低压阀值,低压低于该阀值上传血压,如果未设置,则留空 //低压阀值,低压高于该阀值上传血压,如果未设置,则留空 //高压阀值,高压低于该阀值上传血压,如果未设置,则留空 //高压阀值,高压高于该阀值上传血压,如果未设置,则留空 - public void setWarningThreshold(int _ppg_threshold_max,int _ppg_threshold_min,int _bph_threshold_max,int _bph_threshold_min,int _bpl_threshold_max,int _bpl_threshold_min){ - ppg_threshold_max=_ppg_threshold_max; - ppg_threshold_min=_ppg_threshold_min; - bph_threshold_max=_bph_threshold_max; - bph_threshold_min=_bph_threshold_min; - bpl_threshold_max=_bpl_threshold_max; - bpl_threshold_min=_bpl_threshold_min; + public void setWarningThreshold(int _ppg_threshold_max, int _ppg_threshold_min, int _bph_threshold_max, int _bph_threshold_min, int _bpl_threshold_max, int _bpl_threshold_min) { + ppg_threshold_max = _ppg_threshold_max; + ppg_threshold_min = _ppg_threshold_min; + bph_threshold_max = _bph_threshold_max; + bph_threshold_min = _bph_threshold_min; + bpl_threshold_max = _bpl_threshold_max; + bpl_threshold_min = _bpl_threshold_min; } } diff --git a/app/src/main/java/com/enqualcomm/support/service/Deliver.java b/app/src/main/java/com/enqualcomm/support/service/Deliver.java index c082c5ff..26d56920 100644 --- a/app/src/main/java/com/enqualcomm/support/service/Deliver.java +++ b/app/src/main/java/com/enqualcomm/support/service/Deliver.java @@ -95,18 +95,13 @@ public class Deliver extends AbstractConnectionService { private static boolean wifiEnabled; public static Runnable delaySendMSG; - private static Handler mSendMSGHandler = new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - return false; - } - }); + private static Handler mSendMSGHandler = new Handler(message -> false); static { delaySendMSG = new Runnable() { @Override public void run() { - if (getAndSendMsgFromQueue() == true) { + if (getAndSendMsgFromQueue()) { mSendMSGHandler.postDelayed(delaySendMSG, 5000L); } } diff --git a/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java b/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java index 6168d7ec..62e1228f 100644 --- a/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java +++ b/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java @@ -43,428 +43,426 @@ import static com.enqualcomm.support.Constants.key_ppg; import static com.enqualcomm.support.Constants.key_spo2; public class HeartRateManager extends AbstractInvokeHandlerService implements SensorEventListener { - private int mNetworkType; + private static final String TAG = "HeartRateManager"; + private int mNetworkType; - private SimSignalUtil mSignalUtil; + private SimSignalUtil mSignalUtil; - private Runtime runtime; - private NettyConnection connection; + private Runtime runtime; + private NettyConnection connection; - private ScheduledThreadPoolExecutor timerPPG=null; - private static Handler mHandler=null; + private ScheduledThreadPoolExecutor timerPPG = null; + private static Handler mHandler = null; - private void checkWarning(){ - //ppg - if(runtime.getHRS().ppg_threshold_max>0 && runtime.getHRS().getPPG() >runtime.getHRS().ppg_threshold_max){ + private void checkWarning() { + //ppg + if (runtime.getHRS().ppg_threshold_max > 0 && runtime.getHRS().getPPG() > runtime.getHRS().ppg_threshold_max) { - runtime.setAlarmType(Runtime.AlarmType.ALARM_HEART_RATE_HIGH); - //trigger AP10 报警定位 - CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); + runtime.setAlarmType(Runtime.AlarmType.ALARM_HEART_RATE_HIGH); + //trigger AP10 报警定位 + CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); - }else if ( runtime.getHRS().ppg_threshold_min>0 && runtime.getHRS().getPPG() 0 && runtime.getHRS().getPPG() < runtime.getHRS().ppg_threshold_min) { + runtime.setAlarmType(Runtime.AlarmType.ALARM_HEART_RATE_LOW); + //trigger AP10 报警定位 + CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); + } + + //bph + if (runtime.getHRS().bph_threshold_max > 0 && runtime.getHRS().getBPH() > runtime.getHRS().bph_threshold_max) { + + runtime.setAlarmType(Runtime.AlarmType.ALARM_BPH_HIGH); + //trigger AP10 报警定位 + CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); + + } else if (runtime.getHRS().bph_threshold_min > 0 && runtime.getHRS().getBPH() < runtime.getHRS().bph_threshold_min) { + runtime.setAlarmType(Runtime.AlarmType.ALARM_BPH_LOW); + //trigger AP10 报警定位 + CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); - //bph - if(runtime.getHRS().bph_threshold_max>0 && runtime.getHRS().getBPH() >runtime.getHRS().bph_threshold_max){ + } + + //bpl + if (runtime.getHRS().bpl_threshold_max > 0 && runtime.getHRS().getBPL() > runtime.getHRS().bpl_threshold_max) { - runtime.setAlarmType(Runtime.AlarmType.ALARM_BPH_HIGH); - //trigger AP10 报警定位 - CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); + runtime.setAlarmType(Runtime.AlarmType.ALARM_BPL_HIGH); + //trigger AP10 报警定位 + CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); - }else if ( runtime.getHRS().bph_threshold_min>0 && runtime.getHRS().getBPH() 0 && runtime.getHRS().getBPL() < runtime.getHRS().bpl_threshold_min) { + runtime.setAlarmType(Runtime.AlarmType.ALARM_BPL_LOW); + //trigger AP10 报警定位 + CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); + } } - //bpl - if(runtime.getHRS().bpl_threshold_max>0 && runtime.getHRS().getBPL() >runtime.getHRS().bpl_threshold_max){ + public HeartRateManager(Runtime _runtime, NettyConnection _connection) { + runtime = _runtime; + connection = _connection; + currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_CLOSED; + isTimerStarted = false; + mSensorManager = (SensorManager) runtime.getContextProxy().context.getSystemService(SENSOR_SERVICE); + mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE); + + mHandler = new Handler(message -> { + + switch (message.what) { + case 100: { + ICLogger.log(TAG, "start send heart rate..."); + //只有检测PPG成功,且网络连接中才发送数据 + if (runtime.getHRS().getHeartrateWorkingStat() == + heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_TEST_SUCCESS) { + runtime.getHRS().setLastTestTime(TimeUtil.getSystemTime3()); + String PPGDATA = protocolAPIHelper.getPPG_ECG_MSG(runtime); + sendBroadcastPPGResult(); + //因为协议中没有时间变量,所以只能实时传输,如果恰巧没有网络也只能丢弃,有时间变量的话,可以考虑通过deliver的buffer来进行缓存发送 + if (connection.isServerConnected()) { + if (PPGDATA.isEmpty()) { + String ppgd = protocolAPIHelper.getPPG_MSG(runtime.getHRS().getPPG()); + String bloodd = protocolAPIHelper.getBlood_MSG(runtime.getHRS().getBPH(), runtime.getHRS().getBPL()); + String oxd = protocolAPIHelper.getOxygen_MSG(runtime.getHRS().getSpo2()); + connection.send(protocolAPIHelper.genStringMessage("ppg", ppgd)); + connection.send(protocolAPIHelper.genStringMessage("blood", bloodd)); + connection.send(protocolAPIHelper.genStringMessage("oxygen", oxd)); + checkWarning(); + } else { + connection.send(protocolAPIHelper.genStringMessage("APHT", PPGDATA)); + ICLogger.log(TAG, "Send PPG " + PPGDATA); + checkWarning(); + } + ICLogger.log(TAG, "Send PPG " + PPGDATA); + } else { + ICLogger.log(TAG, "Skip PPG " + PPGDATA); + } + } else { + ICLogger.log(TAG, "PPG Failed for Timeout!"); + } + stopPPG(); + } + break; + case 200: { + startPPG(); + } + break; + case 300: { + stopPPG(); + } + break; + } + return false; + }); - runtime.setAlarmType(Runtime.AlarmType.ALARM_BPL_HIGH); - //trigger AP10 报警定位 - CoreService.getInstance().getConnection().send(protocolAPIHelper.genStringMessage("AP10", protocolAPIHelper.getWarningMSG(runtime))); + } - }else if ( runtime.getHRS().bpl_threshold_min>0 && runtime.getHRS().getBPL() 0) { + Config.setPPGTestCycle(runtime.getContextProxy().context, ppgtestCycle); + runtime.setPpgTestCycle(Config.getPPGTestCycle(runtime.getContextProxy().context)); + ICLogger.i("get and set PPGTestCycle " + ppgtestCycle); + } + CoreService.getInstance().setHeartRateDetectAlarm(runtime.getPpgTestCycle()); + HeartRateManager.this.startPPG(); + } + + } + }; + + private void sendBroadcastPPGResult() { + Intent intent = new Intent(ACTION_BROADCAST_PPG); + intent.putExtra("ppg", runtime.getHRS().getPPG()); + intent.putExtra("bph", runtime.getHRS().getBPH()); + intent.putExtra("bpl", runtime.getHRS().getBPL()); + intent.putExtra("spo2", runtime.getHRS().getSpo2()); + intent.putExtra("time", runtime.getHRS().getTestTime()); + runtime.getContextProxy().context.sendBroadcast(intent); } - } - public HeartRateManager(Runtime _runtime,NettyConnection _connection){ - runtime=_runtime; - connection=_connection; - currentStat= heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_CLOSED; - isTimerStarted=false; - mSensorManager = (SensorManager) runtime.getContextProxy().context.getSystemService(SENSOR_SERVICE); - mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE); - - mHandler=new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - switch (message.what) { - case 100: { - //只有检测PPG成功,且网络连接中才发送数据 - if (runtime.getHRS().getHeartrateWorkingStat() == heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_TEST_SUCCESS) { - runtime.getHRS().setLastTestTime(TimeUtil.getSystemTime3()); - String PPGDATA = protocolAPIHelper.getPPG_ECG_MSG(runtime); - sendBroadcastPPGResult(); - //因为协议中没有时间变量,所以只能实时传输,如果恰巧没有网络也只能丢弃,有时间变量的话,可以考虑通过deliver的buffer来进行缓存发送 - if (connection.isServerConnected()) { - if(PPGDATA.isEmpty()){ - String ppgd=protocolAPIHelper.getPPG_MSG(runtime.getHRS().getPPG()); - String bloodd=protocolAPIHelper.getBlood_MSG( runtime.getHRS().getBPH(), runtime.getHRS().getBPL()); - String oxd=protocolAPIHelper.getOxygen_MSG(runtime.getHRS().getSpo2()); - connection.send(protocolAPIHelper.genStringMessage("ppg", ppgd)); - connection.send(protocolAPIHelper.genStringMessage("blood", bloodd)); - connection.send(protocolAPIHelper.genStringMessage("oxygen", oxd)); - - checkWarning(); - - }else { - connection.send(protocolAPIHelper.genStringMessage("APHT", PPGDATA)); - ICLogger.i("Send PPG " + PPGDATA); - checkWarning(); + public void regReceiver() { + //注册“网络变化”的广播接收器 + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(ACTION_HEATR_RATE_START); + runtime.getContextProxy().context.registerReceiver(PPGStartReceiver, intentFilter); + } + + public void unRegReceiver() { + runtime.getContextProxy().context.unregisterReceiver(PPGStartReceiver); + } + + private SensorManager mSensorManager; + private Sensor mHeartRate; + int PPG; + int BPH; + int BPL; + int SPo2; + boolean isWared; + boolean isPPGTesting; + static boolean isTimerStarted; + static heartRateStatus.HEARTRATE_WORKINGSTAT currentStat; + static int delayCount; + static int testCount; + static int notWaredCount; + private final int MAX_TESTTIMES = 30000;//最大延迟测试时间为30秒 + + + public void doPPGtest() { + int hrsType = ICJniUtils.isPPGavailable(); + if (hrsType > 0 && hrsType != ICJniUtils.PPG_EGC_SensorType.PPG_EGC_TYPE_IC66.ordinal()) { + PPG = ICJniUtils.getPPG();//调用底层函数保证状态更新。 + BPH = ICJniUtils.getHighBloodPressure(); + BPL = ICJniUtils.getLowBloodPressure(); + SPo2 = ICJniUtils.getSPO2(); + isWared = (ICJniUtils.isWeared() == 1); + isPPGTesting = (ICJniUtils.isPPGStarted() == 1); + } else { + isPPGTesting = true; + } + ICLogger.i("PPG TESTING=" + isPPGTesting + ", isWared=" + isWared + ", PPG=" + PPG + ", BPH=" + BPH + ", BPL=" + BPL + ", SPo2=" + SPo2); + if (isPPGTesting) { + if (isWared) { + if (PPG > 0) { + currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_TEST_SUCCESS; + } else { + currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_WARED_AND_TESTING; } - ICLogger.i("Send PPG " + PPGDATA); - } else { - ICLogger.i("Skip PPG " + PPGDATA); - } } else { - ICLogger.i("PPG Failed for Timeout!"); + currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_NOTWARED; } - stopPPG(); - } - break; - case 200: { - startPPG(); - } - break; - case 300: { - stopPPG(); - } - break; + } else { + currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_CLOSED; } - return false; - } - }); - - } - - private BroadcastReceiver PPGStartReceiver = new BroadcastReceiver() { - public void onReceive(Context param1Context, Intent param1Intent) { - if (ACTION_HEATR_RATE_START.equals(param1Intent.getAction())) { - - //此消息来源于BroadCaset,收到开始测试的消息。 - //此时需要重置HeartRateDetect Timer - //倘若有 参数 PPGTestCycle,则根据这个数值进行设置 - int ppgtestCycle=param1Intent.getIntExtra("PPGTestCycle",-1); - if (ppgtestCycle >0){ - Config.setPPGTestCycle(runtime.getContextProxy().context,ppgtestCycle); - runtime.setPpgTestCycle(Config.getPPGTestCycle(runtime.getContextProxy().context)); - ICLogger.i("get and set PPGTestCycle "+ppgtestCycle); + + + if (currentStat == heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_NOTWARED) { + notWaredCount--; + if (notWaredCount < 0) { //没有佩戴次数到限制后,停止检测 + ICLogger.i("HEARTRATE_NOTWARED 超过时限,取消检测报告!"); + stopPPG(); + } } - CoreService.getInstance().setHeartRateDetectAlarm(runtime.getPpgTestCycle()); - HeartRateManager.this.startPPG(); - } + if (currentStat == heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_TEST_SUCCESS) { + runtime.getHRS().setLastHeartrate(PPG, BPH, BPL, SPo2); + delayCount--; + if (delayCount < 0) //达到延迟时间后,停止检测并发送数据 + sendAndStopPPG(); - } - }; - - private void sendBroadcastPPGResult(){ - Intent intent=new Intent(ACTION_BROADCAST_PPG); - intent.putExtra("ppg",runtime.getHRS().getPPG()); - intent.putExtra("bph",runtime.getHRS().getBPH()); - intent.putExtra("bpl",runtime.getHRS().getBPL()); - intent.putExtra("spo2",runtime.getHRS().getSpo2()); - intent.putExtra("time",runtime.getHRS().getTestTime()); - runtime.getContextProxy().context.sendBroadcast(intent); - } - public void regReceiver(){ - //注册“网络变化”的广播接收器 - IntentFilter intentFilter = new IntentFilter(); - intentFilter.addAction(ACTION_HEATR_RATE_START); - runtime.getContextProxy().context.registerReceiver(PPGStartReceiver, intentFilter); - } - - public void unRegReceiver(){ - runtime.getContextProxy().context.unregisterReceiver(PPGStartReceiver); - } - private SensorManager mSensorManager; - private Sensor mHeartRate; - int PPG; - int BPH; - int BPL; - int SPo2; - boolean isWared ; - boolean isPPGTesting ; - static boolean isTimerStarted; - static heartRateStatus.HEARTRATE_WORKINGSTAT currentStat; - static int delayCount; - static int testCount; - static int notWaredCount; - private final int MAX_TESTTIMES=30000;//最大延迟测试时间为30秒 - - - public void doPPGtest(){ - - int hrsType=ICJniUtils.isPPGavailable(); - if (hrsType>0 && hrsType != ICJniUtils.PPG_EGC_SensorType.PPG_EGC_TYPE_IC66.ordinal()) { - PPG = ICJniUtils.getPPG();//调用底层函数保证状态更新。 - BPH = ICJniUtils.getHighBloodPressure(); - BPL = ICJniUtils.getLowBloodPressure(); - SPo2 = ICJniUtils.getSPO2(); - isWared = (ICJniUtils.isWeared() == 1); - isPPGTesting = (ICJniUtils.isPPGStarted() == 1); - }else{ - isPPGTesting=true; - } - ICLogger.i("PPG TESTING="+isPPGTesting+", isWared="+isWared+", PPG="+PPG+", BPH="+BPH+", BPL="+BPL+", SPo2="+SPo2); - if (isPPGTesting){ - if (isWared ) { - if (PPG > 0) { - currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_TEST_SUCCESS; } else { - currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_WARED_AND_TESTING; + runtime.getHRS().setLastHeartrate(0, 0, 0, 0); + } + runtime.getHRS().setHeartrateStat(currentStat); + + + testCount--; + if (testCount < 0) { + ICLogger.i("PPG 超过 " + MAX_TESTTIMES + "秒 未能得出结果,取消检测报告!"); + stopPPG(); } - }else{ - currentStat= heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_NOTWARED; - } - }else{ - currentStat= heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_CLOSED; - } + } - if (currentStat== heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_NOTWARED){ - notWaredCount--; - if( notWaredCount <0){ //没有佩戴次数到限制后,停止检测 - ICLogger.i("HEARTRATE_NOTWARED 超过时限,取消检测报告!"); - stopPPG(); - } + private void sendAndStopPPG() { + //结束和发送数据 + mHandler.sendEmptyMessage(100); } - if (currentStat==heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_TEST_SUCCESS){ - runtime.getHRS().setLastHeartrate(PPG,BPH,BPL,SPo2); - delayCount--; - if (delayCount<0) //达到延迟时间后,停止检测并发送数据 - sendAndStopPPG(); + PowerManager.WakeLock mWakeLock = null; - }else{ - runtime.getHRS().setLastHeartrate(0,0,0,0); + public PowerManager.WakeLock getPPGWakeLock() { + mWakeLock = ((PowerManager) (runtime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, HeartRateManager.class.getSimpleName()); + mWakeLock.acquire(30000L); + return mWakeLock; } - runtime.getHRS().setHeartrateStat(currentStat); + public void releaseWakeLock() { + if (mWakeLock != null && mWakeLock.isHeld()) { + mWakeLock.release(); + } + mWakeLock = null; + } + public void startPPG() { + int hrsType = ICJniUtils.isPPGavailable(); + if (hrsType > 0 && (isTimerStarted == false)) { + currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_OPEN; + delayCount = 4;//检测成功后4秒发送数据 + notWaredCount = 5; //初始化没有佩戴的检测次数5,连续5秒没有佩戴则取消检测 + testCount = MAX_TESTTIMES;//测试MAX_TESTTIMES后没有结果也要强制退出 + isTimerStarted = true; + getPPGWakeLock(); + if (hrsType == ICJniUtils.PPG_EGC_SensorType.PPG_EGC_TYPE_IC66.ordinal()) { - testCount--; - if (testCount<0) - { - ICLogger.i("PPG 超过 "+MAX_TESTTIMES+"秒 未能得出结果,取消检测报告!"); - stopPPG(); - } + boolean ret = mSensorManager.registerListener(this, mHeartRate, SensorManager.SENSOR_DELAY_UI); + ICLogger.i("Heart Rate PPG_EGC_TYPE_IC66 opened ret :: " + ret); - } - - private void sendAndStopPPG(){ - //结束和发送数据 - mHandler.sendEmptyMessage(100); - } - PowerManager.WakeLock mWakeLock=null; - public PowerManager.WakeLock getPPGWakeLock() { - mWakeLock = ((PowerManager)(runtime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, HeartRateManager.class.getSimpleName()); - mWakeLock.acquire(30000L); - return mWakeLock; - } - - public void releaseWakeLock(){ - if (mWakeLock!=null && mWakeLock.isHeld()){ - mWakeLock.release(); - } - mWakeLock=null; - } - public void startPPG(){ - - int hrsType=ICJniUtils.isPPGavailable(); - if ( hrsType > 0 && (isTimerStarted == false) ) { - currentStat = heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_OPEN; - delayCount = 4;//检测成功后4秒发送数据 - notWaredCount = 5; //初始化没有佩戴的检测次数5,连续5秒没有佩戴则取消检测 - testCount = MAX_TESTTIMES;//测试MAX_TESTTIMES后没有结果也要强制退出 - isTimerStarted = true; - getPPGWakeLock(); - if (hrsType == ICJniUtils.PPG_EGC_SensorType.PPG_EGC_TYPE_IC66.ordinal()) { - - boolean ret = mSensorManager.registerListener(this, mHeartRate, SensorManager.SENSOR_DELAY_UI); - ICLogger.i( "Heart Rate PPG_EGC_TYPE_IC66 opened ret :: " + ret); - - } else { - - ICJniUtils.enablePPG(); - timerPPG = new ScheduledThreadPoolExecutor(10); - timerPPG.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - doPPGtest(); - } - }, 0, 1000, TimeUnit.MILLISECONDS); //1 秒更新一次数据 - - } - } - } - - public void stopPPG(){ - if( isTimerStarted ) - { - - int hrsType=ICJniUtils.isPPGavailable(); - if (hrsType == ICJniUtils.PPG_EGC_SensorType.PPG_EGC_TYPE_IC66.ordinal()) { - mSensorManager.unregisterListener(this); - ICLogger.i( "Heart Rate PPG_EGC_TYPE_IC66 closed"); - }else { - timerPPG.shutdownNow(); - timerPPG.purge(); - ICJniUtils.disablePPG(); - } - isTimerStarted=false; + } else { + + ICJniUtils.enablePPG(); + timerPPG = new ScheduledThreadPoolExecutor(10); + timerPPG.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + doPPGtest(); + } + }, 0, 1000, TimeUnit.MILLISECONDS); //1 秒更新一次数据 + + } + } } - releaseWakeLock(); - } + public void stopPPG() { + if (isTimerStarted) { - private void callback(Messenger paramMessenger, int paramInt) { - if (paramMessenger != null) - try { - paramMessenger.send(Message.obtain(null, paramInt)); - return; - } catch (Exception e) { - e.printStackTrace(); - } - } + int hrsType = ICJniUtils.isPPGavailable(); + if (hrsType == ICJniUtils.PPG_EGC_SensorType.PPG_EGC_TYPE_IC66.ordinal()) { + mSensorManager.unregisterListener(this); + ICLogger.i("Heart Rate PPG_EGC_TYPE_IC66 closed"); + } else { + timerPPG.shutdownNow(); + timerPPG.purge(); + ICJniUtils.disablePPG(); + } + isTimerStarted = false; + } + releaseWakeLock(); + } + + private void callback(Messenger paramMessenger, int paramInt) { + if (paramMessenger != null) + try { + paramMessenger.send(Message.obtain(null, paramInt)); + return; + } catch (Exception e) { + e.printStackTrace(); + } + } - public void onAlarmClock(Connection paramConnection, Runtime paramRuntime) {} + public void onAlarmClock(Connection paramConnection, Runtime paramRuntime) { + } - public void onAttach(Connection paramConnection, Runtime paramRuntime) { + public void onAttach(Connection paramConnection, Runtime paramRuntime) { // this.mSignalUtil = SimSignalUtil.getInstance((paramRuntime.getContextProxy()).context); - regReceiver(); - } + regReceiver(); + } - public void onDetach(Connection paramConnection, Runtime paramRuntime) { - unRegReceiver(); - } + public void onDetach(Connection paramConnection, Runtime paramRuntime) { + unRegReceiver(); + } - public boolean onUserRequest(Intent paramIntent, Connection paramConnection, final Runtime runtime) { - String str = paramIntent.getAction(); - if (ACTION_HEATR_RATE_START.equals(str)) { + public boolean onUserRequest(Intent paramIntent, Connection paramConnection, final Runtime runtime) { + String str = paramIntent.getAction(); + if (ACTION_HEATR_RATE_START.equals(str)) { // this.mSignalUtil = SimSignalUtil.getInstance((runtime.getContextProxy()).context); // str = paramIntent.getStringExtra("filepath"); // String str1 = paramIntent.getStringExtra("number"); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("PPG Started on Action "+ACTION_HEATR_RATE_START); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("PPG Started on Action " + ACTION_HEATR_RATE_START); // stringBuilder.append(str); // stringBuilder.append("number == "); // stringBuilder.append(str1); - ICLogger.i(stringBuilder.toString()); - //do something - startPPG(); + ICLogger.i(stringBuilder.toString()); + //do something + startPPG(); + } + return false; } - return false; - } -public static void triggerPPGtest(){ - if (mHandler !=null) mHandler.sendEmptyMessage(200); -} + public static void triggerPPGtest() { + if (mHandler != null) mHandler.sendEmptyMessage(200); + } + public boolean onUserRequest(Message message, Connection connection, final Runtime runtime) { - public boolean onUserRequest(Message message, Connection connection, final Runtime runtime) { + int i = 1; + switch (message.what) { + case MSG_WHAT_PPG: - int i = 1; - switch (message.what) { - case MSG_WHAT_PPG: + //接收UI测试后的结果,直接发送到服务器。 + Bundle bundle3 = message.getData(); + String ppg = bundle3.getString(key_ppg); + String bph = bundle3.getString(key_bph); + String bpl = bundle3.getString(key_bpl); + String spo2 = bundle3.getString(key_spo2); - //接收UI测试后的结果,直接发送到服务器。 - Bundle bundle3 = message.getData(); - String ppg = bundle3.getString(key_ppg); - String bph = bundle3.getString(key_bph); - String bpl = bundle3.getString(key_bpl); - String spo2 = bundle3.getString(key_spo2); + ICLogger.i("get MSG_WHAT_PPG ppg " + ppg + " , bph " + bph + " , bpl " + bpl + " , spo2 " + spo2); + if (ppg == null || bph == null || bpl == null || ppg.isEmpty() || bph.isEmpty() || bpl.isEmpty()) { + ICLogger.i("MSG_WHAT_PPG Data is null or empty ! Skip!"); + callback(message.replyTo, Constants.RESULT_ERROR); - ICLogger.i("get MSG_WHAT_PPG ppg "+ppg + " , bph "+bph + " , bpl "+bpl + " , spo2 "+spo2); - if (ppg == null || bph == null || bpl==null ||ppg.isEmpty()||bph.isEmpty()||bpl.isEmpty()) { - ICLogger.i("MSG_WHAT_PPG Data is null or empty ! Skip!"); - callback(message.replyTo, Constants.RESULT_ERROR); + return true; + } + if (spo2 == null || (spo2 != null && Integer.parseInt(spo2) <= 0)) { + Random r = new Random(); + int randomint = r.nextInt(98 - 95) + 95; + spo2 = String.valueOf(randomint); + } + + + if (((NettyConnection) connection).isServerConnected()) { + String PPGDATA = protocolAPIHelper.getPPG_ECG_MSG(Integer.parseInt(ppg), Integer.parseInt(bph), Integer.parseInt(bpl), Integer.parseInt(spo2)); + if (PPGDATA.isEmpty()) { + String ppgd = protocolAPIHelper.getPPG_MSG(Integer.parseInt(ppg)); + String bloodd = protocolAPIHelper.getBlood_MSG(Integer.parseInt(bph), Integer.parseInt(bpl)); + String oxd = protocolAPIHelper.getOxygen_MSG(Integer.parseInt(spo2)); + connection.send(protocolAPIHelper.genStringMessage("ppg", ppgd)); + connection.send(protocolAPIHelper.genStringMessage("blood", bloodd)); + connection.send(protocolAPIHelper.genStringMessage("oxygen", oxd)); + + } else { + connection.send(protocolAPIHelper.genStringMessage("APHT", PPGDATA)); + ICLogger.i("Send PPG " + PPGDATA); + } + } else { + ICLogger.i("Skip PPG "); + } + + callback(message.replyTo, Constants.RESULT_OK); - return true; + default: + break; } - if (spo2==null || (spo2!=null && Integer.parseInt(spo2 )<=0) ){ - Random r = new Random(); - int randomint = r.nextInt(98 - 95) + 95; - spo2=String.valueOf(randomint); - } - - - if (((NettyConnection) connection).isServerConnected()) { - String PPGDATA = protocolAPIHelper.getPPG_ECG_MSG(Integer.parseInt(ppg), Integer.parseInt(bph), Integer.parseInt(bpl), Integer.parseInt(spo2)); - if(PPGDATA.isEmpty()){ - String ppgd=protocolAPIHelper.getPPG_MSG(Integer.parseInt(ppg)); - String bloodd=protocolAPIHelper.getBlood_MSG( Integer.parseInt(bph), Integer.parseInt(bpl)); - String oxd=protocolAPIHelper.getOxygen_MSG(Integer.parseInt(spo2)); - connection.send(protocolAPIHelper.genStringMessage("ppg", ppgd)); - connection.send(protocolAPIHelper.genStringMessage("blood", bloodd)); - connection.send(protocolAPIHelper.genStringMessage("oxygen", oxd)); - - }else { - connection.send(protocolAPIHelper.genStringMessage("APHT", PPGDATA)); - ICLogger.i("Send PPG " + PPGDATA); - } - } else { - ICLogger.i("Skip PPG "); - } - callback(message.replyTo, Constants.RESULT_OK); + return true; + } - default: - break; + @Override + public void onSensorChanged(SensorEvent sensorEvent) { + float values[] = sensorEvent.values; + int length = values.length; + ICLogger.i("onSensorChanged() is called " + length + + " PPG = " + values[0] + + ", BPH = " + values[1] + + ", BPL = " + values[2] + + ", spo2 = " + values[3] + + " , Weared = " + values[4] + ); + PPG = (int) values[0];//调用底层函数保证状态更新。 + BPH = (int) values[1]; + BPL = (int) values[2]; + SPo2 = (int) values[3]; + isWared = ((int) values[4] == 2); + isPPGTesting = true;// (ICJniUtils.isPPGStarted() == 1); + doPPGtest(); + /*[0]---心率;[1]---血压高压;[2]---血压低压;[3]---血氧;[4]---佩戴检测(1--脱手,2--上手);*/ } - return true; - } - - @Override - public void onSensorChanged(SensorEvent sensorEvent) { - float values[]=sensorEvent.values; - int length = values.length; - ICLogger.i( "onSensorChanged() is called "+length - +" PPG = "+values[0] - +", BPH = "+values[1] - +", BPL = "+values[2] - +", spo2 = "+values[3] - +" , Weared = "+values[4] - ); - PPG = (int)values[0];//调用底层函数保证状态更新。 - BPH = (int)values[1]; - BPL = (int)values[2]; - SPo2 = (int)values[3]; - isWared = ((int)values[4] == 2); - isPPGTesting = true;// (ICJniUtils.isPPGStarted() == 1); - doPPGtest(); - /*[0]---心率;[1]---血压高压;[2]---血压低压;[3]---血氧;[4]---佩戴检测(1--脱手,2--上手);*/ - } - - @Override - public void onAccuracyChanged(Sensor sensor, int i) { - ICLogger.i("onAccuracyChanged() is called "+sensor.getName()+" accuracy="+i); - } + @Override + public void onAccuracyChanged(Sensor sensor, int i) { + ICLogger.i("onAccuracyChanged() is called " + sensor.getName() + " accuracy=" + i); + } } diff --git a/app/src/main/java/com/enqualcomm/support/service/base/AbstractInvokeHandlerService.java b/app/src/main/java/com/enqualcomm/support/service/base/AbstractInvokeHandlerService.java index 0b2b8a4c..d11d3f28 100644 --- a/app/src/main/java/com/enqualcomm/support/service/base/AbstractInvokeHandlerService.java +++ b/app/src/main/java/com/enqualcomm/support/service/base/AbstractInvokeHandlerService.java @@ -31,7 +31,7 @@ public abstract class AbstractInvokeHandlerService implements InvokeHandlerServi if (!onUserRequest(paramIntent, paramConnection, paramRuntime) && this.nextService != null) this.nextService.processUserRequest(paramIntent, paramConnection, paramRuntime); } - + public final void processUserRequest(Message paramMessage, Connection paramConnection, Runtime paramRuntime) { if (!onUserRequest(paramMessage, paramConnection, paramRuntime) && this.nextService != null) this.nextService.processUserRequest(paramMessage, paramConnection, paramRuntime); diff --git a/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java b/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java index 564a43e3..79ce6b14 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java +++ b/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java @@ -24,166 +24,167 @@ import static com.enqualcomm.support.utils.RxSocket.SocketStatus.CONNECTED; import com.enqualcomm.support.bean.Runtime; public class NettyConnection implements Connection { - private static long realtime_old; - private static final String TAG = NettyConnection.class.getSimpleName(); - - ExecutorService executorService = Executors.newSingleThreadExecutor(); - - private protocolAPIHelper API=null; - private ConnectionListener listener=null; - - private int timeout = 60; - - public NettyConnection(ConnectionListener paramConnectionListener,Runtime runtime) { - this.listener = paramConnectionListener; - - if (API == null) API=new protocolAPIHelper(NettyConnection.this,runtime ); - - initReadListener(); - init_connection_listener(); - } - - private void connectImpl(String host, int port) { - connectServer(host,port); - } - - public void close() { + private static long realtime_old; + private static final String TAG = NettyConnection.class.getSimpleName(); + + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + private protocolAPIHelper API = null; + private ConnectionListener listener = null; + + private int timeout = 60; + + public NettyConnection(ConnectionListener paramConnectionListener, Runtime runtime) { + this.listener = paramConnectionListener; + + if (API == null) API = new protocolAPIHelper(NettyConnection.this, runtime); + + initReadListener(); + init_connection_listener(); + } + + private void connectImpl(String host, int port) { + connectServer(host, port); + } + + public void close() { // listener =null; // RxSocket.getInstance().setConnectionListener(null); - this.disconnect(); - } - - public void connect(final String host, final int port) { - long l = SystemClock.elapsedRealtime(); - if (host.isEmpty()||host ==null){ - ICLogger.i("host name error "+host); - return ; - } - if (l - realtime_old < 3000L ) { - ICLogger.i("3秒内skip 重连!"); - return; + this.disconnect(); } - realtime_old = l; - ICLogger.i("connect1 "+host+":"+port); + + public void connect(final String host, final int port) { + long l = SystemClock.elapsedRealtime(); + if (host.isEmpty() || host == null) { + ICLogger.i("host name error " + host); + return; + } + if (l - realtime_old < 3000L) { + ICLogger.i("3秒内skip 重连!"); + return; + } + realtime_old = l; + ICLogger.i("connect1 " + host + ":" + port); // disconnect(); - this.executorService.execute(new Runnable() { - public void run() { - NettyConnection.this.connectImpl(host, port); - ICLogger.i("connect2"); - } + this.executorService.execute(new Runnable() { + public void run() { + NettyConnection.this.connectImpl(host, port); + ICLogger.i("connect2"); + } }); - } - - public void disconnect() { - - disconnectServer(); - } - + } - private boolean connectServer(String serverip,int serverport){ + public void disconnect() { - //进行连接Socket:这里使用的是,在本地上开启了一个服务器。 + disconnectServer(); + } - RxSocket.getInstance().connectRx(serverip==null?"118.178.155.223":serverip,serverport) - .subscribe( - aBoolean -> { - log("RxSocket Connect "+aBoolean); - }, - throwable -> { - log("RxSocket Connect Error : "+throwable.getMessage()); - }, - () -> { - log("RxSocket Connect main"); - } - ); - - - return true; - } - - public boolean disconnectServer(){ - - log("Call disconnectServer"); - //断开连接 - RxSocket.getInstance().disConnect() - .subscribe( - aBoolean -> { - log("RxSocket DisConnect "+aBoolean); - }, - throwable -> { - log("RxSocket DisConnect Error : "+throwable.getMessage()); - }, - () -> { - log("RxSocket DisConnect main"); - } - ); + private boolean connectServer(String serverip, int serverport) { - return true; - } - private void log(String msg) { - ICLogger.log(TAG,msg); - } + //进行连接Socket:这里使用的是,在本地上开启了一个服务器。 + RxSocket.getInstance().connectRx(serverip == null ? "118.178.155.223" : serverip, serverport) + .subscribe( + aBoolean -> { + log("RxSocket Connect " + aBoolean); + }, + throwable -> { + log("RxSocket Connect Error : " + throwable.getMessage()); + }, + () -> { + log("RxSocket Connect main"); - public boolean isServerConnected(){ - return (RxSocket.getInstance().getSocketStatus()== CONNECTED)?true:false; - } + } + ); - public boolean sendMsg(String cmd) { - if( cmd==null || cmd.isEmpty()) - { - return false; + return true; } + public boolean disconnectServer() { - if (!isServerConnected()){ - - log("skiped"+cmd); - if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," skiped " + cmd); - return false; - }else{ - log("send "+cmd); - if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," sent " + cmd); - //向RxSocket写数据 - //示例数据:IWAP00867155030001063# - byte[] test = cmd.getBytes(); - ByteBuffer byteBuffer = ByteBuffer.wrap(test); - RxSocket.getInstance().write(byteBuffer) + log("Call disconnectServer"); + //断开连接 + RxSocket.getInstance().disConnect() .subscribe( aBoolean -> { - log("RxSocket write " + aBoolean); + log("RxSocket DisConnect " + aBoolean); }, throwable -> { - log("RxSocket write Error : " + throwable.getMessage()); + log("RxSocket DisConnect Error : " + throwable.getMessage()); }, () -> { - log("RxSocket write main "); + log("RxSocket DisConnect main"); } ); + return true; + } + + private void log(String msg) { + ICLogger.log(TAG, msg); + } + + public boolean isServerConnected() { + return (RxSocket.getInstance().getSocketStatus() == CONNECTED) ? true : false; } - return true; - } - public boolean sendMsg(byte[] cmdArray) { + public boolean sendMsg(String cmd) { - if( cmdArray==null || cmdArray.length==0) - { + if (cmd == null || cmd.isEmpty()) { return false; } - if (!isServerConnected()){ + if (!isServerConnected()) { - log("skipedBytes "+new String(cmdArray)); - if (Config.LOG_TOFILE)ICLogger.logToFile("APILog"," skiped " + new String(cmdArray)); + log("skiped" + cmd); + if (Config.LOG_TOFILE) ICLogger.logToFile("APILog", " skiped " + cmd); return false; - }else{ - log("sendBytes "+new String(cmdArray)); - if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," sentBytes " + new String(cmdArray)); + } else { + log("send " + cmd); + if (Config.LOG_TOFILE) ICLogger.logToFile("APILog", " sent " + cmd); + //向RxSocket写数据 + //示例数据:IWAP00867155030001063# + byte[] test = cmd.getBytes(); + ByteBuffer byteBuffer = ByteBuffer.wrap(test); + RxSocket.getInstance().write(byteBuffer) + .subscribe( + aBoolean -> { + log("RxSocket write " + aBoolean); + }, + throwable -> { + log("RxSocket write Error : " + throwable.getMessage()); + }, + () -> { + log("RxSocket write main "); + } + ); + + + } + + return true; + } + + public boolean sendMsg(byte[] cmdArray) { + + if (cmdArray == null || cmdArray.length == 0) { + return false; + } + + + if (!isServerConnected()) { + + log("skipedBytes " + new String(cmdArray)); + if (Config.LOG_TOFILE) ICLogger.logToFile("APILog", " skiped " + new String(cmdArray)); + return false; + } else { + log("sendBytes " + new String(cmdArray)); + if (Config.LOG_TOFILE) + ICLogger.logToFile("APILog", " sentBytes " + new String(cmdArray)); //向RxSocket写数据 //示例数据:IWAP00867155030001063# ByteBuffer byteBuffer = ByteBuffer.wrap(cmdArray); @@ -205,20 +206,23 @@ public class NettyConnection implements Connection { return true; } - public int getTimeout() { return this.timeout; } + public int getTimeout() { + return this.timeout; + } - public void DeliverCMDMessageToSystem(String cmd,String msg){ - if (NettyConnection.this.listener!=null){ - String[] msgArr=new String[]{cmd,msg}; - StringMessage stringMessage=new StringMessage(msgArr); - stringMessage.refresh(msg); - NettyConnection.this.listener.onReceive(stringMessage ); - } - } - private void initReadListener(){ - //监听Socket的收包 + public void DeliverCMDMessageToSystem(String cmd, String msg) { + if (NettyConnection.this.listener != null) { + String[] msgArr = new String[]{cmd, msg}; + StringMessage stringMessage = new StringMessage(msgArr); + stringMessage.refresh(msg); + NettyConnection.this.listener.onReceive(stringMessage); + } + } + + private void initReadListener() { + //监听Socket的收包 // RxSocket.getInstance().read() // .subscribeOn(Schedulers.newThread()) // .observeOn(AndroidSchedulers.mainThread()) @@ -240,78 +244,81 @@ public class NettyConnection implements Connection { // log("get Msg ()"); // } // ); - RxSocket.getInstance().setSocketReadCallback(new RxSocket.SocketReadCallback() { - @Override - public void onRecvMsg(byte[] bytes) { - - Message msg=new Message(); - Bundle bdl=new Bundle(); - bdl.putByteArray("RecvData",bytes); - msg.what=100; - msg.setData(bdl); - mHandler.sendMessage(msg); - } - }); - - - } - - private Handler mHandler=new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - - if (message.what == 100){ - byte[] bytes=message.getData().getByteArray("RecvData"); - String msg= new String(bytes); - - log("get Msg :"+msg+" (size) byteslen" + bytes.length +" strlen"+ msg.length()); - API.parserCmd(bytes); - - } - return false; - } - }); - - private void init_connection_listener(){ - - //监听Socket的连接状态 - RxSocket.getInstance().socketStatusListener() - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(socketStatus -> { - log("socketStatusListener socketStatus:" + socketStatus.name()); - if (socketStatus.name().equals("CONNECTED")){ - if (NettyConnection.this.listener!=null){ - NettyConnection.this.listener.onConnectionOpen(); - } - }else if (socketStatus.name().equals("DIS_CONNECT") || socketStatus.name().equals("DIS_CONNECT_BY_SERVERSIDE")) { - if (NettyConnection.this.listener!=null){ - NettyConnection.this.listener.onConnectionClose(socketStatus.name()); - } - disconnectServer(); - } - }); - } - public void open() { - - - } - - public void send(StringMessage paramStringMessage) { - - sendMsg(paramStringMessage.isFromCache()); - ICLogger.logToFile("APILog",paramStringMessage.isFromCache()); - ICLogger.i(paramStringMessage.isFromCache()); - - } - - public boolean sendBlocking(StringMessage paramStringMessage) { - ICLogger.i(paramStringMessage.isFromCache()); - sendMsg(paramStringMessage.isFromCache()); - return true; + RxSocket.getInstance().setSocketReadCallback(new RxSocket.SocketReadCallback() { + @Override + public void onRecvMsg(byte[] bytes) { + + Message msg = new Message(); + Bundle bdl = new Bundle(); + bdl.putByteArray("RecvData", bytes); + msg.what = 100; + msg.setData(bdl); + mHandler.sendMessage(msg); + } + }); + + + } + + private Handler mHandler = new Handler(new Handler.Callback() { + @Override + public boolean handleMessage(Message message) { + + if (message.what == 100) { + byte[] bytes = message.getData().getByteArray("RecvData"); + String msg = new String(bytes); + + log("get Msg :" + msg + " (size) byteslen" + bytes.length + " strlen" + msg.length()); + API.parserCmd(bytes); + + } + return false; + } + }); + + private void init_connection_listener() { + + //监听Socket的连接状态 + RxSocket.getInstance().socketStatusListener() + .subscribeOn(Schedulers.newThread()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(socketStatus -> { + log("socketStatusListener socketStatus:" + socketStatus.name()); + if (socketStatus.name().equals("CONNECTED")) { + if (NettyConnection.this.listener != null) { + NettyConnection.this.listener.onConnectionOpen(); + } + } else if (socketStatus.name().equals("DIS_CONNECT") || socketStatus.name().equals("DIS_CONNECT_BY_SERVERSIDE")) { + if (NettyConnection.this.listener != null) { + NettyConnection.this.listener.onConnectionClose(socketStatus.name()); + } + disconnectServer(); + } + }); + } + + public void open() { + + + } + + public void send(StringMessage paramStringMessage) { + + sendMsg(paramStringMessage.isFromCache()); + ICLogger.logToFile("APILog", paramStringMessage.isFromCache()); + ICLogger.i(paramStringMessage.isFromCache()); + + } + + public boolean sendBlocking(StringMessage paramStringMessage) { + ICLogger.i(paramStringMessage.isFromCache()); + sendMsg(paramStringMessage.isFromCache()); + return true; + } + + public void setTimeout(int paramInt) { + this.timeout = paramInt; } - - public void setTimeout(int paramInt) { this.timeout = paramInt; } } diff --git a/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java b/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java index fe6a39b9..9fc3ac6c 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java +++ b/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java @@ -67,372 +67,373 @@ import static com.enqualcomm.support.Constants.RESUME_ACTION; import static com.enqualcomm.support.bean.Content.CONTACT_CATEGORY_GROUP; - public class ProcessReceiver extends BroadcastReceiver { - private static final int MICRO_CHAT = 2; - - private static int last_app_id; - - private static String last_message_name; - - private static CustomDialog mCustomDialog; - - private CustomNotification mCustomNotification; - - private CustomDialog.Builder mDialog; - - private CustomNotification.Builder mNotificationDialog; - - private NotificationManager mNotificationManager; - - private Vibrator vibrator; - - private float x1 = 0.0F; - - private float x2 = 0.0F; - - private float y1 = 0.0F; - - private float y2 = 0.0F; - - private void initMyDialog(final Context context, final Contact contact, int app_id,String msg) { - String var4 = contact==null?"SMS":contact.name; - - if (this.mDialog == null) { - this.mDialog = new CustomDialog.Builder(context); - } + private static final int MICRO_CHAT = 2; - StringBuilder var5 = new StringBuilder(); - var5.append("===mCustomDialog ") - .append(mCustomDialog) - .append(" , appid ").append(app_id); + private static int last_app_id; - ICLogger.i(var5.toString()); - if (mCustomDialog != null && mCustomDialog.isShowing() && last_message_name != null && var4 != null && last_message_name.equals(var4) && last_app_id == app_id) { - mCustomDialog.dismiss(); - } + private static String last_message_name; - last_message_name = var4; - last_app_id = app_id; - CustomDialog.Builder tmpDialog; - if (app_id == 1) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.setting_title)).setApp(1); - StringBuilder var6 = new StringBuilder(); - var6.append(context.getString(R.string.voiceMessage)); - var6.append(" "); - var6.append(var4); - var6.append(context.getString(R.string.voiceMessageEnd)); - mCustomDialog = tmpDialog.setMessage(var6.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1x, int var2x) { - var1x.dismiss(); - ComponentName var3 = new ComponentName("com.enqualcomm.imessage", "com.enqualcomm.imessage.ui.chat.ChatActivity_"); - Intent var5 = new Intent("android.intent.action.MAIN"); - var5.putExtra("ACTIVITY_TYPE", 2); - var5.putExtra("contact", contact); - var5.addCategory("android.intent.category.DEFAULT"); - var5.addFlags(FLAG_ACTIVITY_NEW_TASK); - var5.setComponent(var3); - VibrateUtil.getInstance(context).VibrateOn(false); - try { - context.startActivity(var5); - } catch (Exception var4) { - var4.printStackTrace(); - } + private static CustomDialog mCustomDialog; + private CustomNotification mCustomNotification; + + private CustomDialog.Builder mDialog; + + private CustomNotification.Builder mNotificationDialog; + + private NotificationManager mNotificationManager; + + private Vibrator vibrator; + + private float x1 = 0.0F; + + private float x2 = 0.0F; + + private float y1 = 0.0F; + + private float y2 = 0.0F; + + private void initMyDialog(final Context context, final Contact contact, int app_id, String msg) { + String var4 = contact == null ? "SMS" : contact.name; + + if (this.mDialog == null) { + this.mDialog = new CustomDialog.Builder(context); } - }).setNegativeButton("取消", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - } else if (app_id == 2) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.hht_misscall_call)).setApp(app_id); - StringBuilder var7 = new StringBuilder(); - var7.append(context.getString(R.string.hht_call_start)); - var7.append(var4); - var7.append(context.getString(R.string.hht_call_end)); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - }else if (app_id ==3){ - tmpDialog = this.mDialog.setTitle(context.getString(R.string.sms_title)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(context.getString(R.string.sms_notify)); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - ComponentName var3 = new ComponentName("com.zmapp.sms", "com.zmapp.sms.MainActivity"); - Intent var5 = new Intent("android.intent.action.MAIN"); - var5.addCategory("android.intent.category.DEFAULT"); - var5.addFlags(FLAG_ACTIVITY_NEW_TASK); - var5.setComponent(var3); - VibrateUtil.getInstance(context).VibrateOn(false); - try { - context.startActivity(var5); - } catch (Exception var4) { - var4.printStackTrace(); - } - } - }).setNegativeButton("取消", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); + + StringBuilder var5 = new StringBuilder(); + var5.append("===mCustomDialog ") + .append(mCustomDialog) + .append(" , appid ").append(app_id); + + ICLogger.i(var5.toString()); + if (mCustomDialog != null && mCustomDialog.isShowing() && last_message_name != null && var4 != null && last_message_name.equals(var4) && last_app_id == app_id) { + mCustomDialog.dismiss(); } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - }else if (app_id ==4) { - tmpDialog = this.mDialog.setTitle("WEB"+context.getString(R.string.sms_title)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(msg); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - if(CoreService.getInstance()!=null) { - CoreService.getInstance().getConnection().send(protocolAPIHelper.getPushTxtReadFlagToSrvMSG()); - } + + last_message_name = var4; + last_app_id = app_id; + CustomDialog.Builder tmpDialog; + if (app_id == 1) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.setting_title)).setApp(1); + StringBuilder var6 = new StringBuilder(); + var6.append(context.getString(R.string.voiceMessage)); + var6.append(" "); + var6.append(var4); + var6.append(context.getString(R.string.voiceMessageEnd)); + mCustomDialog = tmpDialog.setMessage(var6.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1x, int var2x) { + var1x.dismiss(); + ComponentName var3 = new ComponentName("com.enqualcomm.imessage", "com.enqualcomm.imessage.ui.chat.ChatActivity_"); + Intent var5 = new Intent("android.intent.action.MAIN"); + var5.putExtra("ACTIVITY_TYPE", 2); + var5.putExtra("contact", contact); + var5.addCategory("android.intent.category.DEFAULT"); + var5.addFlags(FLAG_ACTIVITY_NEW_TASK); + var5.setComponent(var3); + VibrateUtil.getInstance(context).VibrateOn(false); + try { + context.startActivity(var5); + } catch (Exception var4) { + var4.printStackTrace(); + } + + } + }).setNegativeButton("取消", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } else if (app_id == 2) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.hht_misscall_call)).setApp(app_id); + StringBuilder var7 = new StringBuilder(); + var7.append(context.getString(R.string.hht_call_start)); + var7.append(var4); + var7.append(context.getString(R.string.hht_call_end)); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } else if (app_id == 3) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.sms_title)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(context.getString(R.string.sms_notify)); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + ComponentName var3 = new ComponentName("com.zmapp.sms", "com.zmapp.sms.MainActivity"); + Intent var5 = new Intent("android.intent.action.MAIN"); + var5.addCategory("android.intent.category.DEFAULT"); + var5.addFlags(FLAG_ACTIVITY_NEW_TASK); + var5.setComponent(var3); + VibrateUtil.getInstance(context).VibrateOn(false); + try { + context.startActivity(var5); + } catch (Exception var4) { + var4.printStackTrace(); + } + } + }).setNegativeButton("取消", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } else if (app_id == 4) { + tmpDialog = this.mDialog.setTitle("WEB" + context.getString(R.string.sms_title)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(msg); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + if (CoreService.getInstance() != null) { + CoreService.getInstance().getConnection().send(protocolAPIHelper.getPushTxtReadFlagToSrvMSG()); + } + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } else if (app_id == 5) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.findDev)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(msg); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + stopmediaplayer(); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - } else if (app_id ==5) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.findDev)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(msg); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - stopmediaplayer(); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); } - } - private void playFindDevVoice(Context context){ - AudioService.getInstance().play(context.getAssets(), "Campus_Life.ogg"); + private void playFindDevVoice(Context context) { - } - private void stopmediaplayer(){ - AudioService.getInstance().stop(); - } - private void playNotificationVoice(Context paramContext) { - AudioService.getInstance().play(paramContext.getAssets(), "ring_msg.mp3"); - } + AudioService.getInstance().play(context.getAssets(), "Campus_Life.ogg"); - private void playshutdownsound(Context paramContext) { - AudioService.getInstance().play(paramContext.getAssets(), "shutdownsound.mp3"); - } + } + + private void stopmediaplayer() { + AudioService.getInstance().stop(); + } + + private void playNotificationVoice(Context paramContext) { + AudioService.getInstance().play(paramContext.getAssets(), "ring_msg.mp3"); + } + + private void playshutdownsound(Context paramContext) { + AudioService.getInstance().play(paramContext.getAssets(), "shutdownsound.mp3"); + } - private void screenOn(Context paramContext) { - final PowerManager.WakeLock wakelock = ((PowerManager)paramContext.getSystemService(Context.POWER_SERVICE)).newWakeLock(ACQUIRE_CAUSES_WAKEUP| SCREEN_DIM_WAKE_LOCK, ProcessReceiver.class.getSimpleName()); - wakelock.acquire(5000); + private void screenOn(Context paramContext) { + final PowerManager.WakeLock wakelock = ((PowerManager) paramContext.getSystemService(Context.POWER_SERVICE)).newWakeLock(ACQUIRE_CAUSES_WAKEUP | SCREEN_DIM_WAKE_LOCK, ProcessReceiver.class.getSimpleName()); + wakelock.acquire(5000); // Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { // public void call(Long param1Long) { wakelock.release(); } // }); - } - - @Override - public void onReceive(Context paramContext, Intent paramIntent) { - - boolean isSilence; - Contact contact; - String str = paramIntent.getAction(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("action=="); - stringBuilder.append(str); - ICLogger.i(stringBuilder.toString()); - - if (CoreService.getInstance()==null) - { - ICLogger.i("CoreService is null skip deal with this message! "+str); - paramContext.startService(new Intent(paramContext,CoreService.class));// protocol service - return ; } - if (RESUME_ACTION.equals(str)) { - SharPreferenceUtil.setPrefBoolean(paramContext, "key_is_resume", paramIntent.getBooleanExtra("is_resume", false)); - return; - }else if (ACTION_MESSAGE_SENT.equals(str)) { - - String msgType=paramIntent.getStringExtra(KEY_MESSAGE_TYPE); - String msgFrom=paramIntent.getStringExtra(KEY_MESSAGE_FROM); - String msgUrl=paramIntent.getStringExtra(KEY_MESSAGE_URL); - ICLogger.i("receive msg to send type="+msgType+", msg from = "+msgFrom+", msgUrl"+msgUrl); - if (msgFrom==null) msgFrom="123"; - /** - * * 1 语音—— 1.监听语音 * 2.SOS语音 * 3.扩展 - * * 2 图片—— 1.签到图片 * 2.指令图片 * 3.设备图片 * 4.扩展 - */ - if (msgType.equals("voice")) - { - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,1,3); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - }else if (msgType.equals("pic")){ - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,2,3); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - } - }else if (ACTION_SHUTDOWN.equals(str)) { - - playshutdownsound(paramContext); - - Util.shutdown(); - return; - }else if (ACTION_PLAYTIME.equals(str)) { - LedUtil.setBlueLedOn(true); - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - LedUtil.setBlueLedOn(false); - } - },2000L); - return; - }else if (ACTION_REMOTE_CAMERA.equals(str)) { - if (paramIntent.hasExtra("remote_number")){ - //接收拍照命令,执行拍照 - String str1 = paramIntent.getStringExtra("remote_number"); - new Handler().post(new Runnable() { - @Override - public void run() { - (new CameraUtil(paramContext)).getPictur(str1); - } - }); - }else{ - //接收到拍照完毕命令,发送照片 - String msgFrom=paramIntent.getStringExtra("number"); - String msgUrl=paramIntent.getStringExtra("filepath"); - ICLogger.i("receive taken photo to send "+msgUrl); - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,2,2); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - - } - - - return; - - }else if (DIALOG_ACTION.equals(str)) { - if (paramIntent.hasExtra("contact")) { - contact = (Contact) paramIntent.getParcelableExtra("contact"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (contact != null && !isSilence) { - if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, contact, 1,""); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); + + @Override + public void onReceive(Context paramContext, Intent paramIntent) { + + boolean isSilence; + Contact contact; + String str = paramIntent.getAction(); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("action=="); + stringBuilder.append(str); + ICLogger.i(stringBuilder.toString()); + + if (CoreService.getInstance() == null) { + ICLogger.i("CoreService is null skip deal with this message! " + str); + paramContext.startService(new Intent(paramContext, CoreService.class));// protocol service + return; + } + if (RESUME_ACTION.equals(str)) { + SharPreferenceUtil.setPrefBoolean(paramContext, "key_is_resume", paramIntent.getBooleanExtra("is_resume", false)); + return; + } else if (ACTION_MESSAGE_SENT.equals(str)) { + + String msgType = paramIntent.getStringExtra(KEY_MESSAGE_TYPE); + String msgFrom = paramIntent.getStringExtra(KEY_MESSAGE_FROM); + String msgUrl = paramIntent.getStringExtra(KEY_MESSAGE_URL); + ICLogger.i("receive msg to send type=" + msgType + ", msg from = " + msgFrom + ", msgUrl" + msgUrl); + if (msgFrom == null) msgFrom = "123"; + /** + * * 1 语音—— 1.监听语音 * 2.SOS语音 * 3.扩展 + * * 2 图片—— 1.签到图片 * 2.指令图片 * 3.设备图片 * 4.扩展 + */ + if (msgType.equals("voice")) { + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl, 1, 3); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection() != null) + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); + } else if (msgType.equals("pic")) { + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl, 2, 3); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection() != null) + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); } + } else if (ACTION_SHUTDOWN.equals(str)) { + + playshutdownsound(paramContext); + + Util.shutdown(); + return; + } else if (ACTION_PLAYTIME.equals(str)) { + LedUtil.setBlueLedOn(true); + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + LedUtil.setBlueLedOn(false); + } + }, 2000L); + return; + } else if (ACTION_REMOTE_CAMERA.equals(str)) { + if (paramIntent.hasExtra("remote_number")) { + //接收拍照命令,执行拍照 + String str1 = paramIntent.getStringExtra("remote_number"); + new Handler().post(new Runnable() { + @Override + public void run() { + (new CameraUtil(paramContext)).getPictur(str1); + } + }); + } else { + //接收到拍照完毕命令,发送照片 + String msgFrom = paramIntent.getStringExtra("number"); + String msgUrl = paramIntent.getStringExtra("filepath"); + ICLogger.i("receive taken photo to send " + msgUrl); + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl, 2, 2); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection() != null) + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - this.screenOn(paramContext); - } - }else if (paramIntent.hasExtra("sms")) { - String sms = paramIntent.getStringExtra("sms"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (sms != null && !isSilence) { - if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, null, 3,sms); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); } - this.screenOn(paramContext); - } - }else if (paramIntent.hasExtra("pushtxt")) { - String sms = paramIntent.getStringExtra("pushtxt"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (sms != null && !isSilence) { - if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, null, 4, sms); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - } - this.screenOn(paramContext); + return; + + } else if (DIALOG_ACTION.equals(str)) { + if (paramIntent.hasExtra("contact")) { + contact = (Contact) paramIntent.getParcelableExtra("contact"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (contact != null && !isSilence) { + if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, contact, 1, ""); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + } + + this.screenOn(paramContext); + } + } else if (paramIntent.hasExtra("sms")) { + String sms = paramIntent.getStringExtra("sms"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (sms != null && !isSilence) { + if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, null, 3, sms); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + } + + this.screenOn(paramContext); + } + } else if (paramIntent.hasExtra("pushtxt")) { + String sms = paramIntent.getStringExtra("pushtxt"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (sms != null && !isSilence) { + if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, null, 4, sms); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + } + + this.screenOn(paramContext); + } + } else if (paramIntent.hasExtra("findDev")) { + String finddevtxt = paramIntent.getStringExtra("findDev"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (finddevtxt != null && !isSilence) { + if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, null, 5, finddevtxt); + this.playFindDevVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + + } + + this.screenOn(paramContext); + } } - }else if (paramIntent.hasExtra("findDev")) { - String finddevtxt = paramIntent.getStringExtra("findDev"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (finddevtxt != null && !isSilence) { - if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, null, 5,finddevtxt); - this.playFindDevVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); + } else if (ACTION_TEMP_RESULT.equals(str)) { + double wrist_temp = paramIntent.getDoubleExtra(KEY_TEMP_WRIST, 0.0f); + double body_temp = paramIntent.getDoubleExtra(KEY_TEMP_BODY, 0.0f); + String temperatureMsg = protocolAPIHelper.getTemperatureMSG(wrist_temp, body_temp); + ICLogger.i("发送体温测量值 " + temperatureMsg); + Deliver.sendLocationMSG(temperatureMsg); + } else if (ACTION_SET_SIT_RANGE.equals(str)) { + if (paramIntent.hasExtra(Constants.KEY_SIT_RANGE)) { + int sitrange = paramIntent.getIntExtra(Constants.KEY_SIT_RANGE, 0); + Config.setKeepSitRangeInMinutes(paramContext, sitrange); + ICLogger.i("set KeepSitRange int " + sitrange + " minutes!"); + ICLogger.i("则重置 lastCheckSitTime 以及 lastSitCheckStepCount"); + Runtime.lastSitCheckStepCount = CoreService.getInstance().getRuntime().getTotalStepCount(); + Runtime.lastSitCheckTiimeyyyyMMddHHmmss = TimeUtil.getSystemTime3(); + } + } else { + //如果来电了,还有未读的消息,干脆关掉,防止影响接电话。 + if (mCustomDialog != null && mCustomDialog.isShowing()) { + mCustomDialog.dismiss(); } - this.screenOn(paramContext); - } + if (this.mCustomNotification != null && this.mCustomNotification.isShowing()) { + this.mCustomNotification.dismiss(); + } } + } - }else if (ACTION_TEMP_RESULT.equals(str)) { - double wrist_temp = paramIntent.getDoubleExtra(KEY_TEMP_WRIST, 0.0f); - double body_temp = paramIntent.getDoubleExtra(KEY_TEMP_BODY, 0.0f); - String temperatureMsg = protocolAPIHelper.getTemperatureMSG(wrist_temp, body_temp); - ICLogger.i("发送体温测量值 " + temperatureMsg); - Deliver.sendLocationMSG(temperatureMsg); - }else if (ACTION_SET_SIT_RANGE.equals(str)) { - if (paramIntent.hasExtra( Constants.KEY_SIT_RANGE)){ - int sitrange=paramIntent.getIntExtra(Constants.KEY_SIT_RANGE,0); - Config.setKeepSitRangeInMinutes(paramContext,sitrange); - ICLogger.i("set KeepSitRange int "+sitrange+" minutes!"); - ICLogger.i("则重置 lastCheckSitTime 以及 lastSitCheckStepCount"); - Runtime.lastSitCheckStepCount=CoreService.getInstance().getRuntime().getTotalStepCount(); - Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3(); - } - } else { - //如果来电了,还有未读的消息,干脆关掉,防止影响接电话。 - if (mCustomDialog != null && mCustomDialog.isShowing()) { - mCustomDialog.dismiss(); - } + public void sendStheartRateBroadcast(Context paramContext, String actionStr, int paramInt) { + Intent intent = new Intent(); + intent.setAction(actionStr); + intent.putExtra("stheartRateType", paramInt); + paramContext.sendBroadcast(intent); + } - if (this.mCustomNotification != null && this.mCustomNotification.isShowing()) { - this.mCustomNotification.dismiss(); - } - } - } - - public void sendStheartRateBroadcast(Context paramContext, String actionStr, int paramInt) { - Intent intent = new Intent(); - intent.setAction(actionStr); - intent.putExtra("stheartRateType", paramInt); - paramContext.sendBroadcast(intent); - } - public void sendSOSBroadcast(Context paramContext, String actionStr) { - Intent intent = new Intent(); - intent.setAction(actionStr); - paramContext.sendBroadcast(intent); - } + public void sendSOSBroadcast(Context paramContext, String actionStr) { + Intent intent = new Intent(); + intent.setAction(actionStr); + paramContext.sendBroadcast(intent); + } }