Compare commits

..

No commits in common. "79234c9830475ff4d498f9911168025d943213c8" and "3935b3ad0ba87340bed5974752354f4814ecc063" have entirely different histories.

2 changed files with 137 additions and 81 deletions

View File

@ -5,6 +5,7 @@ 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;
@ -37,19 +38,21 @@ 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 final Context context; private Context context;
private boolean isWiFiOn; private boolean isWiFiOn = true;
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<>(); msgList = new LinkedList<TCPmsg>();
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.
@ -61,6 +64,7 @@ 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) {
@ -68,20 +72,18 @@ public class TCPhandler implements Runnable {
} }
} }
}, 0, 3000); }, 0, 3000);
// get WiFi state // get WiFi state
isWiFiOn = isNetworkConnected(); ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
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 {
@ -98,19 +100,20 @@ public class TCPhandler implements Runnable {
isConnectionUP = true; isConnectionUP = true;
triggerTCPConnectionStateEvent(); triggerTCPConnectionStateEvent();
} }
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
SM.Debug("UnknownHostException", "TCPhandler break:"+ e); SM.Debug("UnknownHostException", "TCPhandler break:" + e.toString());
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
SM.Debug("IllegalArgumentException", "TCPhandler break:"+ e); SM.Debug("IllegalArgumentException", "TCPhandler break:" + e.toString());
} catch (IOException e) { } catch (IOException e) {
SM.Debug("IOException", "TCPhandler break:"+ e); SM.Debug("IOException", "TCPhandler break:" + e.toString());
} }
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); SM.Debug("TCPhandler Crash1 on sleep:" + e.toString());
} }
while (Boolean.TRUE.equals(isConnectionUP)) { while (Boolean.TRUE.equals(isConnectionUP)) {
@ -163,7 +166,7 @@ public class TCPhandler implements Runnable {
//end process leftover //end process leftover
String data = ""; String data = "";
int n = 0; n = 0;
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
// read data into buffer // read data into buffer
@ -178,6 +181,7 @@ 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);
@ -186,72 +190,77 @@ 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; {
leftOver = ""; data = leftOver + data;
} 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 expected string message is smaller then actual string then exit processing; if (messLen > data.length()) {
if (messLen > data.length()) { leftOver = data; // Add by bigu
leftOver = data; // Add by bigu continue;
continue; }
} //perform cut
//perform cut temMSG = data.substring(0, messLen).toCharArray();
temMSG = data.substring(0,messLen).toCharArray(); leftOver = data.substring(messLen, data.length());
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) {
SM.Debug("TCPHandler", "TCPhandler/run/break:"+ ex); } catch (Exception 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); SM.Debug("TCPhandler Crash2 on sleep:" + e.toString());
} }
//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
*/ */
@ -259,26 +268,33 @@ 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)) {
// close socket if the wifi is disconnecting or disconnected NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
isWiFiOn = isNetworkConnected(); // close socket if the wifi is disconnecting or disconnected
if (!isWiFiOn) if (!info.isConnectedOrConnecting()) {
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) /**
* @param msg The messages which will be sent * Send a message through the TCP Socket
*
* @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) {
@ -322,29 +338,52 @@ 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
return toEncryptData.getBytes(); encryptedByteArray = 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; byte[] decryptedByteArray = new byte[]{};
// 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)
@ -356,8 +395,9 @@ public class TCPhandler implements Runnable {
serverHostname = ip; serverHostname = ip;
try { try {
port = Integer.parseInt(_port); port = Integer.parseInt(_port);
} catch (Exception ignored) { } } catch (Exception e) {
finally {
} finally {
port = 13589; port = 13589;
} }
} }
@ -398,11 +438,23 @@ public class TCPhandler implements Runnable {
SM.Exception("restartTCP break:" + e.toString()); SM.Exception("restartTCP break:" + e.toString());
isConnectionUP = false; isConnectionUP = false;
} }
triggerTCPConnectionStateEvent(); triggerTCPConnectionStateEvent();
} }
/** close Socket when unReachable */ public boolean isAlive() {
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;
@ -413,15 +465,17 @@ 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) {
@ -430,6 +484,7 @@ public class TCPhandler implements Runnable {
moribund.interrupt(); moribund.interrupt();
} }
if (input != null) { if (input != null) {
try { try {
input.close(); input.close();
@ -438,7 +493,7 @@ public class TCPhandler implements Runnable {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (output != null) { if (output != null) {
try { try {
output.close(); output.close();
@ -447,14 +502,15 @@ 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); SM.Exception("TCPClient[STOP]", "Stop break:" + e.toString());
} }
} }
} }
}
}