From: snickersun Date: Thu, 27 Aug 2020 12:33:51 +0000 (+0800) Subject: mqtt 测试版本第一版, X-Git-Url: http://git.snicker.com.cn/?a=commitdiff_plain;h=a3b6b18097024fd76def63fbad56f2dcb114ff1c;p=protocol_srv.git mqtt 测试版本第一版, 加入mqtt到原来的逻辑中,添加mqtt_connection,QatjaService,等一系列类 目前只有BREQ,KA,UD完成了,还有其他接口没有需改,另外和以前的协议的兼容性也需要测试。 --- diff --git a/app/release/ICSer_V504_2008212009_release.apk b/app/release/ICSer_V504_2008212009_release.apk deleted file mode 100644 index cf14047c..00000000 Binary files a/app/release/ICSer_V504_2008212009_release.apk and /dev/null differ diff --git a/app/release/output.json b/app/release/output.json deleted file mode 100644 index e48e91c3..00000000 --- a/app/release/output.json +++ /dev/null @@ -1 +0,0 @@ -[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":504,"versionName":"2008212009","enabled":true,"outputFile":"ICSer_V504_2008212009_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V504_2008212009_release.apk","properties":{}}] \ No newline at end of file diff --git a/app/src/main/java/com/enqualcomm/support/CoreService.java b/app/src/main/java/com/enqualcomm/support/CoreService.java index 78fadad6..a704cd8f 100644 --- a/app/src/main/java/com/enqualcomm/support/CoreService.java +++ b/app/src/main/java/com/enqualcomm/support/CoreService.java @@ -20,6 +20,8 @@ import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.SleepInfo; import com.enqualcomm.support.bean.SleepRecord; import com.enqualcomm.support.service.AntiMonitorService; +import com.enqualcomm.support.utils.CellInfoUtil; +import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.DeviceInfoUtil; import com.enqualcomm.support.utils.LedUtil; import com.enqualcomm.support.utils.StorageUtils; @@ -27,6 +29,7 @@ import com.enqualcomm.support.utils.TemperatureUtil; import com.enqualcomm.support.utils.TimeUtil; import com.enqualcomm.support.utils.VibrateUtil; import com.enqualcomm.support.utils.WakeLockUtil; +import com.enqualcomm.support.utils.mqttConnection; import com.ic.jni.ICJniUtils; import com.enqualcomm.support.adapter.LBSHelper; import com.ic.protocols.protocolAPIHelper; @@ -271,7 +274,7 @@ public class CoreService extends Service { coreService.locationClient.onReceive(param1StringMessage); } } - NettyConnection connection = null; + Connection connection = null; AbstractConnectionService connectionServiceChain; AbstractInvokeHandlerService invokeHandlerServiceChain; @@ -494,7 +497,7 @@ public class CoreService extends Service { public Runtime getRuntime(){ return runtime; } - public NettyConnection getConnection(){ + public Connection getConnection(){ return connection; } @@ -516,7 +519,12 @@ public class CoreService extends Service { this.runtime.initDnsUtil(ICApplication.getInstance().getApplicationContext()); - connection=new NettyConnection(new ServerHandler(this),runtime); + if (Config.protocol_no==Config.PROTOCOL_MQTT) + { + connection = new mqttConnection(new ServerHandler(this), runtime); + }else { + connection = new NettyConnection(new ServerHandler(this), runtime); + } this.connectionServiceChain = getConnectionServiceChain(); this.invokeHandlerServiceChain = getInvokeHandlerServiceChain(); // if (cmcm_call_eiot_into_powersave_mode() == 1) { @@ -607,7 +615,7 @@ public class CoreService extends Service { //启动inner Service startService(new Intent(this, InnerService.class)); - ReConnectToServer(); + this.locationClient.init(); @@ -703,6 +711,11 @@ public class CoreService extends Service { //备份DB数据到sd cache目录,为调试方便 Util.getDBFile(); // test(); //test function + + //更新IMEI + DeviceInfoUtil.updateImei(runtime); + + ReConnectToServer(); } private void test(){ @@ -812,8 +825,8 @@ public class CoreService extends Service { + " light " + si.getLightsleep_minutes() + " score " + si.getScore() ); - Observable.timer(randomint * 60 * 1000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { +// Observable.timer(randomint * 60 * 1000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { +// public void call(Long param1Long) { // connection.send(protocolAPIHelper); ICLogger.i("Send sleep info " + si.getCurrentDate() + " deep " + si.getDeepsleep_minutes() @@ -821,8 +834,8 @@ public class CoreService extends Service { + " score " + si.getScore() ); Deliver.sendLocationMSG(protocolAPIHelper.getSleepMSG(SleepInfo.getInstance())); - } - }); +// } +// }); } } diff --git a/app/src/main/java/com/enqualcomm/support/LocationClient.java b/app/src/main/java/com/enqualcomm/support/LocationClient.java index a5b917e3..9030867f 100644 --- a/app/src/main/java/com/enqualcomm/support/LocationClient.java +++ b/app/src/main/java/com/enqualcomm/support/LocationClient.java @@ -11,6 +11,7 @@ import android.os.SystemClock; import com.enqualcomm.support.utils.AlarmHelper; import com.enqualcomm.support.adapter.LBSHelper; +import com.enqualcomm.support.utils.Connection; import com.ic.protocols.protocolAPIHelper; import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.StringMessage; @@ -56,7 +57,7 @@ public class LocationClient { private static final int TIME_OUT = 30000; - private static NettyConnection connection; + private static Connection connection; private static boolean isLocationCallBack = false; @@ -113,7 +114,7 @@ public class LocationClient { public static LocationClient getInstance(){ return gLocationCline; } - public LocationClient(NettyConnection paramNettyConnection, Runtime paramRuntime) { + public LocationClient(Connection paramNettyConnection, Runtime paramRuntime) { connection = paramNettyConnection; runtime = paramRuntime; @@ -363,10 +364,10 @@ public class LocationClient { }else { if (gps_ok) { - String AP01_CMD = protocolAPIHelper.getGPSLocationMSG(runtime); + StringMessage AP01_CMD = protocolAPIHelper.getGPSLocationMSG(runtime); Deliver.sendLocationMSG(AP01_CMD); }else{ - String AP02_CMD = protocolAPIHelper.getLBSLocationMSG(runtime); + StringMessage AP02_CMD = protocolAPIHelper.getLBSLocationMSG(runtime); Deliver.sendLocationMSG(AP02_CMD); } @@ -436,7 +437,7 @@ public class LocationClient { startSOSLocation=false; }else { - String AP02_CMD = protocolAPIHelper.getLBSLocationMSG(runtime); + StringMessage AP02_CMD = protocolAPIHelper.getLBSLocationMSG(runtime); Deliver.sendLocationMSG(AP02_CMD); } diff --git a/app/src/main/java/com/enqualcomm/support/bean/BLEInfo.java b/app/src/main/java/com/enqualcomm/support/bean/BLEInfo.java new file mode 100644 index 00000000..7f09f530 --- /dev/null +++ b/app/src/main/java/com/enqualcomm/support/bean/BLEInfo.java @@ -0,0 +1,16 @@ +package com.enqualcomm.support.bean; + +import java.util.ArrayList; +import java.util.List; + +public class BLEInfo { + public String ble_area_id=""; + + public ArrayList btMacList=new ArrayList<>(); + + public String gps_n=""; + public String gps_e=""; + public boolean is_in_area=false; + + +} diff --git a/app/src/main/java/com/enqualcomm/support/bean/Runtime.java b/app/src/main/java/com/enqualcomm/support/bean/Runtime.java index feb4951f..6347e1ef 100644 --- a/app/src/main/java/com/enqualcomm/support/bean/Runtime.java +++ b/app/src/main/java/com/enqualcomm/support/bean/Runtime.java @@ -26,6 +26,7 @@ public class Runtime { public TemperatureInfo tempInfo=new TemperatureInfo(); public boolean BindingStatus=false; + public BLEInfo bleInfo=new BLEInfo(); private String battery="000"; private int batteryVoltage=0; 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 7de47051..4618156a 100644 --- a/app/src/main/java/com/enqualcomm/support/service/Deliver.java +++ b/app/src/main/java/com/enqualcomm/support/service/Deliver.java @@ -71,7 +71,7 @@ public class Deliver extends AbstractConnectionService { public static LinkedBlockingDeque queue = new LinkedBlockingDeque(200); private static FileCache fileCache; - private static NettyConnection connection; + private static Connection connection; public static boolean is_active_location = false; @@ -111,7 +111,7 @@ public class Deliver extends AbstractConnectionService { } }; } - public Deliver(NettyConnection paramNettyConnection, Runtime paramRuntime) { + public Deliver(Connection paramNettyConnection, Runtime paramRuntime) { connection = paramNettyConnection; mRuntime = paramRuntime; //把queue 保存在磁盘中的缓存文件 @@ -149,10 +149,11 @@ public class Deliver extends AbstractConnectionService { } private static boolean NeedCheckServerResponse=true; private static boolean ServerResponsed=false; - private static String needCheckResponseCMD=null; + private static StringMessage needCheckResponseCMD=null; private static int CheckCount=0; - private static void checkNeedServerResponse(String cmd){ + private static void checkNeedServerResponse(StringMessage cmd){ + if (cmd!=null && Config.protocol_no==Config.PROTOCOL_FZD && (protocolAPIHelper.isCmdStr(cmd).equals("UD") || protocolAPIHelper.isCmdStr(cmd).equals("UD2"))){ NeedCheckServerResponse=false; @@ -182,20 +183,20 @@ public class Deliver extends AbstractConnectionService { //刚刚发送的包不为空,且检测次数小于3,则保留数据,进行下一次重试。 if (needCheckResponseCMD!=null && CheckCount < 3) { //如果cmd有效,且尝试次数小于3, 没有收到反馈的情况下,可以重新插入queue进行下一次尝试! - ICLogger.i("checkSrvResponse "+CheckCount+" times for "+needCheckResponseCMD); - if (!ServiceUtil.offerQueue(new StringMessage(needCheckResponseCMD), true)) { - ICLogger.i("checkSrvResponse failed ,重新添加MessageQueue 已满,数据将被丢弃!" + needCheckResponseCMD); + ICLogger.i("checkSrvResponse "+CheckCount+" times for "+needCheckResponseCMD.cmd()+ " "+needCheckResponseCMD.isFromCache()); + if (!ServiceUtil.offerQueue(needCheckResponseCMD, true)) { + ICLogger.i("checkSrvResponse failed ,重新添加MessageQueue 已满,数据将被丢弃!" + needCheckResponseCMD.cmd()+ " "+needCheckResponseCMD.isFromCache()); if (Config.LOG_TOFILE) - ICLogger.logToFile("APILog", "response failed queueFullskip! " + needCheckResponseCMD); + ICLogger.logToFile("APILog", "response failed queueFullskip! " + needCheckResponseCMD.cmd()+ " "+needCheckResponseCMD.isFromCache()); }else{ if (Config.LOG_TOFILE) - ICLogger.logToFile("APILog", "response failed retry ! " +CheckCount+" " + needCheckResponseCMD); + ICLogger.logToFile("APILog", "response failed retry ! " +CheckCount+" " + needCheckResponseCMD.cmd()+ " "+needCheckResponseCMD.isFromCache()); } CheckCount++; }else{ //否则 可能是还没有发送过数据,或者超过重试次数,继续提取queue中数据进行发送 ICLogger.i("checkSrvResponse CheckCount="+CheckCount+" Timeout or cmd is null, skip "); if (Config.LOG_TOFILE) - ICLogger.logToFile("APILog", "response timeout skip! " + needCheckResponseCMD); + ICLogger.logToFile("APILog", "response timeout skip! " ); CheckCount=0; } } @@ -206,12 +207,15 @@ public class Deliver extends AbstractConnectionService { StringMessage stringMessage = queue.poll(); if (stringMessage != null) { String cmd = stringMessage.isFromCache(); + String topci = stringMessage.cmd(); + stringBuilder.append(topci); + stringBuilder.append(" "); stringBuilder.append(cmd); stringBuilder.append("\n"); if (checkNetwork()) { - connection.sendMsg(cmd); + connection.send(stringMessage); // stringMessage = queue.poll(); - needCheckResponseCMD=cmd; + needCheckResponseCMD=stringMessage; //如果需要Check if (NeedCheckServerResponse==true){ ICLogger.i("checkSrvResponse "+cmd); @@ -245,26 +249,35 @@ public class Deliver extends AbstractConnectionService { return ret; } -public static void sendLocationMSG( String Msg){ + + 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()){ - if(!ServiceUtil.offerQueue(protocolAPIHelper.genStringMessage("queue",Msg))) { - ICLogger.i(" MessageQueue 已满,数据将被丢弃," + Msg); - if (Config.LOG_TOFILE)ICLogger.logToFile( "APILog", " queueFullskip " + Msg); + if(!ServiceUtil.offerQueue(Msg)) { + ICLogger.i(" MessageQueue 已满,数据将被丢弃," + Msg.cmd()+" "+Msg.isFromCache()); + if (Config.LOG_TOFILE)ICLogger.logToFile( "APILog", " queueFullskip " + Msg.cmd()+" "+Msg.isFromCache()); } // if(queue.size()>5) //测试queue 发送逻辑用 triggerSendThread(); }else { if (checkNetwork()) { ICLogger.i(" first send " + Msg); - connection.send(protocolAPIHelper.genStringMessage("queue",Msg)); + connection.send(Msg); } else { ICLogger.i("offline skip " + Msg); - if (Config.LOG_TOFILE) ICLogger.logToFile( "APILog", " offlineskip " + Msg); + if (Config.LOG_TOFILE) ICLogger.logToFile( "APILog", " offlineskip " + Msg.cmd()+" "+Msg.isFromCache()); } } } @@ -344,13 +357,15 @@ public static void sendLocationMSG( String Msg){ 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()); - ((NettyConnection) mConnection).sendMsg( - protocolAPIHelper.getVoicePacketItem(voicepacket.getPacketTime(), - voicepacket.getPacketCount(), - (voicepacket.getCurrentIndexToSent() + 1), - voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketLen(), - voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketData(), voicepacket.getFiletype(), voicepacket.getDateType()) - ); + 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!"); } 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..67639c63 100644 --- a/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java +++ b/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java @@ -48,7 +48,7 @@ public class HeartRateManager extends AbstractInvokeHandlerService implements Se private SimSignalUtil mSignalUtil; private Runtime runtime; - private NettyConnection connection; + private Connection connection; private ScheduledThreadPoolExecutor timerPPG=null; private static Handler mHandler=null; @@ -95,7 +95,7 @@ public class HeartRateManager extends AbstractInvokeHandlerService implements Se } } - public HeartRateManager(Runtime _runtime,NettyConnection _connection){ + public HeartRateManager(Runtime _runtime,Connection _connection){ runtime=_runtime; connection=_connection; currentStat= heartRateStatus.HEARTRATE_WORKINGSTAT.HEARTRATE_CLOSED; @@ -414,7 +414,7 @@ public static void triggerPPGtest(){ } - if (((NettyConnection) connection).isServerConnected()) { + if (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)); diff --git a/app/src/main/java/com/enqualcomm/support/service/Initialize.java b/app/src/main/java/com/enqualcomm/support/service/Initialize.java index 9a6884c4..9cd1b7f0 100644 --- a/app/src/main/java/com/enqualcomm/support/service/Initialize.java +++ b/app/src/main/java/com/enqualcomm/support/service/Initialize.java @@ -76,7 +76,7 @@ public class Initialize extends AbstractConnectionService { Config.loadServerSettings(paramRuntime); //发送登录包 - paramConnection.send(new StringMessage(protocolAPIHelper.getLoginMSG(paramRuntime))); + paramConnection.send(protocolAPIHelper.getLoginMSG(paramRuntime)); return false; diff --git a/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java b/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java index f11fb3f7..c123011d 100644 --- a/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java +++ b/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java @@ -111,16 +111,16 @@ public class KeepAlive extends AbstractConnectionService { boolean ret=DeviceInfoUtil.updateImei(mRuntime); ICLogger.i("Update IMEI "+ret); if (is_login_send_success) { - connection.send(protocolAPIHelper.genStringMessage("heartbeat", protocolAPIHelper.getHeartbeatMSG(mRuntime))); + connection.send(protocolAPIHelper.getHeartbeatMSG(mRuntime)); Observable.timer(1000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { public void call(Long param1Long) { - connection.send(protocolAPIHelper.genStringMessage("binding", protocolAPIHelper.getBindingMSG())); + connection.send(protocolAPIHelper.getBindingMSG(mRuntime)); } }); } else - connection.send(protocolAPIHelper.genStringMessage("heartbeat", protocolAPIHelper.getLoginMSG(mRuntime))); + connection.send(protocolAPIHelper.getLoginMSG(mRuntime)); } } @@ -263,7 +263,7 @@ public class KeepAlive extends AbstractConnectionService { is_login_send_success=false; Observable.timer(500L, TimeUnit.MILLISECONDS).subscribe(new Action1() { public void call(Long param1Long) { - connection.send(protocolAPIHelper.genStringMessage("login",protocolAPIHelper.getLoginMSG(paramRuntime))); + connection.send(protocolAPIHelper.getLoginMSG(paramRuntime)); } }); @@ -283,7 +283,7 @@ public class KeepAlive extends AbstractConnectionService { this.mContext.unregisterReceiver(this.mShutDownReceiver); } - public void onHeartAlarm(NettyConnection paramNettyConnection, Runtime paramRuntime) { + public void onHeartAlarm(Connection paramNettyConnection, Runtime paramRuntime) { ICLogger.i("onHeartAlarm"); stopResponseCheckTimer(); @@ -292,11 +292,11 @@ public class KeepAlive extends AbstractConnectionService { //这个是正常心跳包,暂时不能认为服务器连接时失败的,所以正常发送检测。 //发送心跳包 - connection.send(protocolAPIHelper.genStringMessage("heartbeat",protocolAPIHelper.getHeartbeatMSG(paramRuntime))); + connection.send(protocolAPIHelper.getHeartbeatMSG(paramRuntime)); //发送完心跳后,开始检查服务器响应 Observable.timer(1000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { public void call(Long param1Long) { - connection.send(protocolAPIHelper.genStringMessage("binding", protocolAPIHelper.getBindingMSG())); + connection.send(protocolAPIHelper.getBindingMSG(mRuntime)); } }); startResponseCheckTimer(); @@ -338,11 +338,11 @@ public class KeepAlive extends AbstractConnectionService { public void call(Long param1Long) { //这时重新连接服务器才进行的连接,理论上close已经设置false,此次可以认为协议定然断开,所以设置为false作为双重保险。 mRuntime.setServerProtocolConnected(false); - connection.send(protocolAPIHelper.genStringMessage("heartbeat",protocolAPIHelper.getHeartbeatMSG(paramRuntime))); + connection.send(protocolAPIHelper.getHeartbeatMSG(paramRuntime)); //发送完心跳后,开始检查服务器响应 Observable.timer(1000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { public void call(Long param1Long) { - connection.send(protocolAPIHelper.genStringMessage("binding", protocolAPIHelper.getBindingMSG())); + connection.send(protocolAPIHelper.getBindingMSG(mRuntime)); } }); diff --git a/app/src/main/java/com/enqualcomm/support/service/SendChatMessage.java b/app/src/main/java/com/enqualcomm/support/service/SendChatMessage.java index 637e3be3..f9b28278 100644 --- a/app/src/main/java/com/enqualcomm/support/service/SendChatMessage.java +++ b/app/src/main/java/com/enqualcomm/support/service/SendChatMessage.java @@ -154,7 +154,7 @@ public class SendChatMessage extends AbstractInvokeHandlerService { // 把voiceContent拆解成1024的分包 Util.parseToVoicePacketSent(voiceContent); //trigger 分包发送 - ((NettyConnection) paramConnection).DeliverCMDMessageToSystem("SentVoicePacket", ""); + paramConnection.DeliverCMDMessageToSystem("SentVoicePacket", ""); case 1000: break; diff --git a/app/src/main/java/com/enqualcomm/support/utils/Connection.java b/app/src/main/java/com/enqualcomm/support/utils/Connection.java index 2106dd0d..046eeba9 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/Connection.java +++ b/app/src/main/java/com/enqualcomm/support/utils/Connection.java @@ -8,7 +8,8 @@ public interface Connection { void connect(String paramString, int paramInt); void disconnect(); - + boolean disconnectServer(); + int getTimeout(); void open(); @@ -18,5 +19,9 @@ public interface Connection { boolean sendBlocking(StringMessage paramStringMessage); void setTimeout(int paramInt); + + void DeliverCMDMessageToSystem(String cmd,String msg); + + boolean isServerConnected(); } 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..3674458a 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java +++ b/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java @@ -4,6 +4,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; +import android.util.Log; import com.enqualcomm.support.Config; @@ -35,9 +36,10 @@ public class NettyConnection implements Connection { private int timeout = 60; public NettyConnection(ConnectionListener paramConnectionListener,Runtime runtime) { + Log.i(TAG, "NettyConnection "); this.listener = paramConnectionListener; - if (API == null) API=new protocolAPIHelper(NettyConnection.this,runtime ); + if (API == null) API=new protocolAPIHelper(this,runtime ); initReadListener(); init_connection_listener(); @@ -168,7 +170,13 @@ public class NettyConnection implements Connection { return true; } - public boolean sendMsg(byte[] cmdArray) { + + public boolean sendMsg(String cmdtype,byte[] cmdArray) { + log(cmdtype); + return sendMsg(cmdArray); + + } + public boolean sendMsg(byte[] cmdArray) { if( cmdArray==null || cmdArray.length==0) { @@ -209,11 +217,11 @@ public class NettyConnection implements Connection { public void DeliverCMDMessageToSystem(String cmd,String msg){ - if (NettyConnection.this.listener!=null){ + if (this.listener!=null){ String[] msgArr=new String[]{cmd,msg}; StringMessage stringMessage=new StringMessage(msgArr); stringMessage.refresh(msg); - NettyConnection.this.listener.onReceive(stringMessage ); + this.listener.onReceive(stringMessage ); } } @@ -265,7 +273,7 @@ public class NettyConnection implements Connection { String msg= new String(bytes); log("get Msg :"+msg+" (size) byteslen" + bytes.length +" strlen"+ msg.length()); - API.parserCmd(bytes); + API.parserCmd("",bytes); } return false; @@ -281,12 +289,12 @@ public class NettyConnection implements Connection { .subscribe(socketStatus -> { log("socketStatusListener socketStatus:" + socketStatus.name()); if (socketStatus.name().equals("CONNECTED")){ - if (NettyConnection.this.listener!=null){ - NettyConnection.this.listener.onConnectionOpen(); + if (this.listener!=null){ + 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()); + if (this.listener!=null){ + this.listener.onConnectionClose(socketStatus.name()); } disconnectServer(); } diff --git a/app/src/main/java/com/enqualcomm/support/utils/mqttConnection.java b/app/src/main/java/com/enqualcomm/support/utils/mqttConnection.java new file mode 100644 index 00000000..c44a006d --- /dev/null +++ b/app/src/main/java/com/enqualcomm/support/utils/mqttConnection.java @@ -0,0 +1,142 @@ +package com.enqualcomm.support.utils; + +import android.util.Log; + +import com.enqualcomm.support.bean.Runtime; +import com.enqualcomm.support.bean.StringMessage; +import com.ic.protocols.protocolAPIHelper; +import com.ic.protocols.protocol_mqtt_client; + +public class mqttConnection implements Connection { + private String topic_header=""; + private protocol_mqtt_client.MqttCallbackInterface mqttcallback=new protocol_mqtt_client.MqttCallbackInterface() { + @Override + public void onMqttConnected() { + ICLogger.i( "onMqttConnected"); + topic_header="WBG100/v1/"+mRuntime.IMEI()+"/"; + ICLogger.i( "topic_header "+topic_header); + mqtt_client.setSubscriptTopicHeader(topic_header); + mqtt_client.attemptSubscribeToTopic(topic_header+"+"); + isServerconnected=true; + mRuntime.setServerProtocolConnected(true); + if (listener!=null) + listener.onConnectionOpen(); + + } + + @Override + public void onMqttDisconnected() { + ICLogger.i( "onMqttDisconnected"); + isServerconnected=false; + mRuntime.setServerProtocolConnected(false); + if (listener!=null) + listener.onConnectionClose(""); + } + + @Override + public void handleMqttMessage(String cmdtype, byte[] msgdata) { + ICLogger.i( "handleMqttMessage "+cmdtype+" " +new String(msgdata)); + API.parserCmd(cmdtype,msgdata); + } + + @Override + public void handleMqttMessage(String cmdtype, String msgdata) { + ICLogger.i( "handleMqttMessage "+cmdtype+" "+ msgdata); + API.parserCmd(cmdtype,msgdata.getBytes()); + } + }; + public mqttConnection(ConnectionListener paramConnectionListener, Runtime runtime) { + ICLogger.i("mqttConnection "); + mqtt_client=new protocol_mqtt_client(runtime.getContextProxy().context,mqttcallback); + listener=paramConnectionListener; + mRuntime=runtime; + if (API == null) API=new protocolAPIHelper(this,runtime ); + + } + private Runtime mRuntime=null; + private protocol_mqtt_client mqtt_client=null; + + private static boolean isServerconnected=false; + private protocolAPIHelper API=null; + private ConnectionListener listener=null; + @Override + public void close(){ + + } + + @Override + public void connect(String paramString, int paramInt){ +// mqtt_client.attemptConnectMqtt(paramString,"IC_"+mRuntime.IMEI(),paramInt); + ICLogger.i("mqttconnect " +paramString+" "+paramInt); + mqtt_client.configMqtt(paramString,paramInt,"IC_"+mRuntime.IMEI()); + mqtt_client.connectservice(); + // if(isServerconnected) mqtt_client.attemptConnectMqtt(); + } + + @Override + public void disconnect(){ + disconnectServer(); + } + + @Override + public boolean disconnectServer() { + mqtt_client.disconnect(); + return true; + } + + @Override + public int getTimeout(){ + + return 0; + } + + @Override + public void open(){ + + } + + @Override + public void send(StringMessage paramStringMessage){ + + if(paramStringMessage==null) + { + ICLogger.i("send StringMessage Null skip!"); + return; + } + String topci=paramStringMessage.cmd(); + String msgdata=paramStringMessage.isFromCache(); + if (topci.startsWith("WBG100/v1")) { + mqtt_client.sendMessage(topci, msgdata); + ICLogger.logToFile("API","send "+topci+" "+msgdata); + }else{ + ICLogger.i("topci foramt error "+topci); + } + } + + @Override + public boolean sendBlocking(StringMessage paramStringMessage){ + send(paramStringMessage); + return true; + } + + @Override + public void setTimeout(int paramInt){ + + } + + @Override + public void DeliverCMDMessageToSystem(String cmd, String msg) { + if (this.listener!=null){ + String[] msgArr=new String[]{cmd,msg}; + StringMessage stringMessage=new StringMessage(msgArr); + stringMessage.refresh(msg); + this.listener.onReceive(stringMessage ); + } + } + + @Override + public boolean isServerConnected() { + return isServerconnected; + } + +} diff --git a/app/src/main/java/com/ic/protocols/protocolAPIHelper.java b/app/src/main/java/com/ic/protocols/protocolAPIHelper.java index f1d52dec..40a1ba10 100644 --- a/app/src/main/java/com/ic/protocols/protocolAPIHelper.java +++ b/app/src/main/java/com/ic/protocols/protocolAPIHelper.java @@ -4,8 +4,8 @@ import com.enqualcomm.support.Config; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.bean.SleepInfo; import com.enqualcomm.support.bean.StringMessage; +import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.ICLogger; -import com.enqualcomm.support.utils.NettyConnection; public class protocolAPIHelper { @@ -16,7 +16,7 @@ public class protocolAPIHelper { private static protocol_fzd protocolfzd_handler=null; private static protocol_mqtt protocolmqtt_handler=null; - public protocolAPIHelper(NettyConnection connect,Runtime runtime) { + public protocolAPIHelper(Connection connect, Runtime runtime) { ICLogger.i("init Protocol "+Config.getProtocolNumber()); if (protocolbeehome_handler==null) protocolbeehome_handler=new protocol_beehome(connect,runtime); @@ -40,7 +40,7 @@ public class protocolAPIHelper { 字符串通过#号进行识别。 每个字符串如果发现 #,却又没有Header,“IW”则会被丢弃 */ - public boolean parserCmd(byte[] bytes) { + public boolean parserCmd(String cmd_type,byte[] bytes) { if (is_protocol_not_Initialled()) return false; switch(Config.protocol_no) { @@ -57,11 +57,16 @@ public class protocolAPIHelper { protocolfzd_handler.parserCmd(bytes); break; case Config.PROTOCOL_MQTT: - protocolmqtt_handler.parserCmd(bytes); + protocolmqtt_handler.parserCmd(cmd_type,bytes); break; } return true; } + public static StringMessage genStringMessage(String cmdName, byte[] rawdata){ + StringMessage sm=new StringMessage(new String[]{cmdName,new String(rawdata) }); + + return sm; + } public static StringMessage genStringMessage(String cmdName, String msg){ StringMessage sm=new StringMessage(new String[]{cmdName,msg}); sm.refresh(msg); @@ -69,22 +74,22 @@ public class protocolAPIHelper { } - public static String isCmdStr(String msg){ + public static String isCmdStr(StringMessage msg){ if (is_protocol_not_Initialled()) return ""; String ret=""; switch(Config.protocol_no) { case Config.PROTOCOL_JIAI: - ret=protocol_jiai.isCmdStr(msg); + ret=protocol_jiai.isCmdStr(msg.isFromCache()); break; case Config.PROTOCOL_BEEHOME: - ret=protocol_beehome.isCmdStr(msg); + ret=protocol_beehome.isCmdStr(msg.isFromCache()); break; case Config.PROTOCOL_IC: - ret=protocol_ic.isCmdStr(msg); + ret=protocol_ic.isCmdStr(msg.isFromCache()); break; case Config.PROTOCOL_FZD: - ret=protocol_fzd.isCmdStr(msg); + ret=protocol_fzd.isCmdStr(msg.isFromCache()); break; case Config.PROTOCOL_MQTT: ret=protocol_mqtt.isCmdStr(msg); @@ -93,25 +98,25 @@ public class protocolAPIHelper { return ret; } - public static String getBindingMSG(){ - if (is_protocol_not_Initialled()) return ""; - String ret=""; + public static StringMessage getBindingMSG(Runtime runtime){ + if (is_protocol_not_Initialled()) return null; + StringMessage ret=null; switch(Config.protocol_no) { case Config.PROTOCOL_JIAI: - ret=""; + ret=null; break; case Config.PROTOCOL_BEEHOME: - ret=""; + ret=null; break; case Config.PROTOCOL_IC: - ret=""; + ret=null; break; case Config.PROTOCOL_FZD: - ret=protocol_fzd.PING(); + ret=genStringMessage("PING",protocol_fzd.PING()); break; case Config.PROTOCOL_MQTT: - ret=""; + ret=null; break; } return ret; @@ -135,7 +140,7 @@ public class protocolAPIHelper { ret=protocol_fzd.temp(body_temp); break; case Config.PROTOCOL_MQTT: - ret=protocol_mqtt.temp(body_temp); + ret=""; break; } return ret; @@ -164,46 +169,46 @@ public class protocolAPIHelper { return ret; } - public static String getLoginMSG(Runtime runtime){ - if (is_protocol_not_Initialled()) return ""; - String ret=""; + public static StringMessage getLoginMSG(Runtime runtime){ + if (is_protocol_not_Initialled()) return null; + StringMessage ret=null; switch(Config.protocol_no) { case Config.PROTOCOL_JIAI: - ret=protocol_jiai.AP00(runtime); + ret=genStringMessage("AP00",protocol_jiai.AP00(runtime)); break; case Config.PROTOCOL_BEEHOME: - ret=protocol_beehome.AP00(runtime); + ret=genStringMessage("AP00",protocol_beehome.AP00(runtime)); break; case Config.PROTOCOL_IC: - ret=protocol_ic.AP00(runtime); + ret=genStringMessage("AP00",protocol_ic.AP00(runtime)); break; case Config.PROTOCOL_FZD: - ret=protocol_fzd.LK(); + ret=genStringMessage("AP00",protocol_fzd.LK()); break; case Config.PROTOCOL_MQTT: - ret=""; + ret=protocol_mqtt.BREQ(runtime); break; } return ret; } - public static String getHeartbeatMSG(Runtime runtime){ - if (is_protocol_not_Initialled()) return ""; - String ret=""; + public static StringMessage getHeartbeatMSG(Runtime runtime){ + if (is_protocol_not_Initialled()) return null; + StringMessage ret=null; switch(Config.protocol_no) { case Config.PROTOCOL_JIAI: - ret=protocol_jiai.AP03(runtime); + ret=genStringMessage("AP03",protocol_jiai.AP03(runtime)); break; case Config.PROTOCOL_BEEHOME: - ret=protocol_beehome.AP03(runtime); + ret=genStringMessage("AP03",protocol_beehome.AP03(runtime)); break; case Config.PROTOCOL_IC: - ret=protocol_ic.AP03(runtime); + ret=genStringMessage("AP03",protocol_ic.AP03(runtime)); break; case Config.PROTOCOL_FZD: - ret=protocol_fzd.KA(runtime); + ret=genStringMessage("KA",protocol_fzd.KA(runtime)); break; case Config.PROTOCOL_MQTT: ret=protocol_mqtt.KA(runtime); @@ -212,22 +217,22 @@ public class protocolAPIHelper { return ret; } - public static String getGPSLocationMSG(Runtime runtime){ - if (is_protocol_not_Initialled()) return ""; - String ret=""; + public static StringMessage getGPSLocationMSG(Runtime runtime){ + if (is_protocol_not_Initialled()) return null; + StringMessage ret=null; switch(Config.protocol_no) { case Config.PROTOCOL_JIAI: - ret=protocol_jiai.AP01(runtime); + ret=genStringMessage("AP01",protocol_jiai.AP01(runtime)); break; case Config.PROTOCOL_BEEHOME: - ret=protocol_beehome.AP01(runtime); + ret=genStringMessage("AP01",protocol_beehome.AP01(runtime)); break; case Config.PROTOCOL_IC: - ret=protocol_ic.AP01(runtime); + ret=genStringMessage("AP01",protocol_ic.AP01(runtime)); break; case Config.PROTOCOL_FZD: - ret=protocol_fzd.UD(runtime); + ret=genStringMessage("UD",protocol_fzd.UD(runtime)); break; case Config.PROTOCOL_MQTT: ret=protocol_mqtt.UD(runtime); @@ -235,22 +240,22 @@ public class protocolAPIHelper { } return ret; } - public static String getLBSLocationMSG(Runtime runtime){ - if (is_protocol_not_Initialled()) return ""; - String ret=""; + public static StringMessage getLBSLocationMSG(Runtime runtime){ + if (is_protocol_not_Initialled()) return null; + StringMessage ret=null; switch(Config.protocol_no) { case Config.PROTOCOL_JIAI: - ret=protocol_jiai.AP02(runtime); + ret=genStringMessage("AP02",protocol_jiai.AP02(runtime)); break; case Config.PROTOCOL_BEEHOME: - ret=protocol_beehome.AP02(runtime); + ret=genStringMessage("AP02",protocol_beehome.AP02(runtime)); break; case Config.PROTOCOL_IC: - ret=protocol_ic.AP02(runtime); + ret=genStringMessage("AP02",protocol_ic.AP02(runtime)); break; case Config.PROTOCOL_FZD: - ret=protocol_fzd.UD(runtime); + ret=genStringMessage("UD",protocol_fzd.UD(runtime)); break; case Config.PROTOCOL_MQTT: ret=protocol_mqtt.UD(runtime); @@ -347,7 +352,7 @@ public class protocolAPIHelper { ret=protocol_fzd.blood(pbl,pbh); break; case Config.PROTOCOL_MQTT: - ret=protocol_mqtt.blood(pbl,pbh); + ret="";//protocol_mqtt.blood(pbl,pbh); break; } return ret; @@ -371,7 +376,7 @@ public class protocolAPIHelper { ret=protocol_fzd.oxygen(ox); break; case Config.PROTOCOL_MQTT: - ret=protocol_mqtt.oxygen(ox); + ret="";//protocol_mqtt.oxygen(ox); break; } return ret; @@ -394,7 +399,7 @@ public class protocolAPIHelper { ret=protocol_fzd.heart(ppg); break; case Config.PROTOCOL_MQTT: - ret=protocol_mqtt.heart(ppg); + ret="";//protocol_mqtt.heart(ppg); break; } return ret; diff --git a/app/src/main/java/com/ic/protocols/protocol_beehome.java b/app/src/main/java/com/ic/protocols/protocol_beehome.java index a8ff2bb6..1d1d37dd 100644 --- a/app/src/main/java/com/ic/protocols/protocol_beehome.java +++ b/app/src/main/java/com/ic/protocols/protocol_beehome.java @@ -18,7 +18,6 @@ import com.enqualcomm.support.bean.voicePacket; import com.enqualcomm.support.service.HeartRateManager; import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.ICLogger; -import com.enqualcomm.support.utils.NettyConnection; import com.enqualcomm.support.utils.TemperatureUtil; import com.enqualcomm.support.utils.TimeUtil; import com.enqualcomm.support.utils.Util; @@ -203,10 +202,10 @@ public class protocol_beehome { } - private NettyConnection mConnection=null; + private Connection mConnection=null; private Runtime mRuntime=null; - public protocol_beehome(NettyConnection connect,Runtime runtime) { + public protocol_beehome(Connection connect,Runtime runtime) { mConnection=connect; mRuntime=runtime; @@ -970,7 +969,7 @@ public class protocol_beehome { } - public void handleBP07(String cmd , NettyConnection connection ){ + public void handleBP07(String cmd , Connection connection ){ //平台响应: IWBP07,20140818064408,6,1,1# //20140818064408:设备语音时间,yyyyMMddHHmmss 格式的年月日时分秒 //6:语音包分包总数 @@ -1316,7 +1315,7 @@ public class protocol_beehome { } //处理 BP28 语音消息 - public void handleBP28(NettyConnection connection,String cmd,Runtime runtime,byte[] bytes) { + public void handleBP28(Connection connection,String cmd,Runtime runtime,byte[] bytes) { //log("handleBP28 msg"+cmd); /** * IWBP28, D3590D54,XXXX,6,1,1024,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX# diff --git a/app/src/main/java/com/ic/protocols/protocol_fzd.java b/app/src/main/java/com/ic/protocols/protocol_fzd.java index 3cb26339..05945054 100644 --- a/app/src/main/java/com/ic/protocols/protocol_fzd.java +++ b/app/src/main/java/com/ic/protocols/protocol_fzd.java @@ -21,7 +21,6 @@ import com.enqualcomm.support.service.HeartRateManager; import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.ICLogger; import com.enqualcomm.support.utils.MD5; -import com.enqualcomm.support.utils.NettyConnection; import com.enqualcomm.support.utils.TemperatureUtil; import com.enqualcomm.support.utils.TimeUtil; import com.enqualcomm.support.utils.Util; @@ -145,10 +144,10 @@ public class protocol_fzd { cmdMap.put(CMD_TYPE.heart, "heart"); } - private NettyConnection mConnection=null; + private Connection mConnection=null; private Runtime mRuntime=null; - public protocol_fzd(NettyConnection connect, Runtime runtime) { + public protocol_fzd(Connection connect, Runtime runtime) { mConnection=connect; mRuntime=runtime; diff --git a/app/src/main/java/com/ic/protocols/protocol_ic.java b/app/src/main/java/com/ic/protocols/protocol_ic.java index b056e68f..ba69aa52 100644 --- a/app/src/main/java/com/ic/protocols/protocol_ic.java +++ b/app/src/main/java/com/ic/protocols/protocol_ic.java @@ -21,7 +21,6 @@ import com.enqualcomm.support.service.HeartRateManager; import com.enqualcomm.support.utils.CameraUtil; import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.ICLogger; -import com.enqualcomm.support.utils.NettyConnection; import com.enqualcomm.support.utils.TemperatureUtil; import com.enqualcomm.support.utils.TimeUtil; import com.enqualcomm.support.utils.Util; @@ -240,10 +239,10 @@ public class protocol_ic { } - private NettyConnection mConnection=null; + private Connection mConnection=null; private Runtime mRuntime=null; - public protocol_ic(NettyConnection connect, Runtime runtime) { + public protocol_ic(Connection connect, Runtime runtime) { mConnection=connect; mRuntime=runtime; @@ -1016,7 +1015,7 @@ public class protocol_ic { } - public void handleBP07(String cmd , NettyConnection connection ){ + public void handleBP07(String cmd , Connection connection ){ //平台响应: IWBP07,20140818064408,6,1,1# //20140818064408:设备语音时间,yyyyMMddHHmmss 格式的年月日时分秒 //6:语音包分包总数 @@ -1362,7 +1361,7 @@ public class protocol_ic { } //处理 BP28 语音消息 - public void handleBP28(NettyConnection connection,String cmd,Runtime runtime,byte[] bytes) { + public void handleBP28(Connection connection,String cmd,Runtime runtime,byte[] bytes) { //log("handleBP28 msg"+cmd); /** * IWBP28, D3590D54,XXXX,6,1,1024,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX# @@ -1916,7 +1915,7 @@ public class protocol_ic { .append(CMDEND).toString(); } - public void handleBPDE(NettyConnection connection,String cmd,Runtime runtime){ + public void handleBPDE(Connection connection,String cmd,Runtime runtime){ /*** * 示例: * IWBPDE,867400020316612,853676,0 @@ -1960,7 +1959,7 @@ public class protocol_ic { .append(CMDEND).toString(); } - public void handleBPDG(NettyConnection connection,String cmd,Runtime runtime){ + public void handleBPDG(Connection connection,String cmd,Runtime runtime){ /** * 示例: * IWBPDG,353456789012345,1,30.0,37.3 # @@ -2051,7 +2050,7 @@ public class protocol_ic { } - public void handleBPTU(String cmd , NettyConnection connection ){ + public void handleBPTU(String cmd , Connection connection ){ /*** * 平台响应 * IWBPTU,6654111,080835,1,1,6,1,1# @@ -2128,7 +2127,7 @@ public class protocol_ic { .append(CMDEND).toString(); } - public void handleBP46(String cmd , NettyConnection connection,Runtime runtime) { + public void handleBP46(String cmd , Connection connection,Runtime runtime) { /*** * IWBP46,353456789012345,080835,1,[参数]# * 说明: @@ -2181,7 +2180,7 @@ public class protocol_ic { } - public void handleBPDH( NettyConnection connection,Runtime runtime,String cmd) { + public void handleBPDH( Connection connection,Runtime runtime,String cmd) { /*** * IWBPDH,353456789012345,080835,1,[参数]# * 说明: diff --git a/app/src/main/java/com/ic/protocols/protocol_jiai.java b/app/src/main/java/com/ic/protocols/protocol_jiai.java index 77a92fe0..a0f094bd 100644 --- a/app/src/main/java/com/ic/protocols/protocol_jiai.java +++ b/app/src/main/java/com/ic/protocols/protocol_jiai.java @@ -18,7 +18,6 @@ import com.enqualcomm.support.bean.voicePacket; import com.enqualcomm.support.service.HeartRateManager; import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.ICLogger; -import com.enqualcomm.support.utils.NettyConnection; import com.enqualcomm.support.utils.TimeUtil; import com.enqualcomm.support.utils.Util; @@ -169,10 +168,10 @@ public class protocol_jiai { cmdMap.put(CMD_TYPE.BP89, "BP89"); } - private NettyConnection mConnection=null; + private Connection mConnection=null; private Runtime mRuntime=null; - public protocol_jiai(NettyConnection connect,Runtime runtime) { + public protocol_jiai(Connection connect,Runtime runtime) { mConnection=connect; mRuntime=runtime; @@ -931,7 +930,7 @@ public class protocol_jiai { } - public void handleBP07(String cmd , NettyConnection connection ){ + public void handleBP07(String cmd , Connection connection ){ //平台响应: IWBP07,20140818064408,6,1,1# //20140818064408:设备语音时间,yyyyMMddHHmmss 格式的年月日时分秒 //6:语音包分包总数 @@ -1240,7 +1239,7 @@ public class protocol_jiai { } //处理 BP28 语音消息 - public void handleBP28(NettyConnection connection,String cmd,Runtime runtime,byte[] bytes) { + public void handleBP28(Connection connection,String cmd,Runtime runtime,byte[] bytes) { //log("handleBP28 msg"+cmd); /** * IWBP28, D3590D54,XXXX,6,1,1024,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX# diff --git a/app/src/main/java/com/ic/protocols/protocol_mqtt.java b/app/src/main/java/com/ic/protocols/protocol_mqtt.java index 02c30f86..ddbc8ecc 100644 --- a/app/src/main/java/com/ic/protocols/protocol_mqtt.java +++ b/app/src/main/java/com/ic/protocols/protocol_mqtt.java @@ -2,6 +2,7 @@ package com.ic.protocols; import android.content.ComponentName; import android.content.Intent; +import android.text.TextUtils; import com.enqualcomm.support.Config; import com.enqualcomm.support.CoreService; @@ -12,7 +13,6 @@ import com.enqualcomm.support.service.HeartRateManager; import com.enqualcomm.support.utils.Connection; import com.enqualcomm.support.utils.ICLogger; import com.enqualcomm.support.utils.MD5; -import com.enqualcomm.support.utils.NettyConnection; import com.enqualcomm.support.utils.TemperatureUtil; import com.enqualcomm.support.utils.TimeUtil; import com.enqualcomm.support.utils.Util; @@ -30,9 +30,7 @@ import static java.lang.Math.abs; public class protocol_mqtt { private static final String TAG = "ICSrv." + protocol_mqtt.class.getSimpleName(); private static final String CMDHEADER = "["; - private static final String CMDCOMPANY="IC"; private static final String CMDEND = "]"; - private static final String CMDHEADERSPLIT = "*"; private static final String CMDSPLIT = ","; public static final String defaultServerIP="47.106.237.76"; @@ -94,10 +92,10 @@ public class protocol_mqtt { } - private NettyConnection mConnection=null; + private Connection mConnection=null; private Runtime mRuntime=null; - public protocol_mqtt(NettyConnection connect, Runtime runtime) { + public protocol_mqtt(Connection connect, Runtime runtime) { mConnection=connect; mRuntime=runtime; @@ -122,38 +120,14 @@ public class protocol_mqtt { return sm; } - /* - 输入的字符串,如果有完整命令,返回 命令名 - 否则返回 空字符串 - */ - public static String isCmdStr(String msg) { - String cmd_msgbuf=msg; - int cmdindex =cmd_msgbuf.indexOf(CMDCOMPANY+CMDHEADERSPLIT); - if (cmdindex>0) { //如果开头不是CMDHEADER但是包含CMDHEADER则删除前面的数据 - String cmd=cmd_msgbuf.substring(cmdindex); - cmd_msgbuf=cmd; - } - cmdindex=cmd_msgbuf.indexOf(CMDEND); - if(cmdindex>0){ - String cmd=cmd_msgbuf.substring(0,cmdindex); - cmd_msgbuf=cmd; - } - cmdindex=cmd_msgbuf.indexOf(CMDSPLIT); - if(cmdindex>0){ - String cmd=cmd_msgbuf.substring(0,cmdindex); - cmd_msgbuf=cmd; - } - if (regexUtil.isFZDCMD(cmd_msgbuf)) { - for (CMD_TYPE key : cmdMap.keySet()) { - if (regexUtil.isFZDCMD(cmdMap.get(key), cmd_msgbuf)) { //如果是FZD命令,则进行处理,否则保留数据动 - ICLogger.i("found cmd keyid=" + key + " ,keyname=" + cmdMap.get(key)); - return cmdMap.get(key); - } + public static String isCmdStr(StringMessage msg){ + for (CMD_TYPE key : cmdMap.keySet()) { + if (cmdMap.get(key).toString().equals(msg.cmd())){ + return msg.cmd(); } - return ""; - }else - return ""; + } + return ""; } /* 返回true 表示 cmd 全部解析成功 @@ -161,50 +135,19 @@ public class protocol_mqtt { 字符串通过#号进行识别。 每个字符串如果发现 #,却又没有Header,“IW”则会被丢弃 */ - public boolean parserCmd(byte[] bytes) { + public boolean parserCmd(String cmdtype,byte[] bytes) { String cmd_msgbuf=new String(bytes); log("bytes.size "+bytes.length); cmdbuf.append(cmd_msgbuf); log("cmdbuf.size "+cmdbuf.length() +" "+cmdbuf.toString()); - int cmdindex =cmd_msgbuf.indexOf(CMDCOMPANY+CMDHEADERSPLIT); - if (cmdindex>0) { //如果开头不是CMDHEADER但是包含CMDHEADER则删除前面的数据 - String cmd=cmd_msgbuf.substring(cmdindex); - cmd_msgbuf=cmd; - } - cmdindex=cmd_msgbuf.indexOf(CMDEND); - if(cmdindex>0){ - String cmd=cmd_msgbuf.substring(0,cmdindex); - cmd_msgbuf=cmd; - } - cmdindex=cmd_msgbuf.indexOf(CMDSPLIT); - if(cmdindex>0){ - String cmd=cmd_msgbuf.substring(0,cmdindex); - cmd_msgbuf=cmd; - } - if (cmdbuf.toString().split(CMDCOMPANY+CMDHEADERSPLIT).length>1) - { - ICLogger.i("More than 1 cmd in buffer ! just log it"); - } - for (CMD_TYPE key : cmdMap.keySet()) { - // ICLogger.i("key "+cmdMap.get(key)+" cmdbuf "+cmd_msgbuf); - if (regexUtil.isFZDCMD(cmdMap.get(key),cmd_msgbuf)) { //如果是FZD命令,则进行处理,否则保留数据动 - String data=cmdbuf.toString().replace(CMDHEADER,"").replace(cmd_msgbuf,"").replace(CMDEND,""); -// ICLogger.i("found cmd keyid=" + key + " ,keyname=" + cmdMap.get(key) + " , " + cmdbuf.toString() + " "+cmd_msgbuf + " data "+data ); -// if (key == CMD_TYPE.TK) { -// //如果是BP28则 后面的数据是音频,需要保留 -// byte[] amrBuf; -// int amrLen = getBP28Amrlen(cmdlist[i] ); -// if (bytes.length > amrLen) { -// handleCmd(key, cmdlist[i], bytes); -// } -// } else { - if (data.startsWith(CMDSPLIT)) data=data.substring(1); - handleCmd(key, cmd_msgbuf,data); - cmdbuf.delete(0,cmdbuf.length());//处理后清空 -// } - } + cmd_msgbuf=cmd_msgbuf.replace(CMDHEADER,"").replace(CMDEND,""); + for (CMD_TYPE key : cmdMap.keySet()) { + if (cmdMap.get(key).toString().equals(cmdtype)){ + handleCmd(key, cmdtype,cmd_msgbuf); + return true; } - return true; + } + return false; } private static String getHexLen(int len){ @@ -221,110 +164,111 @@ public class protocol_mqtt { sb.append(hv); return sb.toString(); } - private static String genHeader(int len,String cmd){ - - if (CoreService.getInstance()==null) - return ""; - - String imei =CoreService.getInstance().getRuntime().IMEI(); - return new StringBuilder().append(CMDCOMPANY).append(CMDHEADERSPLIT) - .append(imei).append(CMDHEADERSPLIT) - .append(getHexLen(len)).append(CMDHEADERSPLIT).append(cmd).toString(); - } - - private static String keyheader(String cmd,int len){ - String header=genHeader(len,cmd); - String key= MD5.getCMDStringMD5(header); - return key; - } - - public static String genFZDCMD( String CMD){ - StringBuilder sb=new StringBuilder(); - int len=CMD.length(); - String header=genHeader(len,CMD); - String keyheader=keyheader(CMD,len); - sb.append(CMDHEADER).append(keyheader).append(header).append(CMDEND); - return sb.toString(); - } - public static String genFZDCMD( String CMD,String data){ + public static StringMessage genMqttCMDMsg(String cmdtype, String data,String imei){ StringBuilder sb=new StringBuilder(); - String data_buf=CMD+CMDSPLIT+data; - int data_buf_len=data_buf.length(); - String header=genHeader(data_buf_len,CMD); - String keyheader=keyheader(CMD,data_buf_len);//计算header md5值 - sb.append(CMDHEADER).append(keyheader).append(header).append(CMDSPLIT).append(data).append(CMDEND); - return sb.toString(); + int len=data.length()+1;//长度计算要包括逗号 + sb.append(CMDHEADER).append(getHexLen(len)).append(CMDSPLIT).append(data).append(CMDEND); + StringBuilder sbtopic=new StringBuilder(); + sbtopic.append(projName) + .append("/").append(protocolVersion) + .append("/").append(cmdtype) + .append("/").append(imei); + return genStringMessage(sbtopic.toString(),sb.toString()); } /** - * 绑定 + * 终端发布(平台订阅): + * 终端向“WBG100/v1/BREQ/ID_手表IMEI”的主题发布 [LEN,MQTT注册时的账号及密码的密文] + * + * 实例: 若手表IMEI号为334588000000156, + * MQTT注册时的账号及密码的密文为:QWER15WTF156OQRT1230 + * 则向WBG100/v1/BREQ/ID_334588000000156的主题发布[0016,QWER15WTF156OQRT1230] * */ - public static String BREQ(){ -// IC*YYYYYYYYYYYYYYY*LEN*PING - return genFZDCMD(cmdMap.get(CMD_TYPE.BREQ)); + public static StringMessage BREQ(Runtime runtime){ + + return genMqttCMDMsg(cmdMap.get(CMD_TYPE.BREQ), mqttKey,runtime.IMEI()); } public static void handleBREQ(Runtime runtime,String data){ -// [IC*YYYYYYYYYYYYYYY*LEN*PING,是否绑定(0 表示未绑定,1 表示绑定)] -// 实例:[IC*334588000000156*0006*PING,0]或[IC*334588000000156*0006*PING,1] - int bind=Integer.parseInt(data); - if (bind==0){ - ICLogger.i("设备未绑定!"); - runtime.BindingStatus=false; - }else{ - ICLogger.i("设备已绑定!"); - runtime.BindingStatus=true; +/*** + * 回应的消息为:[LEN,区域id,绑定的区域纬度,N/S,经度,E/W,beacon mac_1,beacon mac_2,beacon mac_3,…,beacon mac_n] + * + * 实例: 若手表IMEI号为334588000000156,绑定的区域为123456789, + * 经纬度为:22.570512,N,113.8623267,E, + * beacon mac:0x5947ffff0001, 5947ffff0002 + * 则终端订阅“WBG100/v1/ID_334588000000156/+”的主题列表,会收到平台的回应 + * 先判断子主题是否为:BREQ + * 是,则消息为:[003F,123456789,22.570512,N,113.8623267,E,5947ffff0001, 5947ffff0002] + */ + String[] list=data.split(CMDSPLIT); + if (list.length>=8){ + + runtime.bleInfo.ble_area_id=list[1]; + runtime.bleInfo.gps_n=list[2]; + runtime.bleInfo.gps_e=list[4]; + runtime.bleInfo.btMacList.clear(); + for (int i=6;i< list.length;i++){ + runtime.bleInfo.btMacList.add(list[i]); + } } - } - public static String KA(Runtime runtime){ -//[IC*YYYYYYYYYYYYYYY*LEN*KA,日期,步数,翻滚次数,电量百分数] 实例:[IC*334588000000156*0014*KA,120414,50,100,100] + public static StringMessage KA(Runtime runtime){ + + /*** + * 终端向“WBG100/v1/KA/ID_手表IMEI”的主题发布 [LEN, 日期,步数,翻滚次数,电量百分数,区域id] + * + * 实例:若手表IMEI号为334588000000156,请求绑定时下发的区域id为123456789, + * 则向WBG100/v1/KA/ID_334588000000156的主题发布 [001B,120414,50,100,100, 123456789] + * + * 终端订阅(平台发布): + * 终端订阅“WBG100/v1/ID_手表IMEI/+”的主题列表,会收到平台的回应 + * 平台发布的子主题为:KA + * 回应的消息为:[LEN,KA] + */ StringBuilder sb=new StringBuilder(); String cmd=cmdMap.get(CMD_TYPE.KA); sb.append(TimeUtil.getSystemDateYYMMDD()).append(CMDSPLIT) .append(runtime.getTotalStepCount()).append(CMDSPLIT) .append(runtime.getRolltimes()).append(CMDSPLIT) - .append(runtime.getBattery()); - return genFZDCMD(cmd,sb.toString()); - } - - - public void handleKA(Runtime runtime,String data){ - + .append(runtime.getBattery()).append(CMDSPLIT) + .append(runtime.bleInfo.ble_area_id); + return genMqttCMDMsg(cmd,sb.toString(),runtime.IMEI()); } /*LBS+GPS混合定位*/ - public static String UD(Runtime runtime) { + public static StringMessage UD(Runtime runtime) { /*** - * [IC*334588000000156*00CD*UD,180916,025723,A,22.570733,N,113.8626083,E,0.00,249.5,0.0,6,100, 60,0,0,00000010,7,255,460,1,9529,21809,158,9529,63555,133,9529,63554,129,9529,21405,126,95 - * 29,21242,124,9529,21151,120,9529,63556,119,0] + * [LEN,定位数据,区域id] + * + * 实例:若手表IMEI号为334588000000156,请求绑定时下发的区域id为123456789, + * 则向WBG100/v1/LGZONE/ID_334588000000156的主题发布 + * [00D7,180916,025723,A,22.570733,N,113.8626083,E,0.00,249.5,0.0,6,100, + * 60,0,0,00000010,7,255,460,1,9529,21809,158,9529,63555,133,9529,63554,129,9529,21405,126,9529,21242,124,9529,21151,120,9529,63556,119,0,123456789] * 说明: * 数据内容: - * UD,命令号 - * 180916,日期(年月日)(0 时区),表示 0 时区的二零一八年九月十六号 - * - * 025723,时间(时分秒)(0 时区),表示 0 时区的两点五十七分二十三秒A,gps 定位有效 + * 180916,日期(年月日)(0 时区),表示0 时区的二零一八年九月十六号 + * 025723,时间(时分秒)(0 时区),表示0 时区的两点五十七分二十三秒 + * A,gps 定位有效 * 22.570733,纬度 - * N,纬度表示113.8626083,经度 - * E,经度表示0.00,速度 + * N,纬度表示 + * 113.8626083,经度 + * E,经度表示 + * 0.00,速度 * 249.5,方向 * 0.0,海拔 * 6,卫星个数 - * * 100,gsm 信号强度 * 60,电量 * 0,计步数 * 0,翻转次数 - * 00000010,终端状态,数据为 16 进制,解析成二进制为 0000 0000 0000 0000 0000 0000 0001 0000 - * 前面 4 个字节表示状态,后面 4 个字节表示报警,数据中第 4 位为 1,对照文档最后的数据解析,表示手表静止状态。详细可参看文档最后部分。 + * 00000010,终端状态,数据为16 进制,解析成二进制为0000 0000 0000 0000 0000 0000 0001 0000 前面4 个字节表示状态,后面4 个字节表示报警,数据中第4 位为1,对照文档最后的数据解析,表示手表静止状态。详细可参看文档最后部分。 * 7,基站个数 - * 255,460,1,9529,21809,158,9529,63555,133,9529,63554,129,9529,21405,126,9529,21242,124,9529, - * 21151,120,9529,63556,119,基站信息 + * 255,460,1,9529,21809,158,9529,63555,133,9529,63554,129,9529,21405,126,9529,21242,124,9529,21151,120,9529,63556,119,基站信息 * 0,WiFi 个数 - * + * 123456789,为区域id */ @@ -339,9 +283,10 @@ public class protocol_mqtt { .append(runtime.getRolltimes()).append(CMDSPLIT) .append(runtime.getFZDDevStatus()).append(CMDSPLIT) .append(runtime.getFZDLBSMultiStationData()).append(CMDSPLIT) - .append(runtime.getFZDWifiData()); - - return genFZDCMD(cmd,sb.toString()); + .append(runtime.getFZDWifiData()).append(CMDSPLIT) + .append(runtime.bleInfo.is_in_area?"1":"0").append(CMDSPLIT) + .append(runtime.bleInfo.ble_area_id); + return genMqttCMDMsg(cmd,sb.toString(),runtime.IMEI()); } @@ -350,108 +295,108 @@ public class protocol_mqtt { log("BP02定位接收成功"); } - - public static String UPLOAD(){ - - return genFZDCMD(cmdMap.get(CMD_TYPE.UPLOAD)); - } - - public void handleUPLOAD(Connection connection,Runtime runtime,String cmd,String data){ - connection.send(genStringMessage("UPLOAD",UPLOAD())); - int timesecond=Integer.parseInt(data); - int mod=runtime.getLocationInstance().getWorkingMod(); - log("LOCATION_MODE "+LOCATION_MODE+" mod "+ mod); - Config.setLocationMode(runtime.getContextProxy().context,mod); - Config.setLocationCycle(runtime.getContextProxy().context,timesecond); - runtime.getLocationInstance().setLocation_cycle(timesecond); - runtime.getLocationInstance().setWorkingMod(mod); -// CoreService.getInstance().setLocationAlarm(runtime.getLocationInstance().getWorkingMod()); - //此处设置好配置后,会在LocationClient通过消息开始执行及时定位操作。 - - } - - public static String heart(int hrt){ - return genFZDCMD(cmdMap.get(CMD_TYPE.heart),String.valueOf(hrt)); - } - public static String oxygen(int ox){ - return genFZDCMD(cmdMap.get(CMD_TYPE.oxygen),String.valueOf(ox)); - } - - public static String blood(int pbl,int pbh){ - String data=pbh+CMDSPLIT+pbl; - return genFZDCMD(cmdMap.get(CMD_TYPE.blood),data); - } - - public static String temp(double temp){ - return genFZDCMD(cmdMap.get(CMD_TYPE.temp),String.format("%.1f",temp)); - } - - public static String wdstart(){ - return genFZDCMD(cmdMap.get(CMD_TYPE.wdstart)); - } - public void handleWdstart(Connection connection,Runtime runtime ,String data) { - - connection.send(genStringMessage("wdstart",wdstart())); - int freq=Integer.parseInt(data); - - - Config.setTemperatureTestCycle(runtime,freq); - CoreService.getInstance().setTempAlarm(); - - TemperatureUtil.doTempTestInThread(); // -// double wrist_temp,body_temp; -// wrist_temp= TemperatureUtil.get_temp_value_adjusted(); -// body_temp=TemperatureUtil.getBodyTemp(wrist_temp,26.0f); -// String temperatureMsg=temp(body_temp); -// connection.send(genStringMessage("temp",temperatureMsg)); - } - public static String hrtstart(){ - return genFZDCMD(cmdMap.get(CMD_TYPE.hrtstart)); - } - public void handleHrtstart(Connection connection) { - - connection.send(genStringMessage("hrtstart",hrtstart())); - } - - public static String SOS(){ - return genFZDCMD(cmdMap.get(CMD_TYPE.SOS)); - } - - - public void handleSOS(Connection connection,Runtime runtime,String cmd,String data) { - - connection.send(genStringMessage("SOS",SOS())); - if (data!=null && data.length()>0) { - String list[] = data.split(CMDSPLIT); - if (list.length==1){ - ArrayList contactArray=new ArrayList(); - if (regexUtil.isMobileNumber( list[0]) || regexUtil.isPhoneNumber(list[0])) - { - contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos1",list[0])); - ICLogger.i("find SOS1 number "+list[0]); - } - }else if (list.length==2){ - - ArrayList contactArray=new ArrayList(); - if (regexUtil.isMobileNumber( list[0]) || regexUtil.isPhoneNumber(list[0])) - { - contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos1",list[0])); - ICLogger.i("find SOS1 number "+list[0]); - } - if (regexUtil.isMobileNumber( list[1]) || regexUtil.isPhoneNumber(list[1])) - { - contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos2",list[1])); - ICLogger.i("find SOS2 number "+list[1]); - } - - runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true); - - } - } - - - } +// public static String UPLOAD(){ +// +// return genFZDCMD(cmdMap.get(CMD_TYPE.UPLOAD)); +// } +// +// public void handleUPLOAD(Connection connection,Runtime runtime,String cmd,String data){ +// connection.send(genStringMessage("UPLOAD",UPLOAD())); +// int timesecond=Integer.parseInt(data); +// int mod=runtime.getLocationInstance().getWorkingMod(); +// log("LOCATION_MODE "+LOCATION_MODE+" mod "+ mod); +// Config.setLocationMode(runtime.getContextProxy().context,mod); +// Config.setLocationCycle(runtime.getContextProxy().context,timesecond); +// runtime.getLocationInstance().setLocation_cycle(timesecond); +// runtime.getLocationInstance().setWorkingMod(mod); +//// CoreService.getInstance().setLocationAlarm(runtime.getLocationInstance().getWorkingMod()); +// //此处设置好配置后,会在LocationClient通过消息开始执行及时定位操作。 +// +// } +// +// public static String heart(int hrt){ +// return genFZDCMD(cmdMap.get(CMD_TYPE.heart),String.valueOf(hrt)); +// } +// public static String oxygen(int ox){ +// return genFZDCMD(cmdMap.get(CMD_TYPE.oxygen),String.valueOf(ox)); +// } +// +// public static String blood(int pbl,int pbh){ +// String data=pbh+CMDSPLIT+pbl; +// return genFZDCMD(cmdMap.get(CMD_TYPE.blood),data); +// } +// +// public static String temp(double temp){ +// return genFZDCMD(cmdMap.get(CMD_TYPE.temp),String.format("%.1f",temp)); +// } +// +// public static String wdstart(){ +// return genFZDCMD(cmdMap.get(CMD_TYPE.wdstart)); +// } +// public void handleWdstart(Connection connection,Runtime runtime ,String data) { +// +// connection.send(genStringMessage("wdstart",wdstart())); +// int freq=Integer.parseInt(data); +// +// +// Config.setTemperatureTestCycle(runtime,freq); +// CoreService.getInstance().setTempAlarm(); +// +// TemperatureUtil.doTempTestInThread(); +//// +//// double wrist_temp,body_temp; +//// wrist_temp= TemperatureUtil.get_temp_value_adjusted(); +//// body_temp=TemperatureUtil.getBodyTemp(wrist_temp,26.0f); +//// String temperatureMsg=temp(body_temp); +//// connection.send(genStringMessage("temp",temperatureMsg)); +// } +// public static String hrtstart(){ +// return genFZDCMD(cmdMap.get(CMD_TYPE.hrtstart)); +// } +// public void handleHrtstart(Connection connection) { +// +// connection.send(genStringMessage("hrtstart",hrtstart())); +// } +// +// public static String SOS(){ +// return genFZDCMD(cmdMap.get(CMD_TYPE.SOS)); +// } +// +// +// public void handleSOS(Connection connection,Runtime runtime,String cmd,String data) { +// +// connection.send(genStringMessage("SOS",SOS())); +// if (data!=null && data.length()>0) { +// String list[] = data.split(CMDSPLIT); +// if (list.length==1){ +// ArrayList contactArray=new ArrayList(); +// if (regexUtil.isMobileNumber( list[0]) || regexUtil.isPhoneNumber(list[0])) +// { +// contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos1",list[0])); +// ICLogger.i("find SOS1 number "+list[0]); +// } +// }else if (list.length==2){ +// +// ArrayList contactArray=new ArrayList(); +// if (regexUtil.isMobileNumber( list[0]) || regexUtil.isPhoneNumber(list[0])) +// { +// contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos1",list[0])); +// ICLogger.i("find SOS1 number "+list[0]); +// } +// if (regexUtil.isMobileNumber( list[1]) || regexUtil.isPhoneNumber(list[1])) +// { +// contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos2",list[1])); +// ICLogger.i("find SOS2 number "+list[1]); +// } +// +// runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true); +// +// } +// } +// +// +// } public void sendBroadcast(String cmd, Runtime dev) { @@ -479,7 +424,9 @@ public class protocol_mqtt { case BREQ: handleBREQ(mRuntime,data); - ICLogger.i("服务器返回Ping绑定信息"); + //ICLogger.i("服务器返回Ping绑定信息"); + ICLogger.i("服务器收到登录包BREQ"); + mConnection.DeliverCMDMessageToSystem("login",cmd);//通知下面线程状态变化 break; // case CR: // //立即定位指令(长链接有效) @@ -507,10 +454,10 @@ public class protocol_mqtt { // ICLogger.i("收到服务器设置闹钟命令BP85"); // mConnection.DeliverCMDMessageToSystem("AP85",cmd);//通知下面线程状态变化 // break; - case UPLOAD: - //设置工作模式 - handleUPLOAD(mConnection,mRuntime,cmd,data); - mConnection.DeliverCMDMessageToSystem("setWorkMod",cmd);//通知下面线程状态变化 +// case UPLOAD: +// //设置工作模式 +// handleUPLOAD(mConnection,mRuntime,cmd,data); +// mConnection.DeliverCMDMessageToSystem("setWorkMod",cmd);//通知下面线程状态变化 // // break; // case BP34: @@ -524,11 +471,11 @@ public class protocol_mqtt { //// API.handleBP05(cmd); //// break; // - case SOS: - //收到设置SOS号码 - handleSOS(mConnection,mRuntime,cmd,data); - ICLogger.i("收到服务器设置SOS号码命令BP12"); - break; +// case SOS: +// //收到设置SOS号码 +// handleSOS(mConnection,mRuntime,cmd,data); +// ICLogger.i("收到服务器设置SOS号码命令BP12"); +// break; // case PHL: // //收到设置白名单号码 // ICLogger.i("收到服务器设置白名单号码命令BP14"); @@ -560,32 +507,32 @@ public class protocol_mqtt { // mConnection.DeliverCMDMessageToSystem("showTxt",cmd);//通知下面线程状态变化 // break; // - case hrtstart: - handleHrtstart(mConnection); - ICLogger.i("收到服务器心率检测命令"); - HeartRateManager.triggerPPGtest(); - break; - - case wdstart: - handleWdstart(mConnection,mRuntime,data); - ICLogger.i("收到服务器体温测试及设置命令"); - break; - case blood: - ICLogger.i("服务器收到上传的血压"); - mConnection.DeliverCMDMessageToSystem("blood",cmd);//通知下面线程状态变化 - break; - case oxygen: - ICLogger.i("服务器收到上传的血氧"); - mConnection.DeliverCMDMessageToSystem("oxygen",cmd);//通知下面线程状态变化 - break; - case temp: - ICLogger.i("服务器收到上传的体温"); - mConnection.DeliverCMDMessageToSystem("temp",cmd);//通知下面线程状态变化 - break; - case heart: - ICLogger.i("服务器收到上传的心率heart"); - mConnection.DeliverCMDMessageToSystem("heart",cmd);//通知下面线程状态变化 - break; +// case hrtstart: +// handleHrtstart(mConnection); +// ICLogger.i("收到服务器心率检测命令"); +// HeartRateManager.triggerPPGtest(); +// break; +// +// case wdstart: +// handleWdstart(mConnection,mRuntime,data); +// ICLogger.i("收到服务器体温测试及设置命令"); +// break; +// case blood: +// ICLogger.i("服务器收到上传的血压"); +// mConnection.DeliverCMDMessageToSystem("blood",cmd);//通知下面线程状态变化 +// break; +// case oxygen: +// ICLogger.i("服务器收到上传的血氧"); +// mConnection.DeliverCMDMessageToSystem("oxygen",cmd);//通知下面线程状态变化 +// break; +// case temp: +// ICLogger.i("服务器收到上传的体温"); +// mConnection.DeliverCMDMessageToSystem("temp",cmd);//通知下面线程状态变化 +// break; +// case heart: +// ICLogger.i("服务器收到上传的心率heart"); +// mConnection.DeliverCMDMessageToSystem("heart",cmd);//通知下面线程状态变化 +// break; // case BP84: // handleBP84(cmd,mConnection); // ICLogger.i("收到服务器白名单命令"); diff --git a/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java b/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java index 8f4c96a0..7b019835 100644 --- a/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java +++ b/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java @@ -9,6 +9,8 @@ import android.os.IBinder; import android.os.Message; import android.util.Log; +import com.enqualcomm.support.utils.ICLogger; + import java.io.IOException; import se.wetcat.qatja.MQTTConstants; @@ -20,74 +22,87 @@ import se.wetcat.qatja.messages.MQTTPublish; public class protocol_mqtt_client { - private String TAG=protocol_mqtt_client.class.getSimpleName(); + private String TAG = protocol_mqtt_client.class.getSimpleName(); private Handler mHandler = new Handler(new MqttCallback()); - QatjaService mClient=null; + QatjaService mClient = null; private Context mContext; private boolean isBound = false; private boolean isBinding = false; + public static String topic_header=""; + public void setSubscriptTopicHeader(String header){ + topic_header=header; + } private class MqttCallback implements Handler.Callback { @Override - public boolean handleMessage(Message msg) - { + public boolean handleMessage(Message msg) { - switch (msg.what) { - case MQTTConnectionConstants.STATE_CHANGE: - handleStateChange(msg); + ICLogger.i("MqttCallback handleMessage "+msg.what); + switch (msg.what) { + case MQTTConnectionConstants.STATE_CHANGE: + handleStateChange(msg); + break; + case 3: + handleReceivedMessage(msg); break; - case 3: - handleReceivedMessage(msg); - break; - } - return true; } + return true; + } } + MqttCallbackInterface mqttCallbackInterface=null; + public protocol_mqtt_client(Context context,MqttCallbackInterface _mqttCallbackInterface) { - public protocol_mqtt_client(Context context ) { - - mContext=context; + mqttCallbackInterface=_mqttCallbackInterface; + mContext = context; } + private void handleStateChange(Message msg) { - Log.e(TAG, MQTTConnectionConstants.resolveStateName(msg.arg1)); + ICLogger.i(MQTTConnectionConstants.resolveStateName(msg.arg1)); switch (msg.arg1) { case MQTTConnectionConstants.STATE_NONE: - onMqttDisconnected(); + if (mqttCallbackInterface!= null) + mqttCallbackInterface.onMqttDisconnected(); break; - case MQTTConnectionConstants.STATE_CONNECTING: break; case MQTTConnectionConstants.STATE_CONNECTED: - onMqttConnected(); + if (mqttCallbackInterface!=null) + mqttCallbackInterface.onMqttConnected(); break; case MQTTConnectionConstants.STATE_CONNECTION_FAILED: - onMqttDisconnected(); + if (mqttCallbackInterface!=null) + mqttCallbackInterface.onMqttDisconnected(); break; default: Log.e(TAG, "Unhandled MQTT state change"); - break; + break; } } private void handleReceivedMessage(Message msg) { - MQTTPublish publish = (MQTTPublish)msg.obj; + MQTTPublish publish = (MQTTPublish) msg.obj; // if (isDebug()) { - Log.d(TAG, "handleReceivedMessage(${publish.topicName})"+publish.getTopicName()+" data "+new String(publish.getPayload())); + Log.d(TAG, "handleReceivedMessage(${publish.topicName})" + publish.getTopicName() + " data " + new String(publish.getPayload())); // } + String cmdtype= publish.getTopicName().replace(topic_header,""); + if (mqttCallbackInterface!=null) + mqttCallbackInterface.handleMqttMessage(cmdtype, publish.getPayload()); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { - mClient = ((QatjaService.QatjaBinder)iBinder).getService(); + mClient = ((QatjaService.QatjaBinder) iBinder).getService(); isBound = true; isBinding = false; mClient.setHandler(mHandler); + + attemptBindService(); } @Override @@ -98,7 +113,7 @@ public class protocol_mqtt_client { }; - public void Resume() { + public void Resume() { attemptBindService(); } @@ -110,7 +125,7 @@ public class protocol_mqtt_client { isBinding = false; isBound = false; - } catch ( IllegalArgumentException ex) { + } catch (IllegalArgumentException ex) { Log.e(TAG, "Couldn't unbind the service, this is probably fine considering the state changes in the app... can probably ignore this.", ex); } @@ -118,14 +133,14 @@ public class protocol_mqtt_client { } public void attemptSubscribeToTopic(String topic) { - Log.d(TAG, "attemptSubscribeToTopic($topic)"+topic); + Log.d(TAG, "attemptSubscribeToTopic($topic)" + topic); - try { - mClient.subscribe(topic, MQTTConstants.AT_MOST_ONCE); - } catch (Exception ex) { - Log.e(TAG, ex.getMessage()); - } + try { + mClient.subscribe(topic, MQTTConstants.AT_MOST_ONCE); + } catch (Exception ex) { + Log.e(TAG, ex.getMessage()); + } } @@ -135,7 +150,7 @@ public class protocol_mqtt_client { public void connectservice() { if (isBound) { -// attemptConnectMqtt() + attemptConnectMqtt(); } else if (!isBound && !isBinding) { attemptBindService(); } @@ -143,7 +158,7 @@ public class protocol_mqtt_client { private void attemptBindService() { // if (isDebug()) { - Log.d(TAG, "attemptBindService() [isBound: $isBound, isBinding: $isBinding]"); + Log.d(TAG, "attemptBindService() [isBound: $isBound, isBinding: $isBinding]"); // } if (!isBound && !isBinding) { isBinding = true; @@ -153,17 +168,30 @@ public class protocol_mqtt_client { } } + private String mqttHost=""; + private String devid=""; + private int mqtt_cycle_seconds=600; + public void configMqtt(String host,int cycle_seconds,String idname){ + mqttHost=host; + devid=idname; + mqtt_cycle_seconds=cycle_seconds; + } - public void attemptConnectMqtt(String host,String identifier, int cycle_inSeconds) { - Log.d(TAG, "attemptConnectMqtt($host, $identifier)"); - if (!(MQTTConnectionConstants.STATE_CONNECTING== mClient.getState() || MQTTConnectionConstants.STATE_CONNECTED == mClient.getState())) - { + public void attemptConnectMqtt(){ + attemptConnectMqtt(mqttHost,devid,mqtt_cycle_seconds); + } + public void attemptConnectMqtt(String host, String identifier, int cycle_inSeconds) { + ICLogger.i("attemptConnectMqtt($host, $identifier)"); + + if (!(MQTTConnectionConstants.STATE_CONNECTING == mClient.getState() || MQTTConnectionConstants.STATE_CONNECTED == mClient.getState())) { try { + + ICLogger.i("attemptConnectMqtt"); mClient.setHost(host); mClient.setPort(1883); mClient.setIdentifier(identifier); - mClient.setKeepAlive(cycle_inSeconds*1000); + mClient.setKeepAlive(cycle_inSeconds); mClient.setCleanSession(true); mClient.connect(); @@ -173,19 +201,18 @@ public class protocol_mqtt_client { } } - void onMqttConnected() { - Log.i(TAG,"onMqttConnected"); - attemptSubscribeToTopic("WBG100/v1/1/+"); - + public void sendMessage(String cmdtype,String data){ + mClient.publish(topic_header+cmdtype,data); } - void onMqttDisconnected() { - Log.i(TAG,"onMqttDisconnected"); - } + public interface MqttCallbackInterface + { + void onMqttConnected() ; + void onMqttDisconnected(); - public void sendMessage(String topic,String data){ + void handleMqttMessage(String cmdtype,byte[] msgdata); + void handleMqttMessage(String cmdtype,String msgdata); - mClient.publish(topic,data); } } diff --git a/app/src/main/java/se/wetcat/qatja/android/QatjaService.java b/app/src/main/java/se/wetcat/qatja/android/QatjaService.java index d6aa41dd..02b55eb3 100644 --- a/app/src/main/java/se/wetcat/qatja/android/QatjaService.java +++ b/app/src/main/java/se/wetcat/qatja/android/QatjaService.java @@ -25,6 +25,8 @@ import android.os.IBinder; import android.text.TextUtils; import android.util.Log; +import com.enqualcomm.support.utils.ICLogger; + import java.io.Closeable; import java.io.IOException; import java.io.InputStream; @@ -101,7 +103,7 @@ public class QatjaService extends Service { private static final boolean DEBUG = true; - private static final String TAG = QatjaService.class.getSimpleName(); + private static final String TAG = "mqtt_"+QatjaService.class.getSimpleName(); /** * Current state of the connection @@ -283,7 +285,7 @@ public class QatjaService extends Service { } connect.setCleanSession(cleanSession); - connect.setKeepAlive(60); + connect.setKeepAlive(KEEP_ALIVE_TIMER); connect.setWillFlag(willFlag); if (willFlag) { connect.setWillTopic(willTopic); @@ -626,7 +628,7 @@ public class QatjaService extends Service { sendMessage(MQTTPingreq.newInstance()); // Make sure to auto-queue the runnable again when the message has been sent. - mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER*1000); } }; @@ -735,7 +737,7 @@ public class QatjaService extends Service { // Start the PINGREQ handler mKeepaliveHandler = new Handler(getMainLooper()); - mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER*1000); Log.d(TAG, "Sending connect message"); @@ -861,10 +863,10 @@ public class QatjaService extends Service { /** * Set keep alive timer in milliseconds * - * @param milliseconds the time + * @param seconds the time */ - public void setKeepAlive(int milliseconds) { - KEEP_ALIVE_TIMER = milliseconds; + public void setKeepAlive(int seconds) { + KEEP_ALIVE_TIMER = seconds; } /** @@ -1042,7 +1044,7 @@ public class QatjaService extends Service { byte type = MQTTHelper.decodeType(buffer); if (DEBUG) - Log.d(TAG, "Received " + MQTTHelper.decodePackageName(type)); + ICLogger.d( "Mqtt_"+"Received " + MQTTHelper.decodePackageName(type)); // Handle automatic responses here switch (type) { @@ -1056,37 +1058,37 @@ public class QatjaService extends Service { switch (connack.getReturnCode()) { case CONNECTION_ACCEPTED: if (DEBUG) - Log.d(TAG, "Connected"); + ICLogger.d( "Mqtt_"+ "Connected"); setState(STATE_CONNECTED); break; case CONNECTION_REFUSED_VERSION: if (DEBUG) - Log.d(TAG, "Failed to connect, unaccebtable protocol version"); + ICLogger.d( "Mqtt_"+ "Failed to connect, unaccebtable protocol version"); setState(STATE_CONNECTION_FAILED); break; case CONNECTION_REFUSED_IDENTIFIER: if (DEBUG) - Log.d(TAG, "Failed to connect, identifier rejected"); + ICLogger.d( "Mqtt_"+ "Failed to connect, identifier rejected"); setState(STATE_CONNECTION_FAILED); break; case CONNECTION_REFUSED_SERVER: if (DEBUG) - Log.d(TAG, "Failed to connect, server unavailable"); + ICLogger.d( "Mqtt_"+ "Failed to connect, server unavailable"); setState(STATE_CONNECTION_FAILED); break; case CONNECTION_REFUSED_USER: if (DEBUG) - Log.d(TAG, "Failed to connect, bad username or password"); + ICLogger.d( "Mqtt_"+ "Failed to connect, bad username or password"); setState(STATE_CONNECTION_FAILED); break; case CONNECTION_REFUSED_AUTH: if (DEBUG) - Log.d(TAG, "Failed to connect, not authorized"); + ICLogger.d( "Mqtt_"+ "Failed to connect, not authorized"); setState(STATE_CONNECTION_FAILED); break; } @@ -1214,7 +1216,7 @@ public class QatjaService extends Service { @Override protected Void doInBackground(Closeable... closeables) { if (DEBUG) { - Log.d(TAG, "[DisconnectTask] Closing streams and socket."); + ICLogger.d( "Mqtt_"+ "[DisconnectTask] Closing streams and socket."); } for (Closeable closeable : closeables) { @@ -1261,7 +1263,7 @@ public class QatjaService extends Service { try { if (mKeepaliveHandler != null) { mKeepaliveHandler.removeCallbacks(mPingSender); - mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER*1000); } } catch (Exception ex) { Log.e(TAG, ex.getMessage(), ex); diff --git a/app/version_code.properties b/app/version_code.properties index e9912a88..d5c8d3ca 100644 --- a/app/version_code.properties +++ b/app/version_code.properties @@ -1,2 +1,2 @@ -#Fri Aug 21 20:09:36 CST 2020 -VERSION_CODE=504 +#Thu Aug 27 00:06:54 CST 2020 +VERSION_CODE=505