1st version that works
This commit is contained in:
@ -0,0 +1,180 @@
|
||||
package com.safemobile.services;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import com.safemobile.interfaces.ITCPListener;
|
||||
import com.safemobile.lib.AppParams;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.IBinder;
|
||||
import android.widget.Toast;
|
||||
|
||||
public class TCPService extends Service {
|
||||
|
||||
private int[] startModes = {START_STICKY, START_NOT_STICKY, START_REDELIVER_INTENT};
|
||||
private int mStartMode = startModes[0]; // indicates how to behave if the service is killed
|
||||
private IBinder mBinder = new TCPBinder(); // interface for clients that bind
|
||||
private boolean mAllowRebind = true; // indicates whether onRebind should be used
|
||||
private TCPhandler tcp = null;
|
||||
private TCPmsgParser tcpParser = null;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
// create a TCP connection and a TCP msg Parser
|
||||
int port = 13589;
|
||||
try {
|
||||
port = Integer.parseInt(AppParams.PORT);
|
||||
}
|
||||
catch(Exception ex) { }
|
||||
|
||||
tcpParser = new TCPmsgParser();
|
||||
|
||||
if(tcp == null && !AppParams.IP.equalsIgnoreCase("n/a"))
|
||||
{
|
||||
tcp = new TCPhandler(getApplicationContext(), AppParams.IP, port);
|
||||
}
|
||||
|
||||
}
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
// The service is starting, due to a call to startService()
|
||||
return mStartMode;
|
||||
}
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
// A client is binding to the service with bindService()
|
||||
return mBinder;
|
||||
}
|
||||
@Override
|
||||
public boolean onUnbind(Intent intent) {
|
||||
// All clients have unbound with unbindService()
|
||||
return mAllowRebind;
|
||||
}
|
||||
@Override
|
||||
public void onRebind(Intent intent) {
|
||||
// A client is binding to the service with bindService(),
|
||||
// after onUnbind() has already been called
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
// The service is no longer used and is being destroyed
|
||||
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
/** get TCP Connection in order to send messages through TCP */
|
||||
public TCPhandler getTCPConnection()
|
||||
{
|
||||
return tcp;
|
||||
}
|
||||
|
||||
/** Add TCP Listener to TCPmsgParser */
|
||||
public boolean addITCPListener(ITCPListener listener)
|
||||
{
|
||||
if(tcpParser != null)
|
||||
tcpParser.addTCPListener(listener);
|
||||
else
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** remove all TCP Listeners */
|
||||
public boolean clearITCPListeners()
|
||||
{
|
||||
if(tcpParser != null)
|
||||
tcpParser.clearITCPListeners();
|
||||
else
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/** get TCP msg Parser in order to add a new TCP Listener */
|
||||
public TCPmsgParser getTCPmsgParser()
|
||||
{
|
||||
if(tcpParser == null)
|
||||
tcpParser = new TCPmsgParser();
|
||||
|
||||
return tcpParser;
|
||||
}
|
||||
|
||||
|
||||
/** Stop TCP Connection */
|
||||
public void stopTCPConnection()
|
||||
{
|
||||
if(tcp != null)
|
||||
{
|
||||
tcp.Stop();
|
||||
tcp = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** restart the TCP Connection after the connection parameters had been changed */
|
||||
public void recreateTCPConnection()
|
||||
{
|
||||
/*
|
||||
Thread t = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000*2);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
*/
|
||||
// create a tcp connection
|
||||
int port = 13589;
|
||||
try {
|
||||
port = Integer.parseInt(AppParams.PORT);
|
||||
}
|
||||
catch(Exception ex) { }
|
||||
tcp = new TCPhandler(getApplicationContext(), AppParams.IP, port);
|
||||
/* }
|
||||
});
|
||||
t.start();
|
||||
*/
|
||||
}
|
||||
|
||||
public void recreateTCPConnection(String _ip, String _port)
|
||||
{
|
||||
// create a tcp connection
|
||||
int port = 13589;
|
||||
try {
|
||||
port = Integer.parseInt(_port);
|
||||
}
|
||||
catch(Exception ex) { }
|
||||
tcp = new TCPhandler(getApplicationContext(), _ip, port);
|
||||
}
|
||||
|
||||
public void updateTCPparameters(String ip, String _port)
|
||||
{
|
||||
if(tcp!=null)
|
||||
tcp.updateTCPparameters(ip, _port);
|
||||
else
|
||||
recreateTCPConnection();
|
||||
}
|
||||
|
||||
/** recreate a TCPmsgParser */
|
||||
public void recreateTCPmsgParser()
|
||||
{
|
||||
tcpParser = new TCPmsgParser();
|
||||
}
|
||||
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
public String getCurrentTime() {
|
||||
SimpleDateFormat dateformat =
|
||||
new SimpleDateFormat("HH:mm:ss MM/dd/yyyy");
|
||||
return (dateformat.format(new Date()));
|
||||
}
|
||||
|
||||
/** get TCPService Binder */
|
||||
public class TCPBinder extends Binder {
|
||||
public TCPService getService() {
|
||||
return TCPService.this;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,704 @@
|
||||
package com.safemobile.services;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.LinkedList;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
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;
|
||||
import com.safemobile.lib.SM;
|
||||
import com.safemobile.lib.TCPmsg;
|
||||
|
||||
|
||||
public class TCPhandler implements Runnable
|
||||
{
|
||||
private boolean alive = true;
|
||||
|
||||
public String serverHostname = new String ("10.120.1.114");//
|
||||
private int port = 13579;
|
||||
private Thread listenThread;
|
||||
private Socket soc =null;
|
||||
|
||||
//private BufferedReader recv;
|
||||
//private PrintWriter writer;
|
||||
|
||||
private DataInputStream input;
|
||||
private DataOutputStream output;
|
||||
private Timer timer;
|
||||
|
||||
private String leftOver = "";
|
||||
|
||||
public static LinkedList<TCPmsg> msgList;
|
||||
private volatile int n=0;
|
||||
|
||||
public Boolean isConnectionUP = false;
|
||||
public Boolean previousConnectionWasUP = false;
|
||||
|
||||
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<TCPmsg>();
|
||||
SM.Debug("---TCPhandler constructor [" + hostName + "," + p + "] ---");
|
||||
listenThread = new Thread(this, "TCPlisten");
|
||||
listenThread.start(); // (2) Start the thread.
|
||||
|
||||
|
||||
// create timer to check socket status
|
||||
timer = new Timer();
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
//Looper.prepare();
|
||||
//mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
// get if is authenticated
|
||||
//Write("0.0", "d");
|
||||
previousConnectionWasUP = isConnectionUP;
|
||||
|
||||
// try to send something
|
||||
TCPmsgParser._fireonTCPConnectionStatusEvent(isConnectionUP, previousConnectionWasUP);
|
||||
}
|
||||
catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
SM.Exception("TIMERException", e.toString());
|
||||
}
|
||||
}
|
||||
}, 0, 3000);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
if(soc!=null)
|
||||
soc.close();
|
||||
|
||||
soc = new Socket();
|
||||
soc.connect(new InetSocketAddress(serverHostname, port), 5000);
|
||||
|
||||
//soc.setSoTimeout(3000);
|
||||
//SM.Debug("Socket timeout:" + soc.getSoTimeout() );
|
||||
//soc.setSoTimeout(5000);
|
||||
|
||||
input = new DataInputStream(soc.getInputStream());
|
||||
output = new DataOutputStream(soc.getOutputStream());
|
||||
|
||||
//recv= new BufferedReader(new InputStreamReader(soc.getInputStream()));
|
||||
//writer =new PrintWriter(soc.getOutputStream()) ;
|
||||
|
||||
|
||||
if(soc !=null) {
|
||||
//previousConnectionWasUP = isConnectionUP;
|
||||
isConnectionUP = true;
|
||||
triggerTCPConnectionStateEvent();
|
||||
}
|
||||
|
||||
}
|
||||
catch (UnknownHostException e)
|
||||
{
|
||||
SM.Debug("UnknownHostException", "TCPhandler break:"+e.toString());
|
||||
}
|
||||
catch (IllegalArgumentException e)
|
||||
{
|
||||
SM.Debug("IllegalArgumentException", "TCPhandler break:"+e.toString());
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
SM.Debug("IOException", "TCPhandler break:"+e.toString());
|
||||
}
|
||||
|
||||
while(alive)
|
||||
{
|
||||
//SM.Debug("Waiting for data...");
|
||||
try {
|
||||
Thread.sleep(3000);
|
||||
} catch (InterruptedException e) {
|
||||
SM.Debug("TCPhandler Crash1 on sleep:"+e.toString());
|
||||
}
|
||||
|
||||
while(isConnectionUP)
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(100);
|
||||
//SM.Debug("Waiting for data...");
|
||||
//process leftover
|
||||
try
|
||||
{
|
||||
boolean FinishLeftOver =true;
|
||||
while (FinishLeftOver)
|
||||
{
|
||||
// add this replacement if message length doesn't contain the last #
|
||||
// leftOver = leftOver.replace("##", "#");
|
||||
String[] tempArr2 = leftOver.split("#");
|
||||
if (tempArr2.length > 1)
|
||||
{
|
||||
int messLen;
|
||||
try
|
||||
{
|
||||
messLen = Integer.parseInt(tempArr2[1]);
|
||||
|
||||
//TODO talk to Gaby to fix this on Bridge
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
SM.Debug("leftovers", "incorect msg len leftOver =" + tempArr2[1]);
|
||||
messLen =-1;
|
||||
}
|
||||
|
||||
if(messLen>leftOver.length())
|
||||
{
|
||||
FinishLeftOver =false;
|
||||
break;
|
||||
}
|
||||
else if(messLen==leftOver.length())
|
||||
{
|
||||
TCPmsg msg = new TCPmsg(leftOver.toCharArray());
|
||||
SM.Debug("leftovers", "RX from leftOver:"+msg.allData);
|
||||
|
||||
if(msg.allData.contains("#92#"))
|
||||
prioritizePongReceived();
|
||||
|
||||
msgList.add(msg);
|
||||
leftOver ="";
|
||||
FinishLeftOver =false;
|
||||
break;
|
||||
}
|
||||
else // we have more message in leftover
|
||||
{
|
||||
TCPmsg msg = new TCPmsg(leftOver.substring(0,messLen).toCharArray());
|
||||
SM.Debug("leftovers", "RX from leftOver:"+msg.allData);
|
||||
|
||||
if(msg.allData.contains("#92#"))
|
||||
prioritizePongReceived();
|
||||
|
||||
msgList.add(msg);
|
||||
leftOver = leftOver.substring(messLen,leftOver.length());
|
||||
}
|
||||
}
|
||||
else FinishLeftOver = false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
SM.Debug("leftovers", "Error on process leftover"+e.toString());
|
||||
}
|
||||
//end process leftover
|
||||
|
||||
String data ="";
|
||||
n=0;
|
||||
//char[] buf = new char[1024];
|
||||
//n = recv.read(buf);
|
||||
|
||||
byte[] buf = new byte[1024];
|
||||
// read data into buffer
|
||||
n = input.read(buf);
|
||||
//connection closed by server
|
||||
if(n==-1)
|
||||
{
|
||||
SM.Debug("TCP Client", "Connection closed by server!");
|
||||
soc.close();
|
||||
//previousConnectionWasUP = isConnectionUP;
|
||||
isConnectionUP = false;
|
||||
triggerTCPConnectionStateEvent();
|
||||
soc = null;
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
byte[] temp = new byte[n];
|
||||
for(int i=0;i<n;i++) temp[i] = buf[i];
|
||||
//String data =new String(temp);
|
||||
|
||||
// decryptData
|
||||
temp = decryptTEA(temp);
|
||||
|
||||
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 = "";
|
||||
}
|
||||
|
||||
//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
|
||||
// for(int i=0;i<tempArr.length;i++)
|
||||
// SM.Debug("I:"+i+" tempArr[i]:"+tempArr[i]);
|
||||
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)
|
||||
{
|
||||
//SM.Debug("messLen not int=" + messLen +" tempArr[1]:" +tempArr[1]);
|
||||
continue;
|
||||
}
|
||||
char[] temMSG = data.toCharArray();
|
||||
//SM.Debug("MessLen:"+messLen+" Data len:"+data.length()+"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>n)
|
||||
{
|
||||
//SM.Debug("duda","messLen=" + messLen +" data.length():" +data.length()+"n:"+n);
|
||||
leftOver = data; // Add by bigu
|
||||
continue;
|
||||
}
|
||||
//perform cut
|
||||
//SM.Debug("We got leftover ....message length("+messLen+") != actual length("+data.length()+")");
|
||||
temMSG = data.substring(0,messLen).toCharArray();
|
||||
//SM.Debug("temMSG:"+temMSG.toString());
|
||||
leftOver = data.substring(messLen,data.length());
|
||||
//SM.Debug("leftOver:"+leftOver);
|
||||
//leftOver = data.substring(messLen,n);
|
||||
//SM.Debug("left over string:"+leftOver);
|
||||
}
|
||||
//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.toString());
|
||||
//previousConnectionWasUP = isConnectionUP;
|
||||
isConnectionUP = false;
|
||||
triggerTCPConnectionStateEvent();
|
||||
}
|
||||
}//while(connOK)
|
||||
|
||||
|
||||
//
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
SM.Debug("TCPhandler Crash2 on sleep:"+e.toString());
|
||||
//previousConnectionWasUP = isConnectionUP;
|
||||
}
|
||||
|
||||
//try to restart connection
|
||||
if(alive && isWiFiOn)
|
||||
RestartTCP();
|
||||
|
||||
}//while(alive)
|
||||
SM.Debug("==================================");
|
||||
SM.Debug("TCP listenThread stoped!! alive = false");
|
||||
SM.Debug("==================================");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a bypass in order to trigger the ping received event
|
||||
*/
|
||||
private void prioritizePongReceived() {
|
||||
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)){
|
||||
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
|
||||
* @return True if the message was sent
|
||||
*/
|
||||
public boolean Write(String seqID, String msg)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
/*
|
||||
if(writer != null)
|
||||
{
|
||||
String cmdok = "#" + seqID + msg;
|
||||
Integer tmp = cmdok.length() + 1;
|
||||
//SM.Debug("tmp:"+tmp);
|
||||
|
||||
tmp += Integer.toString(tmp).length();// tmp.ToString().Length;
|
||||
if((tmp==10)||(tmp==100)||(tmp==1000)) tmp++;
|
||||
cmdok = "#" + Integer.toString(tmp) + cmdok;
|
||||
writer.write(encryptTEA(cmdok));
|
||||
writer.flush();
|
||||
SM.Debug("TX:"+encryptTEA(cmdok));
|
||||
return true;
|
||||
}*/
|
||||
|
||||
if(output != null)
|
||||
{
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
String cmdok = "#" + seqID + msg;
|
||||
Integer tmp = cmdok.length() + 1;
|
||||
//SM.Debug("tmp:"+tmp);
|
||||
|
||||
tmp += Integer.toString(tmp).length();// tmp.ToString().Length;
|
||||
if((tmp==10)||(tmp==100)||(tmp==1000)) tmp++;
|
||||
cmdok = "#" + Integer.toString(tmp) + cmdok;
|
||||
|
||||
byte[] mess = encryptTEA(cmdok);
|
||||
|
||||
|
||||
output.write(mess);
|
||||
output.flush();
|
||||
|
||||
// show only notACK messages
|
||||
//if(mess[3] != 0x0C)
|
||||
SM.Debug(" ", new String(mess));
|
||||
return true;
|
||||
}
|
||||
catch (IOException e) {
|
||||
//e.printStackTrace();
|
||||
SM.Exception("TCPClient[Send]", e.toString());
|
||||
} catch (InterruptedException e) {
|
||||
SM.Exception("TCPClient[Send]", e.toString());
|
||||
} catch (NoSuchElementException e) {
|
||||
SM.Exception("TCPClient[Send]", e.toString());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
SM.Debug("TCPhandler Write Procedure:"+e.toString());
|
||||
}
|
||||
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[]{};
|
||||
|
||||
/*
|
||||
//encrypt message using TEA
|
||||
try {
|
||||
encryptedByteArray = TEA.encrypt(toEncryptData);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
SM.Exception("encryptTEA Exception(UEE): " + e.toString());
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
SM.Exception("encryptTEA Exception(IOoBE): " + e.toString());
|
||||
} catch (NullPointerException e) {
|
||||
SM.Exception("encryptTEA Exception(NPE): " + e.toString());
|
||||
}
|
||||
//*/
|
||||
|
||||
// no encryption
|
||||
encryptedByteArray = toEncryptData.getBytes();
|
||||
|
||||
return encryptedByteArray;
|
||||
}
|
||||
|
||||
/* Decrypt a string using an encryption algorithm,
|
||||
* in this case TEA */
|
||||
public static byte[] decryptTEA(byte[] toDecryptData) {
|
||||
byte[] decryptedByteArray = new byte[]{};
|
||||
|
||||
/*
|
||||
String sm = "";
|
||||
for(int i=0; i<toDecryptData.length; i++)
|
||||
sm+=toDecryptData[i] + " ";
|
||||
|
||||
SM.Debug("DDDDDD: " + sm);
|
||||
//*/
|
||||
/*
|
||||
//decrypt message using TEA
|
||||
try {
|
||||
decryptedByteArray = TEA.decrypt(toDecryptData);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
SM.Exception("encryptTEA Exception(UEE): " + e.toString());
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
SM.Exception("encryptTEA Exception(IOoBE): " + e.toString());
|
||||
} catch (NullPointerException e) {
|
||||
SM.Exception("encryptTEA Exception(NPE): " + e.toString());
|
||||
}
|
||||
|
||||
String sm = "";
|
||||
for(int i=0; i<decryptedByteArray.length; i++)
|
||||
sm+= (int)decryptedByteArray[i] + " ";
|
||||
//sm = new String(decryptedByteArray.toString());
|
||||
try {
|
||||
SM.Debug("##### " + new String(decryptedByteArray, "UTF-8"));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
SM.Debug("DEcrypted: " + decryptedByteArray.toString());
|
||||
|
||||
//*/
|
||||
|
||||
// no decryption
|
||||
decryptedByteArray = toDecryptData;
|
||||
|
||||
return decryptedByteArray;
|
||||
}
|
||||
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void updateTCPparameters(String ip, String _port)
|
||||
{
|
||||
|
||||
// stop socket
|
||||
try {
|
||||
if(soc != null)
|
||||
soc.close();
|
||||
} catch (IOException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
serverHostname = ip;
|
||||
try
|
||||
{
|
||||
port = Integer.parseInt(_port);
|
||||
}
|
||||
catch (Exception e) {
|
||||
|
||||
}
|
||||
finally
|
||||
{
|
||||
port = 13589;
|
||||
}
|
||||
}
|
||||
|
||||
public void triggerTCPConnectionStateEvent() {
|
||||
if(!isConnectionUP)
|
||||
TCPmsgParser._fireTCPConnectionDownEvent(previousConnectionWasUP);
|
||||
else
|
||||
TCPmsgParser._fireTCPConnectionUpEvent(previousConnectionWasUP);
|
||||
}
|
||||
|
||||
private void RestartTCP()
|
||||
{
|
||||
try
|
||||
{
|
||||
isConnectionUP = false;
|
||||
previousConnectionWasUP = false;
|
||||
|
||||
SM.Debug("Restarting TCP...ip:"+serverHostname + ":" + port);
|
||||
soc = new Socket();
|
||||
soc.connect(new InetSocketAddress(serverHostname, port), 5000);
|
||||
|
||||
input = new DataInputStream(soc.getInputStream());
|
||||
//input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
||||
//output stream
|
||||
output = new DataOutputStream(soc.getOutputStream());
|
||||
|
||||
//recv= new BufferedReader(new InputStreamReader(soc.getInputStream()));
|
||||
//writer =new PrintWriter(soc.getOutputStream()) ;
|
||||
if(soc !=null)
|
||||
{
|
||||
//previousConnectionWasUP = isConnectionUP;
|
||||
isConnectionUP = true;
|
||||
//triggerTCPConnectionStateEvent();
|
||||
|
||||
/*
|
||||
//init connection
|
||||
boolean res = Write("0.0", "#19#" + AppParams.crtRadio.ip + "&"
|
||||
+ AppParams.crtRadio.id + "#");
|
||||
if(res){
|
||||
SM.Debug("Message (AirPadInit) sent to controller");
|
||||
}else{
|
||||
SM.Debug("Could not send message(AirPadInit)!!");
|
||||
}
|
||||
|
||||
//get
|
||||
res = Write("0.0", "#30#104#0#0#0#0#");
|
||||
if(res){
|
||||
SM.Debug("Message (GetSetZoneAndChannel) sent to app server zoneNR:"+0+ " channelNR:"+0);
|
||||
}else{
|
||||
SM.Debug("Could not send message(GetSetZoneAndChannel)!!!");
|
||||
}
|
||||
*/
|
||||
//init audio
|
||||
//AudioHandle.b_SendinitUDP = true;
|
||||
}
|
||||
|
||||
}
|
||||
catch (UnknownHostException e)
|
||||
{
|
||||
SM.Exception("RestartTCP break:"+e.toString());
|
||||
isConnectionUP = false;
|
||||
|
||||
}
|
||||
catch (IllegalArgumentException e)
|
||||
{
|
||||
SM.Debug("IllegalArgumentException", "RestartTCP break:"+e.toString());
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
SM.Exception("RestartTCP break:"+e.toString());
|
||||
isConnectionUP = false;
|
||||
}
|
||||
catch (NullPointerException e)
|
||||
{
|
||||
SM.Exception("RestartTCP break:"+e.toString());
|
||||
isConnectionUP = false;
|
||||
}
|
||||
|
||||
triggerTCPConnectionStateEvent();
|
||||
}
|
||||
|
||||
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;
|
||||
if(soc!=null)
|
||||
soc.close();
|
||||
soc = null;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
SM.Debug("Stopping TCP", "TCP Connection is stopping on " + AppParams.IP + ":" + port);
|
||||
alive = false;
|
||||
|
||||
|
||||
if(mReceived!= null)
|
||||
try{ context.unregisterReceiver(mReceived); } catch(Exception ex) {/* receiver not registered //*/};
|
||||
|
||||
// stop thread
|
||||
if(listenThread != null)
|
||||
{
|
||||
Thread moribund = listenThread;
|
||||
listenThread = null;
|
||||
moribund.interrupt();
|
||||
}
|
||||
|
||||
|
||||
if(input!=null)
|
||||
{
|
||||
try {
|
||||
input.close();
|
||||
input = null;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
if(output!=null)
|
||||
{
|
||||
try {
|
||||
output.close();
|
||||
output = null;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
if(soc !=null)
|
||||
{
|
||||
try {
|
||||
soc.close();
|
||||
soc = null;
|
||||
}
|
||||
catch (IOException e) {
|
||||
SM.Exception("TCPClient[STOP]", "Stop break:"+e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,459 @@
|
||||
package com.safemobile.services;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import com.safemobile.interfaces.ITCPListener;
|
||||
import com.safemobile.interfaces.TCPEvent;
|
||||
import com.safemobile.lib.OperationCodes;
|
||||
import com.safemobile.lib.SM;
|
||||
import com.safemobile.lib.TCPmsg;
|
||||
import com.safemobile.services.TCPhandler;
|
||||
|
||||
|
||||
public class TCPmsgParser implements Runnable{
|
||||
|
||||
|
||||
public boolean run = true;
|
||||
private TCPmsg _msg;
|
||||
private static List<ITCPListener> _listeners = new ArrayList<ITCPListener>();
|
||||
private Thread TCPmsgParserThread;
|
||||
|
||||
public TCPmsgParser()
|
||||
{
|
||||
TCPmsgParserThread = new Thread(this, "TCPmsgParserThread");
|
||||
TCPmsgParserThread.start(); // (2) Start the thread.
|
||||
}
|
||||
|
||||
public synchronized void addTCPListener( ITCPListener l ) {
|
||||
_listeners.add( l );
|
||||
}
|
||||
|
||||
public synchronized void removeTCPListener( ITCPListener l ) {
|
||||
_listeners.remove( l );
|
||||
}
|
||||
|
||||
public synchronized void clearITCPListeners() {
|
||||
_listeners.clear();
|
||||
}
|
||||
|
||||
public int getListenersSize()
|
||||
{
|
||||
return _listeners.size();
|
||||
}
|
||||
|
||||
private synchronized void _fireLoginEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onLoginReceived( event );
|
||||
}
|
||||
}
|
||||
private synchronized void _fireGPSEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onGPSReceived(event);
|
||||
}
|
||||
}
|
||||
private synchronized void _fireSMSEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onSMSReceived( event );
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireLastSMSEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onLastSMSsReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireVehEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onVehiclesReceived( event );
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireNewSMS() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onNewSMSReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireSMSconfirm() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onSMSAckReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireLastPos() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onLastPositionsReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireRadioEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onRadioMsgReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireHistPos() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onHistoryPositionsReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireHistCount() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onHistoryPositionsCountReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireAlarmList() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onAlarmsReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireAlarmACK() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).onAlarmAckReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireAlarmLive() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next() ).alarmLiveRecv(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireRecordList() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onRecordingsListReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireRecordPlay() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onRecordingPlayReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _firePOLLEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onPollReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireConnectionReplyEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onConnectionReplyReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireContactsReceivedEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onContactsListReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireRecordingsReceivedEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onRecordingsListReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void _fireTextMessagesReceivedEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onTextMessagesListReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private synchronized void _fireRecordingPlayReceivedEvent() {
|
||||
TCPEvent event = new TCPEvent( this, _msg );
|
||||
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onRecordingPlayReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static synchronized void _fireTCPConnectionDownEvent(boolean previuosWasConnectionUp) {
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onTCPConnectionDown(previuosWasConnectionUp);
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized void _fireTCPConnectionUpEvent(boolean previuosWasConnectionUp) {
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onTCPConnectionUp(previuosWasConnectionUp);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static synchronized void _fireonTCPConnectionStatusEvent(boolean isConnectionUp, boolean previuosWasConnectionUp) {
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onTCPConnectionStatusReceived(isConnectionUp, previuosWasConnectionUp);
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized void _firePONGReceivedEvent() {
|
||||
Iterator<ITCPListener> listeners = _listeners.iterator();
|
||||
while( listeners.hasNext() ) {
|
||||
( (ITCPListener) listeners.next()).onPONGReceived();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
while(run)
|
||||
{
|
||||
//SM.Debug("TCPmsgParser waiting for data...");
|
||||
sleep(1);
|
||||
|
||||
if(TCPhandler.msgList==null)
|
||||
continue;
|
||||
if(!TCPhandler.msgList.isEmpty())
|
||||
{
|
||||
try
|
||||
{
|
||||
_msg = TCPhandler.msgList.poll();
|
||||
if(_msg == null)
|
||||
continue;
|
||||
if(_msg.OK == false)
|
||||
continue;
|
||||
//parse the rest of the message;
|
||||
|
||||
switch(_msg.opCode)
|
||||
{
|
||||
case 40:{
|
||||
_fireLoginEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case 41:{
|
||||
_fireVehEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case 42:{
|
||||
_fireSMSEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case 43:{
|
||||
_fireLastSMSEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.TM_ACK:{
|
||||
_fireSMSconfirm();
|
||||
break;
|
||||
}
|
||||
case OperationCodes.TM_ACK_SD:{
|
||||
_fireSMSconfirm();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.RECEIVED_TM:{
|
||||
_fireNewSMS();
|
||||
break;
|
||||
}
|
||||
|
||||
case 45:{
|
||||
_fireLastPos();
|
||||
break;
|
||||
}
|
||||
|
||||
case 131:{
|
||||
_fireGPSEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case 231:{
|
||||
_firePOLLEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case 50:{
|
||||
_fireRadioEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case 46:{
|
||||
_fireHistPos();
|
||||
break;
|
||||
}
|
||||
|
||||
case 86:{
|
||||
_fireHistCount();
|
||||
break;
|
||||
}
|
||||
|
||||
case 47:{
|
||||
_fireAlarmList();
|
||||
break;
|
||||
}
|
||||
|
||||
case 48:{
|
||||
_fireAlarmACK();
|
||||
break;
|
||||
}
|
||||
|
||||
case 49:{
|
||||
_fireRecordList();
|
||||
break;
|
||||
}
|
||||
|
||||
case 38:{
|
||||
_fireRecordPlay();
|
||||
break;
|
||||
}
|
||||
|
||||
case 135:
|
||||
case 136:
|
||||
case 137:
|
||||
case 138:
|
||||
case 140:{
|
||||
_fireAlarmLive();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.PONG: {
|
||||
//_firePONGReceivedEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.CONNECTION_REP: {
|
||||
_fireConnectionReplyEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.CONTACTS_REP: {
|
||||
sleep(15);
|
||||
_fireContactsReceivedEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.TM_LIST_REP: {
|
||||
_fireTextMessagesReceivedEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.RECORDINGS_LIST_REP: {
|
||||
_fireRecordingsReceivedEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
case OperationCodes.RECORDING_REP: {
|
||||
_fireRecordingPlayReceivedEvent();
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
try {
|
||||
if(TCPhandler.msgList.size() > 0)
|
||||
_msg = TCPhandler.msgList.remove(0);
|
||||
}
|
||||
catch(NoSuchElementException exe)
|
||||
{
|
||||
SM.Exception("TCP msg Parser", "NoSuchElementException");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
/*
|
||||
catch (Exception e)
|
||||
{
|
||||
SM.Debug("Error on fire Event:"+e.toString());
|
||||
break;
|
||||
}
|
||||
|
||||
}*/
|
||||
SM.Debug("TCPmsgParser listen thread stoped.");
|
||||
}
|
||||
|
||||
private void sleep(int miliseconds) {
|
||||
try {
|
||||
Thread.sleep(miliseconds);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
}
|
||||
|
||||
public void clearMsgList()
|
||||
{
|
||||
TCPhandler.msgList.clear();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
run = false;
|
||||
// stop thread
|
||||
if(TCPmsgParserThread != null)
|
||||
{
|
||||
Thread moribund = TCPmsgParserThread;
|
||||
TCPmsgParserThread = null;
|
||||
moribund.interrupt();
|
||||
}
|
||||
SM.Debug("Stoping TCPmsgParser");
|
||||
}
|
||||
|
||||
}
|
280
libSafeMobile/src/main/java/com/safemobile/services/TEA.java
Normal file
280
libSafeMobile/src/main/java/com/safemobile/services/TEA.java
Normal file
@ -0,0 +1,280 @@
|
||||
package com.safemobile.services;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public class TEA {
|
||||
|
||||
private final static long DELTA = 0x9E3779B9L;
|
||||
private final static long STEPS = 32;
|
||||
private final static long UNDELTA = 0xC6EF3720L;
|
||||
private static final String password = "SafeMobileBridge";
|
||||
private static String encoding = "UTF-8";
|
||||
private static long[] encrypted;
|
||||
private static long[] decrypted;
|
||||
private static long[] key;
|
||||
|
||||
public TEA(String password, String encoding) throws UnsupportedEncodingException {
|
||||
// convert key to long
|
||||
key = convertByteArrayToLongArray(password.getBytes(encoding));
|
||||
TEA.encoding = encoding;
|
||||
}
|
||||
|
||||
public TEA(String password) throws UnsupportedEncodingException {
|
||||
// convert key to long
|
||||
key = convertByteArrayToLongArray(password.getBytes(encoding));
|
||||
}
|
||||
|
||||
|
||||
public static byte[] encrypt(String toEncrypt) throws UnsupportedEncodingException {
|
||||
encrypted = new long[200];
|
||||
|
||||
key = convertByteArrayToLongArray(password.getBytes(encoding));
|
||||
|
||||
// convert String to long array
|
||||
long[] values = convertByteArrayToLongArray(toEncrypt.getBytes(encoding));
|
||||
|
||||
encrypted = new long[values.length];
|
||||
|
||||
// encipher the long array
|
||||
for(int i=0; i<values.length; i=i+2) {
|
||||
//System.out.println("v[" + i + "]=" + values[i]);
|
||||
//System.out.println("v[" + (i+1) + "]=" + values[i+1]);
|
||||
|
||||
// get the long values that will be enciphered
|
||||
long[] v = new long[2];
|
||||
long[] w = new long[2];
|
||||
v[0] = values[i];
|
||||
v[1] = values[i+1];
|
||||
|
||||
// ENCRYPT
|
||||
encipher(v, w, key);
|
||||
|
||||
// save the encrypted values in the big string
|
||||
encrypted[i] = w[0];
|
||||
encrypted[i+1] = w[1];
|
||||
//System.out.println("\nEncrypted: " + w[0] + " | " + w[1]);
|
||||
}
|
||||
return convertLongArrayToByteArray(encrypted, false);
|
||||
}
|
||||
|
||||
/*
|
||||
public static byte[] decrypt(long[] toDecrypt) {
|
||||
// convert String to long array
|
||||
long[] values = toDecrypt;
|
||||
|
||||
decrypted = new long[values.length];
|
||||
|
||||
for(int i=0; i<values.length; i=i+2) {
|
||||
//System.out.println("v[" + i + "]=" + values[i]);
|
||||
//System.out.println("v[" + (i+1) + "]=" + values[i+1]);
|
||||
|
||||
long[] v = new long[2];
|
||||
long[] w = new long[2];
|
||||
v[0] = values[i];
|
||||
v[1] = values[i+1];
|
||||
|
||||
|
||||
// ENCRYPT
|
||||
decipher(v, w, key);
|
||||
|
||||
// save the encrypted values in the big string
|
||||
decrypted[i] = w[0];
|
||||
decrypted[i+1] = w[1];
|
||||
//System.out.println("\nEncrypted: " + w[0] + " | " + w[1]);
|
||||
}
|
||||
|
||||
return convertLongArrayToByteArray(decrypted);
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
public static byte[] decrypt(byte[] toDecrypt) throws UnsupportedEncodingException {
|
||||
// convert String containing encrypted data to long array
|
||||
long[] values = convertByteArrayToLongArray(toDecrypt);
|
||||
|
||||
decrypted = new long[values.length];
|
||||
|
||||
key = convertByteArrayToLongArray(password.getBytes(encoding));
|
||||
|
||||
for(int i=0; i<values.length; i=i+2) {
|
||||
//System.out.println("v[" + i + "]=" + values[i]);
|
||||
//System.out.println("v[" + (i+1) + "]=" + values[i+1]);
|
||||
|
||||
long[] v = new long[2];
|
||||
long[] w = new long[2];
|
||||
v[0] = values[i];
|
||||
v[1] = values[i+1];
|
||||
|
||||
// DECRYPT
|
||||
decipher(v, w, key);
|
||||
|
||||
// save the encrypted values in the big string
|
||||
decrypted[i] = w[0];
|
||||
decrypted[i+1] = w[1];
|
||||
//System.out.println("\nEncrypted: " + w[0] + " | " + w[1]);
|
||||
}
|
||||
|
||||
return convertLongArrayToByteArray(decrypted, true);
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static void encipher(long v[], long w[], long k[])
|
||||
{
|
||||
long y=v[0],z=v[1],sum=0, a=k[0],b=k[1],c=k[2],d=k[3],n=STEPS;
|
||||
|
||||
//System.out.printf("\nv[0] = %d | v[1] = %d\n", y, z);
|
||||
//System.out.printf("a=%d | b=%d | c=%d | d=%d\n", a,b,c,d);
|
||||
|
||||
while(n-- > 0)
|
||||
{
|
||||
/*
|
||||
sum += DELTA;
|
||||
y += ((z << 4)+a) ^ (z+sum) ^ ((z >> 5)+b);
|
||||
z += ((y << 4)+c) ^ (y+sum) ^ ((y >> 5)+d);
|
||||
*/
|
||||
sum = (long)((int)(sum + DELTA) & 0xFFFFFFFFL);
|
||||
|
||||
/*
|
||||
System.out.println("left: " + (ctu(z<<4) + a));
|
||||
System.out.println("center: " + ctu(z + sum));
|
||||
System.out.println("right: " + (ctu(z>>>5) + b));
|
||||
*/
|
||||
y = ctu(y + ((ctu(z<<4) + a) ^ (z + sum) ^ (ctu(z>>>5) + b)));
|
||||
z = ctu(z + ((ctu(y<<4) + c) ^ (y + sum) ^ (ctu(y>>>5) + d)));
|
||||
|
||||
//System.out.println("Y = " + y + " | " + "Z = " + z) ;
|
||||
}
|
||||
w[0]=y; w[1]=z;
|
||||
|
||||
//System.out.println("Encrypted: " + y + " | " + z);
|
||||
}
|
||||
|
||||
private static void decipher(long v[], long w[], long k[])
|
||||
{
|
||||
long y=v[0],z=v[1],sum=UNDELTA, a=k[0],b=k[1], c=k[2],d=k[3],n=STEPS;
|
||||
/* sum = delta<<5, in general sum = delta * n */
|
||||
while(n-->0)
|
||||
{
|
||||
z = ctu(z - ((ctu(y << 4)+c) ^ (y+sum) ^ (ctu(y >>> 5)+d)));
|
||||
y = ctu(y - ((ctu(z << 4)+a) ^ (z+sum) ^ (ctu(z >>> 5)+b)));
|
||||
|
||||
//System.out.println("Y = " + y + " | " + "Z = " + z) ;
|
||||
|
||||
sum -= DELTA;
|
||||
}
|
||||
w[0]=y; w[1]=z;
|
||||
//System.out.println("Y = " + y + " | " + "Z = " + z) ;
|
||||
}
|
||||
|
||||
/*
|
||||
private long convertToUnsigned(long value) {
|
||||
return (((int) value) & 0xFFFFFFFFL);
|
||||
}
|
||||
*/
|
||||
|
||||
private static long ctu (long value) {
|
||||
return (((int) value) & 0xFFFFFFFFL);
|
||||
}
|
||||
|
||||
|
||||
private static long[] convertByteArrayToLongArray(byte[] toConvert) {
|
||||
// convert string in an array of bytes
|
||||
byte[] by = toConvert;
|
||||
|
||||
|
||||
// get the size of long array considering that a long has 4bytes
|
||||
int size = (int) Math.ceil(by.length / 4);
|
||||
|
||||
// if the size of the array is an odd number I should increase it because
|
||||
// encryption needs an array of two long values
|
||||
if(size % 2 != 0)
|
||||
size++;
|
||||
|
||||
long[] values = new long[size];
|
||||
|
||||
// convert every string value to a long one by shifting 4 chars
|
||||
// a long is 4 bytes
|
||||
for(int i=0; i<by.length; i=i+4) {
|
||||
|
||||
//
|
||||
byte c4 = ((i+3 >= by.length ) ? 0 : (byte) by[i+3]);
|
||||
byte c3 = ((i+2 >= by.length ) ? 0 : (byte) by[i+2] );
|
||||
byte c2 = ((i+1 >= by.length ) ? 0 : (byte) by[i+1] );
|
||||
byte c1 = ((i >= by.length ) ? 0 : (byte) by[i] );
|
||||
|
||||
//System.out.println("###" + c4 + " | " + c3 + " | " + c2 + " | " + c1);
|
||||
|
||||
values[i/4] = ctu(((c4 & 0x00FFL) << 24) + ((c3 & 0x00FFL) << 16) + ((c2 & 0x00FFL) << 8) + ((c1 & 0x00FFL)));
|
||||
//System.out.println("##### " + (encrypted == null ? 0 : encrypted[i/4]) + " | " + values[i/4]);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
|
||||
private static byte[] convertLongArrayToByteArray(long[] array, boolean isDecrypt) {
|
||||
//String myString = "";
|
||||
byte[] byteArray = new byte[array.length * 4];
|
||||
byte[] byteArrayReduced;
|
||||
int sizeToReduce = 0;
|
||||
|
||||
// convert every bytes from a long into a char using masks
|
||||
for(int i=0; i<array.length; i++) {
|
||||
byte c1 = (byte) (array[i] & 0xFF);
|
||||
byte c2 = (byte) ((array[i] & 0x0000FF00) >> 8);
|
||||
byte c3 = (byte) ((array[i] & 0x00FF0000) >> 16);
|
||||
byte c4 = (byte) ((array[i] & 0xFF000000) >> 24);
|
||||
|
||||
//System.out.println("###" + array[i] + " | c4: " + c4 + " | " + c3 + " | " + c2 + " | " + c1);
|
||||
//*
|
||||
// remove last bytes containing 0 because they are unwanted information
|
||||
if(array.length > 1 && i==(array.length-1) && isDecrypt)
|
||||
{
|
||||
System.out.println("LAST Chunck of four");
|
||||
if (c4 != 0)
|
||||
byteArray[i*4+3] = c4;
|
||||
else
|
||||
sizeToReduce++;
|
||||
if (c3 != 0)
|
||||
byteArray[i*4+2] = c3;
|
||||
else
|
||||
sizeToReduce++;
|
||||
if (c2 != 0)
|
||||
byteArray[i*4+1] = c2;
|
||||
else
|
||||
sizeToReduce++;
|
||||
if (c1 != 0)
|
||||
byteArray[i*4] = c1;
|
||||
else
|
||||
sizeToReduce++;
|
||||
}
|
||||
// add value because it's not the last long value
|
||||
|
||||
else //*/
|
||||
{
|
||||
byteArray[i*4] = c1;
|
||||
byteArray[i*4+1] = c2;
|
||||
byteArray[i*4+2] = c3;
|
||||
byteArray[i*4+3] = c4;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// remove the 0's from the string, they were added when converting long
|
||||
//System.out.println("#### Syze to reduce : " + sizeToReduce);
|
||||
byteArrayReduced = new byte[byteArray.length - sizeToReduce];
|
||||
for(int i=0; i<(byteArray.length - sizeToReduce); i++)
|
||||
byteArrayReduced[i] = byteArray[i];
|
||||
|
||||
/*
|
||||
try {
|
||||
myString = new String ( byteArray, encoding);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}*/
|
||||
|
||||
//myString = new String(byteArray);
|
||||
|
||||
return byteArrayReduced;
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user