Compare commits

...

3 Commits

2 changed files with 81 additions and 137 deletions

View File

@ -5,7 +5,6 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager; import android.net.wifi.WifiManager;
import com.safemobile.lib.AppParams; import com.safemobile.lib.AppParams;
@ -38,21 +37,19 @@ public class TCPhandler implements Runnable {
private String leftOver = ""; private String leftOver = "";
public static LinkedList<TCPmsg> msgList; public static LinkedList<TCPmsg> msgList;
private volatile int n = 0;
public Boolean isConnectionUP = false; public Boolean isConnectionUP = false;
public Boolean previousConnectionWasUP = false; public Boolean previousConnectionWasUP = false;
private Context context; private final Context context;
private boolean isWiFiOn = true; private boolean isWiFiOn;
public TCPhandler(Context context, String hostName, int p) { public TCPhandler(Context context, String hostName, int p) {
this.context = context; this.context = context;
serverHostname = hostName; serverHostname = hostName;
port = p; port = p;
msgList = new LinkedList<TCPmsg>(); msgList = new LinkedList<>();
SM.Debug("---TCPhandler constructor [" + hostName + "," + p + "] ---"); SM.Debug("---TCPhandler constructor [" + hostName + "," + p + "] ---");
listenThread = new Thread(this, "TCPlisten"); listenThread = new Thread(this, "TCPlisten");
listenThread.start(); // (2) Start the thread. listenThread.start(); // (2) Start the thread.
@ -64,7 +61,6 @@ public class TCPhandler implements Runnable {
public void run() { public void run() {
try { try {
previousConnectionWasUP = isConnectionUP; previousConnectionWasUP = isConnectionUP;
// try to send something // try to send something
TCPmsgParser._fireonTCPConnectionStatusEvent(isConnectionUP, previousConnectionWasUP); TCPmsgParser._fireonTCPConnectionStatusEvent(isConnectionUP, previousConnectionWasUP);
} catch (Exception e) { } catch (Exception e) {
@ -72,18 +68,20 @@ public class TCPhandler implements Runnable {
} }
} }
}, 0, 3000); }, 0, 3000);
// get WiFi state // get WiFi state
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); isWiFiOn = isNetworkConnected();
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnectedOrConnecting())
isWiFiOn = true;
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
context.registerReceiver(mReceived, intentFilter); context.registerReceiver(mReceived, intentFilter);
} }
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
@Override @Override
public void run() { public void run() {
try { try {
@ -100,20 +98,19 @@ public class TCPhandler implements Runnable {
isConnectionUP = true; isConnectionUP = true;
triggerTCPConnectionStateEvent(); triggerTCPConnectionStateEvent();
} }
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
SM.Debug("UnknownHostException", "TCPhandler break:" + e.toString()); SM.Debug("UnknownHostException", "TCPhandler break:"+ e);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
SM.Debug("IllegalArgumentException", "TCPhandler break:" + e.toString()); SM.Debug("IllegalArgumentException", "TCPhandler break:"+ e);
} catch (IOException e) { } catch (IOException e) {
SM.Debug("IOException", "TCPhandler break:" + e.toString()); SM.Debug("IOException", "TCPhandler break:"+ e);
} }
while (alive) { while (alive) {
try { try {
Thread.sleep(3000); Thread.sleep(3000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
SM.Debug("TCPhandler Crash1 on sleep:" + e.toString()); SM.Debug("TCPhandler Crash1 on sleep:"+ e);
} }
while (Boolean.TRUE.equals(isConnectionUP)) { while (Boolean.TRUE.equals(isConnectionUP)) {
@ -166,7 +163,7 @@ public class TCPhandler implements Runnable {
//end process leftover //end process leftover
String data = ""; String data = "";
n = 0; int n = 0;
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
// read data into buffer // read data into buffer
@ -181,7 +178,6 @@ public class TCPhandler implements Runnable {
break; break;
} }
byte[] temp = new byte[n]; byte[] temp = new byte[n];
if (n >= 0) System.arraycopy(buf, 0, temp, 0, n); if (n >= 0) System.arraycopy(buf, 0, temp, 0, n);
@ -190,77 +186,72 @@ public class TCPhandler implements Runnable {
data = new String(temp); data = new String(temp);
//if we have any leftovers from previous message add them //if we have any leftovers from previous message add them
if (leftOver.length() > 1) // avoid case with only one # if(leftOver.length() > 1) { // avoid case with only one #
{ data = leftOver+data;
data = leftOver + data; leftOver = "";
leftOver = ""; }
}
//search for overflow message //search for overflow message
String[] tempArr = data.split("#"); String[] tempArr = data.split("#");
if ((tempArr.length == 0) || (tempArr.length == 1)) { if ((tempArr.length == 0) || (tempArr.length == 1)) {
SM.Debug("TCP Client", "incorect messagebuss message=" + data); SM.Debug("TCP Client", "incorect messagebuss message=" + data);
continue; continue;
} }
//get msg len //get msg len
int messLen; int messLen;
try { try {
messLen = Integer.parseInt(tempArr[1]); messLen = Integer.parseInt(tempArr[1]);
} catch (Exception e) { } catch (Exception e) {
SM.Debug("TCP Client", "incorect msg len =" + tempArr[1]); SM.Debug("TCP Client", "incorect msg len =" + tempArr[1]);
continue; continue;
} }
//messLen not int //messLen not int
if (messLen == -1) { if (messLen == -1) {
continue; continue;
} }
char[] temMSG = data.toCharArray(); char[] temMSG = data.toCharArray();
if (data.length() != messLen) { if (data.length() != messLen) {
if (messLen > data.length()) { //if expected string message is smaller then actual string then exit processing;
leftOver = data; // Add by bigu if (messLen > data.length()) {
continue; leftOver = data; // Add by bigu
} continue;
//perform cut }
temMSG = data.substring(0, messLen).toCharArray(); //perform cut
leftOver = data.substring(messLen, data.length()); temMSG = data.substring(0,messLen).toCharArray();
} leftOver = data.substring(messLen);
}
//decode TCP msg //decode TCP msg
TCPmsg msg = new TCPmsg(temMSG); TCPmsg msg = new TCPmsg(temMSG);
SM.Debug("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> RX <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", msg.allData); SM.Debug("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> RX <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", msg.allData);
if (msg.allData.contains("#92#")) if (msg.allData.contains("#92#"))
prioritizePongReceived(); prioritizePongReceived();
msgList.add(msg); msgList.add(msg);
} catch(Exception ex) {
} catch (Exception ex) { SM.Debug("TCPHandler", "TCPhandler/run/break:"+ ex);
SM.Debug("TCPHandler", "TCPhandler/run/break:" + ex.toString());
isConnectionUP = false; isConnectionUP = false;
triggerTCPConnectionStateEvent(); triggerTCPConnectionStateEvent();
} }
} }
// //
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
SM.Debug("TCPhandler Crash2 on sleep:" + e.toString()); SM.Debug("TCPhandler Crash2 on sleep:"+ e);
} }
//try to restart connection //try to restart connection
if (alive && isWiFiOn) if (alive && isWiFiOn)
restartTCP(); restartTCP();
} }
SM.Debug("=================================="); SM.Debug("==================================");
SM.Debug("TCP listenThread stoped!! alive = false"); SM.Debug("TCP listenThread stoped!! alive = false");
SM.Debug("=================================="); SM.Debug("==================================");
} }
/** /**
* Create a bypass in order to trigger the ping received event * Create a bypass in order to trigger the ping received event
*/ */
@ -268,33 +259,26 @@ public class TCPhandler implements Runnable {
TCPmsgParser._firePONGReceivedEvent(); TCPmsgParser._firePONGReceivedEvent();
} }
/* Broadcast Received for WiFi Connect/Disconnect */ /* Broadcast Received for WiFi Connect/Disconnect */
public BroadcastReceiver mReceived = new BroadcastReceiver() { public BroadcastReceiver mReceived = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
final String action = intent.getAction(); final String action = intent.getAction();
SM.Debug("WIFI STATE", action); SM.Debug("WIFI STATE", action);
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); // close socket if the wifi is disconnecting or disconnected
// close socket if the wifi is disconnecting or disconnected isWiFiOn = isNetworkConnected();
if (!info.isConnectedOrConnecting()) { if (!isWiFiOn)
closeSocket(); closeSocket();
isWiFiOn = false; }
} else
isWiFiOn = true;
}
} }
}; };
/** Send a message through the TCP Socket
/** * @param seqID The messages's sequence ID (a number of order)
* Send a message through the TCP Socket * @param msg The messages which will be sent
*
* @param seqID The messages's sequence id (a number of order)
* @param msg The messages which will be sent
* @return True if the message was sent * @return True if the message was sent
*/ */
public boolean Write(String seqID, String msg) { public boolean Write(String seqID, String msg) {
@ -338,52 +322,29 @@ public class TCPhandler implements Runnable {
} }
return false; return false;
} }
public void setConnectionIsDown() {
if (input != null) {
try {
input.close();
} catch (IOException e) {
} finally {
input = null;
}
}
isConnectionUP = false;
}
/* Encrypt a string using an encryption algorithm, /* Encrypt a string using an encryption algorithm,
* in this case TEA */ * in this case TEA */
public static byte[] encryptTEA(String toEncryptData) { public static byte[] encryptTEA(String toEncryptData) {
byte[] encryptedByteArray = new byte[]{};
// no encryption // no encryption
encryptedByteArray = toEncryptData.getBytes(); return toEncryptData.getBytes();
return encryptedByteArray;
} }
/* Decrypt a string using an encryption algorithm, /* Decrypt a string using an encryption algorithm,
* in this case TEA */ * in this case TEA */
public static byte[] decryptTEA(byte[] toDecryptData) { public static byte[] decryptTEA(byte[] toDecryptData) {
byte[] decryptedByteArray = new byte[]{}; byte[] decryptedByteArray;
// no decryption // no decryption
decryptedByteArray = toDecryptData; decryptedByteArray = toDecryptData;
return decryptedByteArray; return decryptedByteArray;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void updateTCPparameters(String ip, String _port) { public void updateTCPparameters(String ip, String _port) {
// stop socket // stop socket
try { try {
if (soc != null) if (soc != null)
@ -395,9 +356,8 @@ public class TCPhandler implements Runnable {
serverHostname = ip; serverHostname = ip;
try { try {
port = Integer.parseInt(_port); port = Integer.parseInt(_port);
} catch (Exception e) { } catch (Exception ignored) { }
finally {
} finally {
port = 13589; port = 13589;
} }
} }
@ -438,23 +398,11 @@ public class TCPhandler implements Runnable {
SM.Exception("restartTCP break:" + e.toString()); SM.Exception("restartTCP break:" + e.toString());
isConnectionUP = false; isConnectionUP = false;
} }
triggerTCPConnectionStateEvent(); triggerTCPConnectionStateEvent();
} }
public boolean isAlive() { /** close Socket when unReachable */
return alive;
}
public void setAlive(boolean alive) {
this.alive = alive;
}
/**
* close Socket when unReachable
*/
public void closeSocket() { public void closeSocket() {
try { try {
input = null; input = null;
output = null; output = null;
@ -465,17 +413,15 @@ public class TCPhandler implements Runnable {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void Stop() { public void Stop() {
SM.Debug("Stopping TCP", "TCP Connection is stopping on " + AppParams.IP + ":" + port); SM.Debug("Stopping TCP", "TCP Connection is stopping on " + AppParams.IP + ":" + port);
alive = false; alive = false;
if (mReceived!= null)
if (mReceived != null)
try { try {
context.unregisterReceiver(mReceived); context.unregisterReceiver(mReceived);
} catch (Exception ex) {/* receiver not registered //*/} } catch(Exception ex) {/* receiver not registered //*/}
;
// stop thread // stop thread
if (listenThread != null) { if (listenThread != null) {
@ -484,7 +430,6 @@ public class TCPhandler implements Runnable {
moribund.interrupt(); moribund.interrupt();
} }
if (input != null) { if (input != null) {
try { try {
input.close(); input.close();
@ -493,7 +438,7 @@ public class TCPhandler implements Runnable {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (output != null) { if (output != null) {
try { try {
output.close(); output.close();
@ -502,15 +447,14 @@ public class TCPhandler implements Runnable {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (soc != null) { if (soc !=null) {
try { try {
soc.close(); soc.close();
soc = null; soc = null;
} catch (IOException e) { } catch (IOException e) {
SM.Exception("TCPClient[STOP]", "Stop break:" + e.toString()); SM.Exception("TCPClient[STOP]", "Stop break:"+ e);
} }
} }
} }
}
}