From: snickersun Date: Wed, 16 Dec 2020 10:08:34 +0000 (+0800) Subject: 远程设置wifi链接的时候也要考虑用户是否开启过wifi X-Git-Url: http://git.snicker.com.cn/?a=commitdiff_plain;h=dca8fd973e8c32a22dcdc2acd475bb1899a315af;p=protocol_srv.git 远程设置wifi链接的时候也要考虑用户是否开启过wifi --- 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 6049949a..246f1dfd 100644 --- a/app/src/main/java/com/enqualcomm/support/service/Deliver.java +++ b/app/src/main/java/com/enqualcomm/support/service/Deliver.java @@ -1,835 +1,839 @@ -package com.enqualcomm.support.service; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.net.ConnectivityManager; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiManager; -import android.os.Build; -import android.os.Handler; -import android.os.Message; -import android.os.Parcelable; -import android.os.PowerManager; -import android.os.SystemClock; - -import com.enqualcomm.support.Config; -import com.enqualcomm.support.Constants; -import com.enqualcomm.support.CoreService; -import com.enqualcomm.support.R; -import com.enqualcomm.support.bean.VoiceContent; -import com.enqualcomm.support.utils.DBHelper; -import com.enqualcomm.support.utils.TemperatureUtil; -import com.enqualcomm.support.utils.TimeUtil; -import com.ic.protocols.protocolAPIHelper; -import com.enqualcomm.support.bean.Contact; -import com.enqualcomm.support.bean.StringMessage; -import com.enqualcomm.support.bean.voicePacket; -import com.enqualcomm.support.service.base.AbstractConnectionService; -import com.enqualcomm.support.utils.Connection; -import com.enqualcomm.support.bean.Runtime; -import com.enqualcomm.support.utils.FileCache; -import com.enqualcomm.support.utils.ICLogger; -import com.enqualcomm.support.utils.NettyConnection; -import com.enqualcomm.support.utils.ServiceUtil; -import com.enqualcomm.support.utils.SharPreferenceUtil; -import com.enqualcomm.support.utils.SimSignalUtil; -import com.enqualcomm.support.utils.Util; - -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.ReentrantLock; - -import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; -import static com.enqualcomm.support.Constants.ACTION_WAKEUP_ALARM; -import static com.enqualcomm.support.Constants.DIALOG_ACTION; -import static com.enqualcomm.support.bean.Contact.CATEGORY_GROUP; -import static com.enqualcomm.support.bean.Content.CONTACT_CATEGORY_GROUP; - -/** - * 负责发送除了login,心跳之外的所有指令 - */ -public class Deliver extends AbstractConnectionService { - private static final String RECEIVE_WAKE_LOCKTAG = "ReceiveWakelockTag"; - - private static PowerManager.WakeLock WifiListWakeLock; - - public static boolean haveSendH42 = false; - - private static int isAppSetWifi = 0; - - private static boolean sendloopruning=false; - - - private static ReentrantLock mLock = new ReentrantLock(); - private static ReentrantLock lock = new ReentrantLock(); - private static Condition mCondition = mLock.newCondition(); - - public static LinkedBlockingDeque queue = new LinkedBlockingDeque(200); - - private static FileCache fileCache; - private static Connection connection; - - public static boolean is_active_location = false; - - private static PowerManager.WakeLock ReceiveWakeLock; - - private Handler delayHandler; - - private Runnable delayTh; - - private Connection mConnection; - - private ConWifiReceiver mMyWifiReceiver; - - private static Runtime mRuntime; - - private static boolean wakeLockWifiList = false; - - private static boolean wakeLockWifiSet = false; - - 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; - } - }); - - static { - delaySendMSG = new Runnable() { - @Override - public void run() { - sendloopruning=true; - if (getAndSendMsgFromQueue()==true){ - //数据发送成功,则5秒后进行下一轮发送(while 循环用sleep会很占资源造成死锁 - mSendMSGHandler.postDelayed(delaySendMSG,5000L); - }else{ - //没有数据可以发送,则退出sendloop - sendloopruning=false; - } - } - }; - } - public Deliver(Connection paramNettyConnection, Runtime paramRuntime) { - connection = paramNettyConnection; - mRuntime = paramRuntime; - //把queue 保存在磁盘中的缓存文件 - //此文件只缓存 除了 登录指令AP00,心跳AP03以及voice 分包指令以外的需要上传的指令。初步规划为 定位AP01和心率/血压 APHT - fileCache = new FileCache(paramRuntime.getFileDir()); - } - - private static boolean checkNetwork(){ - boolean ret=true; - boolean dateConnectionLinked=SimSignalUtil.checkNet(mRuntime.getContextProxy().context); - - if (dateConnectionLinked) { -// int signal = mRuntime.getSignalStrength(); -// int networkType = SimSignalUtil.getInstance((mRuntime.getContextProxy()).context).getNetworkType(); -// if (signal + 110 < getMinSignalStrength(networkType)) { -// ICLogger.i("Skip Send for SignalStrengh " + (signal + 110) + " < " + getMinSignalStrength(networkType)); -// //如果信号不好,把msg放回去 -// ret = false; -// } - if (connection.isServerConnected() == false || !mRuntime.isServerProtocolConnected()) { - ICLogger.i("服务器无法访问,或者协议状态失常"); - ret = false; - } - }else{ - ICLogger.i("数据网络没有连接"); - ret=false; - } - return ret; - } - public static void triggerSendThread() { - - - if(sendloopruning==false) { - ICLogger.i("triggerSendThread !"); - mSendMSGHandler.post(delaySendMSG); - }else{ - ICLogger.i("triggerSendThread running skip !"); - } - -// delaySendMSG.run(); -// mSendMSGHandler.sendEmptyMessage(1); - } - private static int CheckCount=0; - private static boolean checkNeedServerResponse(StringMessage cmd){ - - boolean NeedCheckServerResponse; - if(cmd!=null && - Config.protocol_no==Config.PROTOCOL_FZD && - (protocolAPIHelper.isCmdStr(cmd).equals("UD") || protocolAPIHelper.isCmdStr(cmd).equals("UD2")) - ){ - NeedCheckServerResponse=false; - }else{ - NeedCheckServerResponse=true; - } - return NeedCheckServerResponse; - } - public static void dumpMessage(StringMessage msg){ - - StringBuilder sb = new StringBuilder("StringMessage "); - if (msg!=null) { - sb.append("index ").append(msg.getIndex()) - .append("\nDate ").append(msg.getDate()).append(msg.getTime()) - .append("\nflag ").append(msg.haveSent()) - .append("\ntopic ").append(msg.cmd()) - .append("\ncmd ").append(msg.isFromCache()).append("\n"); - } -// ICLogger.i(sb.toString()); - - } - public static boolean getAndSendMsgFromQueue(){ - boolean ret=false; - if (mRuntime.getUseQueue()) { - ICLogger.i("queue locked "+mLock.isLocked()); - if(mLock.isLocked()) return false; - mLock.lock(); - try - { - String str; - //如果没有数据从缓存中尝试读取 - - //检查刚刚发送出去的包是否需要检查server response - - StringMessage msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); - dumpMessage(msgWait); - - if(msgWait!=null) { - //如果需要,且没有服务器反馈 - //刚刚发送的包不为空,且检测次数小于3,则保留数据,进行下一次重试。 - //如果cmd有效,且尝试次数小于3, 没有收到反馈的情况下,可以重新插入queue进行下一次尝试! - ICLogger.i("checkSrvResponse " + CheckCount + " times for " + msgWait.cmd() + " " + msgWait.isFromCache() + " index " + msgWait.getIndex()); - if (msgWait.getIndex() >= 0) { - mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 0);//设置为未发送 - } - dumpMessage(msgWait); - CheckCount++; - //尝试次数大于5 ,可能是还没有发送过数据,或者超过重试次数,暂停提取queue中数据进,下次心跳再开始发送 - if (CheckCount > 5) { - ICLogger.i("checkSrvResponse CheckCount=" + CheckCount + " Timeout or cmd is null, skip "); - - //C5要的临时版本,去掉盲点续传。 - - if( Config.discard_cmd_after_retryfailed) { - if (msgWait.getIndex() >= 0) { - //有些协议需要对盲点数据进行修改(盲点数据可能是不同的topic),在此对数据修改后更新数据库 - mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 3);//设置为盲点不发送 - } - dumpMessage(msgWait); - } - if (Config.LOG_TOFILE) - ICLogger.logToFile("APILog", "response timeout skip! "); - CheckCount = 0; - if (mLock != null && mLock.isLocked()) - mLock.unlock(); - return false; - } - - } - - StringBuilder stringBuilder = new StringBuilder(); - if (checkNetwork()) { - StringMessage msgSent; - if( Config.discard_cmd_after_retryfailed) { - //如果可以丢弃数据,则直接查找没发送的数据即可 - msgSent = mRuntime.getDbHelper().queryNotSentCMDRecord(); - }else{ - //如果有盲点续传问题,不丢弃,则先查找丢掉的数据(重试失败的)先进行重传。 - msgSent = mRuntime.getDbHelper().queryDiscardCMDRecord(); - if(msgSent==null) { - //如果没有丢弃的数据,直接查找未发送的数据进行 - msgSent = mRuntime.getDbHelper().queryNotSentCMDRecord(); - } - } - dumpMessage(msgSent); - if (msgSent != null) { - String cmd = msgSent.isFromCache(); - String topic = msgSent.cmd(); - stringBuilder.append(topic); - stringBuilder.append(" "); - stringBuilder.append(cmd); - stringBuilder.append("\n"); - if (checkNetwork()) { - - connection.send(msgSent); - //如果需要CheckResponse - if (checkNeedServerResponse(msgSent)==true){ - ICLogger.i("checkSrvResponse "+topic+" "+cmd); - mRuntime.getDbHelper().updateCMDRecord(msgSent.getIndex(),1); //设置为等待响应 - }else{ - ICLogger.i("no need checkSrvResponse "+topic+" "+cmd); - mRuntime.getDbHelper().updateCMDRecord(msgSent.getIndex(),2); //直接设置为已经响应 - } - ret=true; - } else { - //已经拿到的缓存,如果刚巧没有网络,就原路放回去 - ICLogger.i("网络不通,不能发送!"); - if (msgSent.getIndex() >= 0) { - mRuntime.getDbHelper().updateCMDRecord(msgSent.getIndex(), 0); //设置为未发送 - } - dumpMessage(msgSent); - ret=false; - } - }else{ - stringBuilder.append("no message!\n"); - } - } - str = stringBuilder.toString(); - ICLogger.i("send cached cmd : \n"+str); - //ICLogger.i("\n"+queue.size()+" left in Queue!"); - }finally { - if(mLock!=null && mLock.isLocked()) - mLock.unlock(); - } - } - return ret; - } - - public static void resetCMDReocrdsDB(){ - //正常应该只有一个在wait的记录,如果开机的时候,可能需要处理一下第一条记录 - StringMessage msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); - dumpMessage(msgWait); - if (msgWait!=null) { - if( Config.discard_cmd_after_retryfailed) { - while(msgWait!=null) { - //所有缓存数据都设置为放弃发送 - mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 3); - msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); - } - }else { - mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 0);//设置为未发送 - } - } - } - public static void sendLocationMSG( String Msg){ - - if(Msg==null ||Msg.trim().isEmpty()){ - ICLogger.i("命令为空,跳过发送!"); - return ; - } - sendLocationMSG(protocolAPIHelper.genStringMessage("queue",Msg)); - } - public static void sendLocationMSG( StringMessage Msg){ - if(Msg==null ){ - ICLogger.i("命令为空,跳过发送!"); - return ; - } - - if(mRuntime.getUseQueue()){ - long id=mRuntime.getDbHelper().insertCMDRecord(Msg); - Msg.setIndex((int)id); - dumpMessage(Msg); - triggerSendThread(); - }else { - if (checkNetwork()) { - ICLogger.i(" first send " + Msg); - connection.send(Msg); - } else { - ICLogger.i("offline skip " + Msg); - if (Config.LOG_TOFILE) ICLogger.logToFile( "APILog", " offlineskip " + Msg.cmd()+" "+Msg.isFromCache()); - } - } -} - private static int getMinSignalStrength(int paramInt) { - int b = -105; - switch (paramInt) { - case SimSignalUtil.IS_4G: - b = -100; - break; - case SimSignalUtil.IS_2G: - case SimSignalUtil.IS_3G: - default: - break; - } - return b; - } - - public static PowerManager.WakeLock WakeLockForGetWifiList(Runtime paramRuntime) { - PowerManager.WakeLock wakeLock = ((PowerManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Deliver.class.getSimpleName()); - wakeLock.acquire(120000L); - return wakeLock; - } - - private boolean isSilence(Runtime paramRuntime) { - return SharPreferenceUtil.getPrefBoolean((paramRuntime.getContextProxy()).context, "KEY_ISSILENCE", false); - } - - public static void releaseWakeLockForGetWifiList() { - if (WifiListWakeLock == null) { - ICLogger.i("WifiListWakeLock 没有加锁"); - return; - } - if (WifiListWakeLock.isHeld()) { - WifiListWakeLock.release(); - WifiListWakeLock = null; - } - } - - public PowerManager.WakeLock getWakeLock() { - PowerManager.WakeLock wakeLock = ((PowerManager)(this.mRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Deliver.class.getSimpleName()); - wakeLock.acquire(40000L); - return wakeLock; - } - - public void onAlarmClock(Connection paramConnection, Runtime paramRuntime) {} - - public void onAttach(Connection paramConnection, Runtime paramRuntime) {} - - @Override - public boolean onConnectionClose(Connection paramConnection, Runtime paramRuntime, String ErrorMsg) { - return false; } - - public boolean onConnectionOpen(Connection paramConnection, Runtime paramRuntime) { return false; } - - public void onDetach(Connection paramConnection, Runtime paramRuntime) {} - - public boolean onReceive(StringMessage paramStringMessage, Connection paramConnection, final Runtime paramRuntime) { - this.mConnection = paramConnection; - this.mRuntime = paramRuntime; - String cmd = paramStringMessage.cmd(); - if(Config.protocol_no==Config.PROTOCOL_MQTT) - { - cmd=protocolAPIHelper.isCmdStr(paramStringMessage); - } - //如果需要检测是否响应。 - StringMessage msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); - dumpMessage(msgWait); - if(msgWait!=null) { - ICLogger.i("====== checkSrvResponse cmd " + cmd + " msg " + protocolAPIHelper.isCmdStr(msgWait)); - if (cmd.equals(protocolAPIHelper.isCmdStr(msgWait))) { - ICLogger.i("checkSrvResponse " + cmd + " " + protocolAPIHelper.isCmdStr(msgWait) + " is responsed!"); - mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 2);//设置为已读 - CheckCount = 0; - } - } - - ICLogger.i("Deliver receive cmd " + paramStringMessage.cmd()); - if (cmd.equals("SentVoicePacket") ) { - //收到BP07 表示服务器收到一个voicePacket 分包成功,开始检查下一个包是否存在需要发送。 - //收到SentVoicePacket 表示 有一个VoiceMessage要发送,需要从第0个包开始发送语音分包。 - voicePacket voicepacket = voicePacket.getInstanceSent(); - if (voicepacket.getCurrentIndexToSent() < voicepacket.getPacketCount()) { - ICLogger.i("voicepacket " + voicepacket.getName() + " filetype " + voicepacket.getFiletype() + " , datatype " + voicepacket.getDateType() +" "+ voicepacket.getPacketTime() + " send " + (voicepacket.getCurrentIndexToSent() + 1) + "/" + voicepacket.getPacketCount()); - if(mConnection instanceof NettyConnection) { - ((NettyConnection) mConnection).sendMsg("RAWPACKET", - protocolAPIHelper.getVoicePacketItem(voicepacket.getPacketTime(), - voicepacket.getPacketCount(), - (voicepacket.getCurrentIndexToSent() + 1), - voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketLen(), - voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketData(), voicepacket.getFiletype(), voicepacket.getDateType()) - ); - } - } else { - ICLogger.i("voicepacket " + voicepacket.getName() + " filetype " + voicepacket.getFiletype() + " , datatype " + voicepacket.getDateType() + " " + voicepacket.getPacketTime() + " sent Done!"); - } - return true; - } else if ("PhotoRemoteTaken".equals(paramStringMessage.cmd())) { - //接收到拍照完毕命令,发送照片 - - String msgUrl=paramStringMessage.isFromCache(); - ICLogger.i("receive taken photo to send "+msgUrl); - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, "123", msgUrl,2,2); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) { - - - //H88 专用功能拍照时检测用户体温心率 - if(Util.getSystemProperties("persist.sys.do_check_condition","false").equals("true")) { - //开启测温 - if(mRuntime.check_stat_do_temp_test()) { - TemperatureUtil.DoTempTest(); - } - - Util.mSleep(5000); - //开启测量PPG - if(mRuntime.check_stat_do_ppg_test()) { - HeartRateManager.triggerPPGtest(); - } - } - - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - } - return true; - } else if ("poweroffCheckSim".equals(paramStringMessage.cmd())) { - paramRuntime.setShutdown(true); - - if (SimSignalUtil.hasSimCard(paramRuntime.getContextProxy().context)) - { - ICLogger.i("Has Sim Card Skip poweroff!"); - Util.ShowToast(paramRuntime,"Has Sim Card Skip poweroff!"); - return true; - }else{ - Util.ShowToast(paramRuntime,"Do poweroff!"); - } - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - Util.shutdown(); - } - },2000); - return true; - } else if ("FactoryResetCheckSim".equals(paramStringMessage.cmd())) { - - if (SimSignalUtil.hasSimCard(paramRuntime.getContextProxy().context)) - { - ICLogger.i("Has Sim Card Skip FactoryReset!"); - Util.ShowToast(paramRuntime,"Has Sim Card Skip FactoryReset!"); - - return true; - }else{ - Util.ShowToast(paramRuntime,"Do FactoryReset!"); - } - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - Util.doMasterClear(paramRuntime.getContextProxy().context); - } - },2000); - return true; - } else if ("poweroff".equals(paramStringMessage.cmd())) { - paramRuntime.setShutdown(true); - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - Util.shutdown(); - } - },2000); - return true; - } else if ("FactoryReset".equals(paramStringMessage.cmd())) { - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - Util.doMasterClear(paramRuntime.getContextProxy().context); - } - },2000); - return true; - } else if ("Reboot".equals(paramStringMessage.cmd())) { - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - Util.reboot(paramRuntime.getContextProxy().context); - } - },2000); - return true; - } else if ("heartbeat".equals(paramStringMessage.cmd())) { - //每次心跳,查询一下 是否有语音消息需要接收。 -// paramConnection.send(protocolAPIHelper.genStringMessage("AP05",protocolAPIHelper.AP05(true))); - - } else if ("getWeather".equals(paramStringMessage.cmd())) { - ICLogger.i("获取天气"); - mConnection.send(protocolAPIHelper.getWeatherMSG(mRuntime)); - } else if ("NewVoice".equals(paramStringMessage.cmd())) - { - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - final Context context = (Deliver.this.mRuntime.getContextProxy()).context; - - Contact param2Contact = new Contact(CATEGORY_GROUP, (mRuntime.getContextProxy()).context.getResources().getString(R.string.all_group), Contact.GROUP_ALL); - int i = mRuntime.getContextProxy().getTelephonyManager().getCallState(); - if (!mRuntime.getBatteryLow() && 1 != i && 2 != i) { - if (Config.do_broadCast_message) - { - - ICLogger.d(Constants.ACTION_MESSAGE_RECEIVED+" "+paramStringMessage.isFromCache()); - //广播 voice消息 - Intent intent = new Intent(); - intent.setAction(Constants.ACTION_MESSAGE_RECEIVED); - intent.putExtra(Constants.KEY_MESSAGE_TYPE,"voice"); - intent.putExtra(Constants.KEY_MESSAGE_FROM,"广播消息"); - intent.putExtra(Constants.KEY_MESSAGE_URL,paramStringMessage.isFromCache()); - - // playVoice(context,paramStringMessage.isFromCache()); - context.sendBroadcast(intent); - } - - if (Config.noVoiceNotifyDialog==false) { - - Intent intent = new Intent(); - //显示提示窗口 - intent.setAction(DIALOG_ACTION); - intent.putExtra("contact", (Parcelable) param2Contact); - context.sendBroadcast(intent); - } - - } - } - },500); - - return true; - }else if ("findDev".equals(paramStringMessage.cmd())) { - - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - final Context context = (Deliver.this.mRuntime.getContextProxy()).context; - Intent intent = new Intent(); - ICLogger.d(Constants.ACTION_MESSAGE_RECEIVED+" "+paramStringMessage.isFromCache()); - //显示提示窗口 - intent.setAction(DIALOG_ACTION); - intent.putExtra("findDev", "Find Device"); - context.sendBroadcast(intent); - } - },500); - - return true; - }else if ("takephoto".equals(paramStringMessage.cmd())) { - - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - final Context context = (Deliver.this.mRuntime.getContextProxy()).context; - Intent intent = new Intent(); - ICLogger.d(Constants.ACTION_MESSAGE_RECEIVED+" "+paramStringMessage.isFromCache()); - //显示提示窗口 - intent.setAction(DIALOG_ACTION); - intent.putExtra("takephoto", "Take Photo !"); - context.sendBroadcast(intent); - } - },500); - - return true; - - }else if ("StartMonitor".equals(paramStringMessage.cmd())) { - - String recordfilepath=Util.getRecordfilePath(mRuntime, TimeUtil.getSystemTime3()); - int recordtime=Integer.parseInt(paramStringMessage.isFromCache().trim()); - mSendMSGHandler.post(new Runnable() { - @Override - public void run() { - AudioService.getInstance().startRecord(recordfilepath); - } - }); - mSendMSGHandler.postDelayed(new Runnable() { - @Override - public void run() { - AudioService.getInstance().stopRecord(); - ICLogger.i("Monitor Record to send "+recordfilepath); - //创建voiceConent并添加到数据 - /** - * * * 1 语音—— 1.监听语音 * 2.SOS语音 * 3.扩展 - * * * 2 图片—— 1.签到图片 * 2.指令图片 * 3.设备图片 * 4.扩展 - */ - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, "123", recordfilepath,1,1); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - } - },recordtime*1000); - - return true; - } - - return false; - } - - - - private void playVoice(Context paramContext,String voicefile) { - AudioService.getInstance().play(voicefile); - } - - public static void releaseOneWakeLock() { - if (ReceiveWakeLock == null) { - ICLogger.i("ReceiveWakeLock 没有加锁"); - return; - } - if (!wakeLockWifiList && !wakeLockWifiSet && ReceiveWakeLock.isHeld()) { - ReceiveWakeLock.release(); - ReceiveWakeLock = null; - } - } - - public void releaseReceiveWakeLock() { - if (this.ReceiveWakeLock == null) { - ICLogger.i("ReceiveWakeLock 没有加锁"); - return; - } - if (this.ReceiveWakeLock.isHeld()) { - this.ReceiveWakeLock.release(); - this.wakeLockWifiList = false; - this.wakeLockWifiSet = false; - this.ReceiveWakeLock = null; - } - } - public static void connectToWifi(String ssid,String pwd,String encryptType){ - int networkid; - final WifiManager wifiManager = mRuntime.getContextProxy().getWifiManager(); - wifiEnabled = wifiManager.isWifiEnabled(); - if (!wifiEnabled) - { - //没开就打开wifi - Util.turnOnWifiForConnect(mRuntime.getContextProxy().context, mRuntime); - } - if (Util.isConnectWifi(mRuntime.getContextProxy().context)) { - networkid = wifiManager.getConnectionInfo().getNetworkId(); - wifiManager.disconnect(); - wifiManager.removeNetwork(networkid); - wifiManager.saveConfiguration(); - } - - Deliver.isAppSetWifi = 1; - WifiConfiguration wifiConfiguration = Util.GetconfigWifiInfo(mRuntime.getContextProxy().context, ssid, pwd, encryptType); - networkid = wifiConfiguration.networkId; - wifiManager.removeNetwork(networkid); - wifiManager.saveConfiguration(); - networkid = wifiManager.addNetwork(wifiConfiguration); - if (Util.connectWifiByReflectMethod(mRuntime.getContextProxy().context, networkid) == null && !wifiManager.enableNetwork(networkid, true)) { - ICLogger.i("连接失败 3"); - SystemClock.sleep(3000L); - - wifiManager.setWifiEnabled(false); - wakeLockWifiSet = false; - releaseOneWakeLock(); - WifiListWakeLock = Deliver.WakeLockForGetWifiList(mRuntime); - - return; - } - - if(!wifiEnabled ){ - //原来wifi没开就关闭wifi - Util.turnOffWifiForSleep(mRuntime.getContextProxy().context, mRuntime); - } - - } - public void setWakeupAlarm(Runtime paramRuntime) { - AlarmManager alarmManager = (AlarmManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent((paramRuntime.getContextProxy()).context, CoreService.class); - intent.setAction(ACTION_WAKEUP_ALARM); - PendingIntent pendingIntent = PendingIntent.getService((paramRuntime.getContextProxy()).context, 0, intent, FLAG_UPDATE_CURRENT); - alarmManager.cancel(pendingIntent); - long l = SystemClock.elapsedRealtime(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("SDK_INT="); - stringBuilder.append(Build.VERSION.SDK_INT); - stringBuilder.append(",m=,"); - stringBuilder.append(23); - stringBuilder.append(",kitkat="); - stringBuilder.append(19); - ICLogger.i(stringBuilder.toString()); - if (Build.VERSION.SDK_INT >= 19) { - alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, l + 10000L, pendingIntent); - return; - } - alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, l + 10000L, pendingIntent); - } - - class ConWifiReceiver extends BroadcastReceiver { - ConWifiReceiver() { - } - - public void onReceive(final Context var1, Intent var2) { - String var3 = var2.getAction(); - StringBuilder var4 = new StringBuilder(); - var4.append(" receive action="); - var4.append(var3); - var4.append(" isAppSetWifi="); - var4.append(Deliver.isAppSetWifi); - ICLogger.i(var4.toString()); - if (var3.equals("android.net.conn.CONNECTIVITY_CHANGE")) { - if (Deliver.isAppSetWifi == 0) { - return; - } - - if (Deliver.isAppSetWifi == 1) { - Deliver.isAppSetWifi = 0; - if (Deliver.this.delayHandler != null) { - Deliver.this.delayHandler.removeCallbacks(Deliver.this.delayTh); - Deliver.this.delayHandler = null; - } - } - - WifiManager var5 = (WifiManager)var1.getSystemService(Context.WIFI_SERVICE); - if (((ConnectivityManager)var1.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { - ICLogger.i("连接成功"); - Deliver.isAppSetWifi = 0; - Deliver.haveSendH42 = true; - Deliver.this.mConnection.connect(Deliver.this.mRuntime.getHost(), Deliver.this.mRuntime.getPort()); - if (Deliver.this.delayHandler != null) { - Deliver.this.delayHandler.removeCallbacks(Deliver.this.delayTh); - Deliver.this.delayHandler = null; - } - - var1.unregisterReceiver(Deliver.this.mMyWifiReceiver); - Deliver.this.mMyWifiReceiver = null; - Deliver.this.wakeLockWifiSet = false; - Deliver.this.releaseOneWakeLock(); - Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); - } else { - StringBuilder var6 = new StringBuilder(); - var6.append("连接失败 222 delayHandler="); - var6.append(Deliver.this.delayHandler); - ICLogger.i(var6.toString()); - Deliver.isAppSetWifi = 2; - var5.reconnect(); - if (Deliver.this.delayHandler == null) { - Deliver.this.delayHandler = new Handler(); - Deliver.this.delayTh = new Runnable() { - public void run() { - StringBuilder var1x = new StringBuilder(); - var1x.append("连接失败 超时 wifiEnabled="); - var1x.append(Deliver.this.wifiEnabled); - ICLogger.i(var1x.toString()); - if (Deliver.isAppSetWifi != 1) { - Deliver.isAppSetWifi = 0; - var1.unregisterReceiver(Deliver.this.mMyWifiReceiver); - Deliver.this.mMyWifiReceiver = null; - WifiManager var3 = (WifiManager)var1.getSystemService(Context.WIFI_SERVICE); - if (((ConnectivityManager)var1.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { - ICLogger.i("连接成功 1"); - Deliver.haveSendH42 = true; - Deliver.this.mConnection.connect(Deliver.this.mRuntime.getHost(), Deliver.this.mRuntime.getPort()); - Deliver.this.wakeLockWifiSet = false; - Deliver.this.releaseOneWakeLock(); - Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); - } else { - int var2 = var3.getConnectionInfo().getNetworkId(); - if (var2 != -1) { - var3.disableNetwork(var2); -// ServiceUtil.offerQueue(API.H42(Deliver.this.mRuntime, "3")); - Deliver.this.wakeLockWifiSet = false; - Deliver.this.releaseOneWakeLock(); - Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); - } else { - ICLogger.i("连接失败 2-2"); -// ServiceUtil.offerQueue(API.H42(Deliver.this.mRuntime, "3")); - Deliver.this.wakeLockWifiSet = false; - Deliver.this.releaseOneWakeLock(); - Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); - } - - if (!Deliver.this.wifiEnabled) { - var3.setWifiEnabled(false); - } - } - - Deliver.this.delayHandler = null; - } - } - }; - Deliver.this.delayHandler.postDelayed(Deliver.this.delayTh, 30000L); - } - } - } - - } - } - - -} - +package com.enqualcomm.support.service; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; +import android.os.Build; +import android.os.Handler; +import android.os.Message; +import android.os.Parcelable; +import android.os.PowerManager; +import android.os.SystemClock; + +import com.enqualcomm.support.Config; +import com.enqualcomm.support.Constants; +import com.enqualcomm.support.CoreService; +import com.enqualcomm.support.R; +import com.enqualcomm.support.bean.VoiceContent; +import com.enqualcomm.support.utils.DBHelper; +import com.enqualcomm.support.utils.TemperatureUtil; +import com.enqualcomm.support.utils.TimeUtil; +import com.ic.protocols.protocolAPIHelper; +import com.enqualcomm.support.bean.Contact; +import com.enqualcomm.support.bean.StringMessage; +import com.enqualcomm.support.bean.voicePacket; +import com.enqualcomm.support.service.base.AbstractConnectionService; +import com.enqualcomm.support.utils.Connection; +import com.enqualcomm.support.bean.Runtime; +import com.enqualcomm.support.utils.FileCache; +import com.enqualcomm.support.utils.ICLogger; +import com.enqualcomm.support.utils.NettyConnection; +import com.enqualcomm.support.utils.ServiceUtil; +import com.enqualcomm.support.utils.SharPreferenceUtil; +import com.enqualcomm.support.utils.SimSignalUtil; +import com.enqualcomm.support.utils.Util; + +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + +import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; +import static com.enqualcomm.support.Constants.ACTION_WAKEUP_ALARM; +import static com.enqualcomm.support.Constants.DIALOG_ACTION; +import static com.enqualcomm.support.bean.Contact.CATEGORY_GROUP; +import static com.enqualcomm.support.bean.Content.CONTACT_CATEGORY_GROUP; + +/** + * 负责发送除了login,心跳之外的所有指令 + */ +public class Deliver extends AbstractConnectionService { + private static final String RECEIVE_WAKE_LOCKTAG = "ReceiveWakelockTag"; + + private static PowerManager.WakeLock WifiListWakeLock; + + public static boolean haveSendH42 = false; + + private static int isAppSetWifi = 0; + + private static boolean sendloopruning=false; + + + private static ReentrantLock mLock = new ReentrantLock(); + private static ReentrantLock lock = new ReentrantLock(); + private static Condition mCondition = mLock.newCondition(); + + public static LinkedBlockingDeque queue = new LinkedBlockingDeque(200); + + private static FileCache fileCache; + private static Connection connection; + + public static boolean is_active_location = false; + + private static PowerManager.WakeLock ReceiveWakeLock; + + private Handler delayHandler; + + private Runnable delayTh; + + private Connection mConnection; + + private ConWifiReceiver mMyWifiReceiver; + + private static Runtime mRuntime; + + private static boolean wakeLockWifiList = false; + + private static boolean wakeLockWifiSet = false; + + 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; + } + }); + + static { + delaySendMSG = new Runnable() { + @Override + public void run() { + sendloopruning=true; + if (getAndSendMsgFromQueue()==true){ + //数据发送成功,则5秒后进行下一轮发送(while 循环用sleep会很占资源造成死锁 + mSendMSGHandler.postDelayed(delaySendMSG,5000L); + }else{ + //没有数据可以发送,则退出sendloop + sendloopruning=false; + } + } + }; + } + public Deliver(Connection paramNettyConnection, Runtime paramRuntime) { + connection = paramNettyConnection; + mRuntime = paramRuntime; + //把queue 保存在磁盘中的缓存文件 + //此文件只缓存 除了 登录指令AP00,心跳AP03以及voice 分包指令以外的需要上传的指令。初步规划为 定位AP01和心率/血压 APHT + fileCache = new FileCache(paramRuntime.getFileDir()); + } + + private static boolean checkNetwork(){ + boolean ret=true; + boolean dateConnectionLinked=SimSignalUtil.checkNet(mRuntime.getContextProxy().context); + + if (dateConnectionLinked) { +// int signal = mRuntime.getSignalStrength(); +// int networkType = SimSignalUtil.getInstance((mRuntime.getContextProxy()).context).getNetworkType(); +// if (signal + 110 < getMinSignalStrength(networkType)) { +// ICLogger.i("Skip Send for SignalStrengh " + (signal + 110) + " < " + getMinSignalStrength(networkType)); +// //如果信号不好,把msg放回去 +// ret = false; +// } + if (connection.isServerConnected() == false || !mRuntime.isServerProtocolConnected()) { + ICLogger.i("服务器无法访问,或者协议状态失常"); + ret = false; + } + }else{ + ICLogger.i("数据网络没有连接"); + ret=false; + } + return ret; + } + public static void triggerSendThread() { + + + if(sendloopruning==false) { + ICLogger.i("triggerSendThread !"); + mSendMSGHandler.post(delaySendMSG); + }else{ + ICLogger.i("triggerSendThread running skip !"); + } + +// delaySendMSG.run(); +// mSendMSGHandler.sendEmptyMessage(1); + } + private static int CheckCount=0; + private static boolean checkNeedServerResponse(StringMessage cmd){ + + boolean NeedCheckServerResponse; + if(cmd!=null && + Config.protocol_no==Config.PROTOCOL_FZD && + (protocolAPIHelper.isCmdStr(cmd).equals("UD") || protocolAPIHelper.isCmdStr(cmd).equals("UD2")) + ){ + NeedCheckServerResponse=false; + }else{ + NeedCheckServerResponse=true; + } + return NeedCheckServerResponse; + } + public static void dumpMessage(StringMessage msg){ + + StringBuilder sb = new StringBuilder("StringMessage "); + if (msg!=null) { + sb.append("index ").append(msg.getIndex()) + .append("\nDate ").append(msg.getDate()).append(msg.getTime()) + .append("\nflag ").append(msg.haveSent()) + .append("\ntopic ").append(msg.cmd()) + .append("\ncmd ").append(msg.isFromCache()).append("\n"); + } +// ICLogger.i(sb.toString()); + + } + public static boolean getAndSendMsgFromQueue(){ + boolean ret=false; + if (mRuntime.getUseQueue()) { + ICLogger.i("queue locked "+mLock.isLocked()); + if(mLock.isLocked()) return false; + mLock.lock(); + try + { + String str; + //如果没有数据从缓存中尝试读取 + + //检查刚刚发送出去的包是否需要检查server response + + StringMessage msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); + dumpMessage(msgWait); + + if(msgWait!=null) { + //如果需要,且没有服务器反馈 + //刚刚发送的包不为空,且检测次数小于3,则保留数据,进行下一次重试。 + //如果cmd有效,且尝试次数小于3, 没有收到反馈的情况下,可以重新插入queue进行下一次尝试! + ICLogger.i("checkSrvResponse " + CheckCount + " times for " + msgWait.cmd() + " " + msgWait.isFromCache() + " index " + msgWait.getIndex()); + if (msgWait.getIndex() >= 0) { + mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 0);//设置为未发送 + } + dumpMessage(msgWait); + CheckCount++; + //尝试次数大于5 ,可能是还没有发送过数据,或者超过重试次数,暂停提取queue中数据进,下次心跳再开始发送 + if (CheckCount > 5) { + ICLogger.i("checkSrvResponse CheckCount=" + CheckCount + " Timeout or cmd is null, skip "); + + //C5要的临时版本,去掉盲点续传。 + + if( Config.discard_cmd_after_retryfailed) { + if (msgWait.getIndex() >= 0) { + //有些协议需要对盲点数据进行修改(盲点数据可能是不同的topic),在此对数据修改后更新数据库 + mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 3);//设置为盲点不发送 + } + dumpMessage(msgWait); + } + if (Config.LOG_TOFILE) + ICLogger.logToFile("APILog", "response timeout skip! "); + CheckCount = 0; + if (mLock != null && mLock.isLocked()) + mLock.unlock(); + return false; + } + + } + + StringBuilder stringBuilder = new StringBuilder(); + if (checkNetwork()) { + StringMessage msgSent; + if( Config.discard_cmd_after_retryfailed) { + //如果可以丢弃数据,则直接查找没发送的数据即可 + msgSent = mRuntime.getDbHelper().queryNotSentCMDRecord(); + }else{ + //如果有盲点续传问题,不丢弃,则先查找丢掉的数据(重试失败的)先进行重传。 + msgSent = mRuntime.getDbHelper().queryDiscardCMDRecord(); + if(msgSent==null) { + //如果没有丢弃的数据,直接查找未发送的数据进行 + msgSent = mRuntime.getDbHelper().queryNotSentCMDRecord(); + } + } + dumpMessage(msgSent); + if (msgSent != null) { + String cmd = msgSent.isFromCache(); + String topic = msgSent.cmd(); + stringBuilder.append(topic); + stringBuilder.append(" "); + stringBuilder.append(cmd); + stringBuilder.append("\n"); + if (checkNetwork()) { + + connection.send(msgSent); + //如果需要CheckResponse + if (checkNeedServerResponse(msgSent)==true){ + ICLogger.i("checkSrvResponse "+topic+" "+cmd); + mRuntime.getDbHelper().updateCMDRecord(msgSent.getIndex(),1); //设置为等待响应 + }else{ + ICLogger.i("no need checkSrvResponse "+topic+" "+cmd); + mRuntime.getDbHelper().updateCMDRecord(msgSent.getIndex(),2); //直接设置为已经响应 + } + ret=true; + } else { + //已经拿到的缓存,如果刚巧没有网络,就原路放回去 + ICLogger.i("网络不通,不能发送!"); + if (msgSent.getIndex() >= 0) { + mRuntime.getDbHelper().updateCMDRecord(msgSent.getIndex(), 0); //设置为未发送 + } + dumpMessage(msgSent); + ret=false; + } + }else{ + stringBuilder.append("no message!\n"); + } + } + str = stringBuilder.toString(); + ICLogger.i("send cached cmd : \n"+str); + //ICLogger.i("\n"+queue.size()+" left in Queue!"); + }finally { + if(mLock!=null && mLock.isLocked()) + mLock.unlock(); + } + } + return ret; + } + + public static void resetCMDReocrdsDB(){ + //正常应该只有一个在wait的记录,如果开机的时候,可能需要处理一下第一条记录 + StringMessage msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); + dumpMessage(msgWait); + if (msgWait!=null) { + if( Config.discard_cmd_after_retryfailed) { + while(msgWait!=null) { + //所有缓存数据都设置为放弃发送 + mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 3); + msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); + } + }else { + mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 0);//设置为未发送 + } + } + } + public static void sendLocationMSG( String Msg){ + + if(Msg==null ||Msg.trim().isEmpty()){ + ICLogger.i("命令为空,跳过发送!"); + return ; + } + sendLocationMSG(protocolAPIHelper.genStringMessage("queue",Msg)); + } + public static void sendLocationMSG( StringMessage Msg){ + if(Msg==null ){ + ICLogger.i("命令为空,跳过发送!"); + return ; + } + + if(mRuntime.getUseQueue()){ + long id=mRuntime.getDbHelper().insertCMDRecord(Msg); + Msg.setIndex((int)id); + dumpMessage(Msg); + triggerSendThread(); + }else { + if (checkNetwork()) { + ICLogger.i(" first send " + Msg); + connection.send(Msg); + } else { + ICLogger.i("offline skip " + Msg); + if (Config.LOG_TOFILE) ICLogger.logToFile( "APILog", " offlineskip " + Msg.cmd()+" "+Msg.isFromCache()); + } + } +} + private static int getMinSignalStrength(int paramInt) { + int b = -105; + switch (paramInt) { + case SimSignalUtil.IS_4G: + b = -100; + break; + case SimSignalUtil.IS_2G: + case SimSignalUtil.IS_3G: + default: + break; + } + return b; + } + + public static PowerManager.WakeLock WakeLockForGetWifiList(Runtime paramRuntime) { + PowerManager.WakeLock wakeLock = ((PowerManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Deliver.class.getSimpleName()); + wakeLock.acquire(120000L); + return wakeLock; + } + + private boolean isSilence(Runtime paramRuntime) { + return SharPreferenceUtil.getPrefBoolean((paramRuntime.getContextProxy()).context, "KEY_ISSILENCE", false); + } + + public static void releaseWakeLockForGetWifiList() { + if (WifiListWakeLock == null) { + ICLogger.i("WifiListWakeLock 没有加锁"); + return; + } + if (WifiListWakeLock.isHeld()) { + WifiListWakeLock.release(); + WifiListWakeLock = null; + } + } + + public PowerManager.WakeLock getWakeLock() { + PowerManager.WakeLock wakeLock = ((PowerManager)(this.mRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Deliver.class.getSimpleName()); + wakeLock.acquire(40000L); + return wakeLock; + } + + public void onAlarmClock(Connection paramConnection, Runtime paramRuntime) {} + + public void onAttach(Connection paramConnection, Runtime paramRuntime) {} + + @Override + public boolean onConnectionClose(Connection paramConnection, Runtime paramRuntime, String ErrorMsg) { + return false; } + + public boolean onConnectionOpen(Connection paramConnection, Runtime paramRuntime) { return false; } + + public void onDetach(Connection paramConnection, Runtime paramRuntime) {} + + public boolean onReceive(StringMessage paramStringMessage, Connection paramConnection, final Runtime paramRuntime) { + this.mConnection = paramConnection; + this.mRuntime = paramRuntime; + String cmd = paramStringMessage.cmd(); + if(Config.protocol_no==Config.PROTOCOL_MQTT) + { + cmd=protocolAPIHelper.isCmdStr(paramStringMessage); + } + //如果需要检测是否响应。 + StringMessage msgWait=mRuntime.getDbHelper().queryWaitCMDRecord(); + dumpMessage(msgWait); + if(msgWait!=null) { + ICLogger.i("====== checkSrvResponse cmd " + cmd + " msg " + protocolAPIHelper.isCmdStr(msgWait)); + if (cmd.equals(protocolAPIHelper.isCmdStr(msgWait))) { + ICLogger.i("checkSrvResponse " + cmd + " " + protocolAPIHelper.isCmdStr(msgWait) + " is responsed!"); + mRuntime.getDbHelper().updateCMDRecord(msgWait.getIndex(), 2);//设置为已读 + CheckCount = 0; + } + } + + ICLogger.i("Deliver receive cmd " + paramStringMessage.cmd()); + if (cmd.equals("SentVoicePacket") ) { + //收到BP07 表示服务器收到一个voicePacket 分包成功,开始检查下一个包是否存在需要发送。 + //收到SentVoicePacket 表示 有一个VoiceMessage要发送,需要从第0个包开始发送语音分包。 + voicePacket voicepacket = voicePacket.getInstanceSent(); + if (voicepacket.getCurrentIndexToSent() < voicepacket.getPacketCount()) { + ICLogger.i("voicepacket " + voicepacket.getName() + " filetype " + voicepacket.getFiletype() + " , datatype " + voicepacket.getDateType() +" "+ voicepacket.getPacketTime() + " send " + (voicepacket.getCurrentIndexToSent() + 1) + "/" + voicepacket.getPacketCount()); + if(mConnection instanceof NettyConnection) { + ((NettyConnection) mConnection).sendMsg("RAWPACKET", + protocolAPIHelper.getVoicePacketItem(voicepacket.getPacketTime(), + voicepacket.getPacketCount(), + (voicepacket.getCurrentIndexToSent() + 1), + voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketLen(), + voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketData(), voicepacket.getFiletype(), voicepacket.getDateType()) + ); + } + } else { + ICLogger.i("voicepacket " + voicepacket.getName() + " filetype " + voicepacket.getFiletype() + " , datatype " + voicepacket.getDateType() + " " + voicepacket.getPacketTime() + " sent Done!"); + } + return true; + } else if ("PhotoRemoteTaken".equals(paramStringMessage.cmd())) { + //接收到拍照完毕命令,发送照片 + + String msgUrl=paramStringMessage.isFromCache(); + ICLogger.i("receive taken photo to send "+msgUrl); + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, "123", msgUrl,2,2); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection()!=null) { + + + //H88 专用功能拍照时检测用户体温心率 + if(Util.getSystemProperties("persist.sys.do_check_condition","false").equals("true")) { + //开启测温 + if(mRuntime.check_stat_do_temp_test()) { + TemperatureUtil.DoTempTest(); + } + + Util.mSleep(5000); + //开启测量PPG + if(mRuntime.check_stat_do_ppg_test()) { + HeartRateManager.triggerPPGtest(); + } + } + + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); + } + return true; + } else if ("poweroffCheckSim".equals(paramStringMessage.cmd())) { + paramRuntime.setShutdown(true); + + if (SimSignalUtil.hasSimCard(paramRuntime.getContextProxy().context)) + { + ICLogger.i("Has Sim Card Skip poweroff!"); + Util.ShowToast(paramRuntime,"Has Sim Card Skip poweroff!"); + return true; + }else{ + Util.ShowToast(paramRuntime,"Do poweroff!"); + } + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + Util.shutdown(); + } + },2000); + return true; + } else if ("FactoryResetCheckSim".equals(paramStringMessage.cmd())) { + + if (SimSignalUtil.hasSimCard(paramRuntime.getContextProxy().context)) + { + ICLogger.i("Has Sim Card Skip FactoryReset!"); + Util.ShowToast(paramRuntime,"Has Sim Card Skip FactoryReset!"); + + return true; + }else{ + Util.ShowToast(paramRuntime,"Do FactoryReset!"); + } + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + Util.doMasterClear(paramRuntime.getContextProxy().context); + } + },2000); + return true; + } else if ("poweroff".equals(paramStringMessage.cmd())) { + paramRuntime.setShutdown(true); + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + Util.shutdown(); + } + },2000); + return true; + } else if ("FactoryReset".equals(paramStringMessage.cmd())) { + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + Util.doMasterClear(paramRuntime.getContextProxy().context); + } + },2000); + return true; + } else if ("Reboot".equals(paramStringMessage.cmd())) { + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + Util.reboot(paramRuntime.getContextProxy().context); + } + },2000); + return true; + } else if ("heartbeat".equals(paramStringMessage.cmd())) { + //每次心跳,查询一下 是否有语音消息需要接收。 +// paramConnection.send(protocolAPIHelper.genStringMessage("AP05",protocolAPIHelper.AP05(true))); + + } else if ("getWeather".equals(paramStringMessage.cmd())) { + ICLogger.i("获取天气"); + mConnection.send(protocolAPIHelper.getWeatherMSG(mRuntime)); + } else if ("NewVoice".equals(paramStringMessage.cmd())) + { + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + final Context context = (Deliver.this.mRuntime.getContextProxy()).context; + + Contact param2Contact = new Contact(CATEGORY_GROUP, (mRuntime.getContextProxy()).context.getResources().getString(R.string.all_group), Contact.GROUP_ALL); + int i = mRuntime.getContextProxy().getTelephonyManager().getCallState(); + if (!mRuntime.getBatteryLow() && 1 != i && 2 != i) { + if (Config.do_broadCast_message) + { + + ICLogger.d(Constants.ACTION_MESSAGE_RECEIVED+" "+paramStringMessage.isFromCache()); + //广播 voice消息 + Intent intent = new Intent(); + intent.setAction(Constants.ACTION_MESSAGE_RECEIVED); + intent.putExtra(Constants.KEY_MESSAGE_TYPE,"voice"); + intent.putExtra(Constants.KEY_MESSAGE_FROM,"广播消息"); + intent.putExtra(Constants.KEY_MESSAGE_URL,paramStringMessage.isFromCache()); + + // playVoice(context,paramStringMessage.isFromCache()); + context.sendBroadcast(intent); + } + + if (Config.noVoiceNotifyDialog==false) { + + Intent intent = new Intent(); + //显示提示窗口 + intent.setAction(DIALOG_ACTION); + intent.putExtra("contact", (Parcelable) param2Contact); + context.sendBroadcast(intent); + } + + } + } + },500); + + return true; + }else if ("findDev".equals(paramStringMessage.cmd())) { + + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + final Context context = (Deliver.this.mRuntime.getContextProxy()).context; + Intent intent = new Intent(); + ICLogger.d(Constants.ACTION_MESSAGE_RECEIVED+" "+paramStringMessage.isFromCache()); + //显示提示窗口 + intent.setAction(DIALOG_ACTION); + intent.putExtra("findDev", "Find Device"); + context.sendBroadcast(intent); + } + },500); + + return true; + }else if ("takephoto".equals(paramStringMessage.cmd())) { + + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + final Context context = (Deliver.this.mRuntime.getContextProxy()).context; + Intent intent = new Intent(); + ICLogger.d(Constants.ACTION_MESSAGE_RECEIVED+" "+paramStringMessage.isFromCache()); + //显示提示窗口 + intent.setAction(DIALOG_ACTION); + intent.putExtra("takephoto", "Take Photo !"); + context.sendBroadcast(intent); + } + },500); + + return true; + + }else if ("StartMonitor".equals(paramStringMessage.cmd())) { + + String recordfilepath=Util.getRecordfilePath(mRuntime, TimeUtil.getSystemTime3()); + int recordtime=Integer.parseInt(paramStringMessage.isFromCache().trim()); + mSendMSGHandler.post(new Runnable() { + @Override + public void run() { + AudioService.getInstance().startRecord(recordfilepath); + } + }); + mSendMSGHandler.postDelayed(new Runnable() { + @Override + public void run() { + AudioService.getInstance().stopRecord(); + ICLogger.i("Monitor Record to send "+recordfilepath); + //创建voiceConent并添加到数据 + /** + * * * 1 语音—— 1.监听语音 * 2.SOS语音 * 3.扩展 + * * * 2 图片—— 1.签到图片 * 2.指令图片 * 3.设备图片 * 4.扩展 + */ + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, "123", recordfilepath,1,1); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection()!=null) + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); + } + },recordtime*1000); + + return true; + } + + return false; + } + + + + private void playVoice(Context paramContext,String voicefile) { + AudioService.getInstance().play(voicefile); + } + + public static void releaseOneWakeLock() { + if (ReceiveWakeLock == null) { + ICLogger.i("ReceiveWakeLock 没有加锁"); + return; + } + if (!wakeLockWifiList && !wakeLockWifiSet && ReceiveWakeLock.isHeld()) { + ReceiveWakeLock.release(); + ReceiveWakeLock = null; + } + } + + public void releaseReceiveWakeLock() { + if (this.ReceiveWakeLock == null) { + ICLogger.i("ReceiveWakeLock 没有加锁"); + return; + } + if (this.ReceiveWakeLock.isHeld()) { + this.ReceiveWakeLock.release(); + this.wakeLockWifiList = false; + this.wakeLockWifiSet = false; + this.ReceiveWakeLock = null; + } + } + public static void connectToWifi(String ssid,String pwd,String encryptType){ + int networkid; + final WifiManager wifiManager = mRuntime.getContextProxy().getWifiManager(); + wifiEnabled = wifiManager.isWifiEnabled(); + if (!wifiEnabled) + { + //没开就打开wifi + Util.turnOnWifiForConnect(mRuntime.getContextProxy().context, mRuntime); + } + if (Util.isConnectWifi(mRuntime.getContextProxy().context)) { + networkid = wifiManager.getConnectionInfo().getNetworkId(); + wifiManager.disconnect(); + wifiManager.removeNetwork(networkid); + wifiManager.saveConfiguration(); + } + + Deliver.isAppSetWifi = 1; + WifiConfiguration wifiConfiguration = Util.GetconfigWifiInfo(mRuntime.getContextProxy().context, ssid, pwd, encryptType); + networkid = wifiConfiguration.networkId; + wifiManager.removeNetwork(networkid); + wifiManager.saveConfiguration(); + networkid = wifiManager.addNetwork(wifiConfiguration); + if (Util.connectWifiByReflectMethod(mRuntime.getContextProxy().context, networkid) == null && !wifiManager.enableNetwork(networkid, true)) { + ICLogger.i("连接失败 3"); + SystemClock.sleep(3000L); + String isUserOpen = Util.getSystemProperties("persist.sys.ic.wifi_enable", "false"); + ICLogger.d("is open by user == > " + isUserOpen); + if ("false".equals(isUserOpen)) { + //用户手动打开的,那么就不关闭wifi了 + wifiManager.setWifiEnabled(false); + } + wakeLockWifiSet = false; + releaseOneWakeLock(); + WifiListWakeLock = Deliver.WakeLockForGetWifiList(mRuntime); + + return; + } + + if(!wifiEnabled ){ + //原来wifi没开就关闭wifi + Util.turnOffWifiForSleep(mRuntime.getContextProxy().context, mRuntime); + } + + } + public void setWakeupAlarm(Runtime paramRuntime) { + AlarmManager alarmManager = (AlarmManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.ALARM_SERVICE); + Intent intent = new Intent((paramRuntime.getContextProxy()).context, CoreService.class); + intent.setAction(ACTION_WAKEUP_ALARM); + PendingIntent pendingIntent = PendingIntent.getService((paramRuntime.getContextProxy()).context, 0, intent, FLAG_UPDATE_CURRENT); + alarmManager.cancel(pendingIntent); + long l = SystemClock.elapsedRealtime(); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("SDK_INT="); + stringBuilder.append(Build.VERSION.SDK_INT); + stringBuilder.append(",m=,"); + stringBuilder.append(23); + stringBuilder.append(",kitkat="); + stringBuilder.append(19); + ICLogger.i(stringBuilder.toString()); + if (Build.VERSION.SDK_INT >= 19) { + alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, l + 10000L, pendingIntent); + return; + } + alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, l + 10000L, pendingIntent); + } + + class ConWifiReceiver extends BroadcastReceiver { + ConWifiReceiver() { + } + + public void onReceive(final Context var1, Intent var2) { + String var3 = var2.getAction(); + StringBuilder var4 = new StringBuilder(); + var4.append(" receive action="); + var4.append(var3); + var4.append(" isAppSetWifi="); + var4.append(Deliver.isAppSetWifi); + ICLogger.i(var4.toString()); + if (var3.equals("android.net.conn.CONNECTIVITY_CHANGE")) { + if (Deliver.isAppSetWifi == 0) { + return; + } + + if (Deliver.isAppSetWifi == 1) { + Deliver.isAppSetWifi = 0; + if (Deliver.this.delayHandler != null) { + Deliver.this.delayHandler.removeCallbacks(Deliver.this.delayTh); + Deliver.this.delayHandler = null; + } + } + + WifiManager var5 = (WifiManager)var1.getSystemService(Context.WIFI_SERVICE); + if (((ConnectivityManager)var1.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { + ICLogger.i("连接成功"); + Deliver.isAppSetWifi = 0; + Deliver.haveSendH42 = true; + Deliver.this.mConnection.connect(Deliver.this.mRuntime.getHost(), Deliver.this.mRuntime.getPort()); + if (Deliver.this.delayHandler != null) { + Deliver.this.delayHandler.removeCallbacks(Deliver.this.delayTh); + Deliver.this.delayHandler = null; + } + + var1.unregisterReceiver(Deliver.this.mMyWifiReceiver); + Deliver.this.mMyWifiReceiver = null; + Deliver.this.wakeLockWifiSet = false; + Deliver.this.releaseOneWakeLock(); + Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); + } else { + StringBuilder var6 = new StringBuilder(); + var6.append("连接失败 222 delayHandler="); + var6.append(Deliver.this.delayHandler); + ICLogger.i(var6.toString()); + Deliver.isAppSetWifi = 2; + var5.reconnect(); + if (Deliver.this.delayHandler == null) { + Deliver.this.delayHandler = new Handler(); + Deliver.this.delayTh = new Runnable() { + public void run() { + StringBuilder var1x = new StringBuilder(); + var1x.append("连接失败 超时 wifiEnabled="); + var1x.append(Deliver.this.wifiEnabled); + ICLogger.i(var1x.toString()); + if (Deliver.isAppSetWifi != 1) { + Deliver.isAppSetWifi = 0; + var1.unregisterReceiver(Deliver.this.mMyWifiReceiver); + Deliver.this.mMyWifiReceiver = null; + WifiManager var3 = (WifiManager)var1.getSystemService(Context.WIFI_SERVICE); + if (((ConnectivityManager)var1.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { + ICLogger.i("连接成功 1"); + Deliver.haveSendH42 = true; + Deliver.this.mConnection.connect(Deliver.this.mRuntime.getHost(), Deliver.this.mRuntime.getPort()); + Deliver.this.wakeLockWifiSet = false; + Deliver.this.releaseOneWakeLock(); + Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); + } else { + int var2 = var3.getConnectionInfo().getNetworkId(); + if (var2 != -1) { + var3.disableNetwork(var2); +// ServiceUtil.offerQueue(API.H42(Deliver.this.mRuntime, "3")); + Deliver.this.wakeLockWifiSet = false; + Deliver.this.releaseOneWakeLock(); + Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); + } else { + ICLogger.i("连接失败 2-2"); +// ServiceUtil.offerQueue(API.H42(Deliver.this.mRuntime, "3")); + Deliver.this.wakeLockWifiSet = false; + Deliver.this.releaseOneWakeLock(); + Deliver.WifiListWakeLock = Deliver.WakeLockForGetWifiList(Deliver.this.mRuntime); + } + + if (!Deliver.this.wifiEnabled) { + var3.setWifiEnabled(false); + } + } + + Deliver.this.delayHandler = null; + } + } + }; + Deliver.this.delayHandler.postDelayed(Deliver.this.delayTh, 30000L); + } + } + } + + } + } + + +} +