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