package ajtest.mobed.yonsei;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity
{
//Variables for UI and other common TAG
TextView aj_status;
Button ScanAP, Disassociate, ForgetJJORO;
private String TAG = "AssociateJJORO Test";
//Variables for spontaneous connection
private WifiManager wifiManager;
private WiFiScanReceiver wifiScanBroadcastReceiver;
private WifiConfiguration wc = new WifiConfiguration();
private int res = -1;
private boolean found = false;
//Variables for TCP/IP message sending
private String serverIp="192.168.43.1";
public static final int SERVERPORT = 8080;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
private static final int TCP_TIMEOUT_MS = 10000;
private Thread uThread = new Thread(new udpThread());
//Variables for UCP broadcast
private static final String REMOTE_KEY = "SSNUDP";
private static final int DISCOVERY_PORT = 9000;
private static final int TIMEOUT_MS = 15000;
private static final String mChallenge = "Hey, SSN_UDP neighbors";
private String udp_receive_buff = "";
//Section for Spontaneous Connection
public void WiFiScan()
{
Log.d(TAG, "Scan AP ");
wifiManager.startScan();
}
public void Disassociate()
{
Log.d(TAG, "Disconnect ");
wifiManager.disconnect();
}
public void ForgetJJORO()
{
Log.d(TAG, "ForgetJJORO button is pressed.");
/*This part is used for delete remebered AP configuration information from the list*/
//wifiManager.disableNetwork(wc.networkId);
/*TODO: put "Triggering UDP broadcast" part here*/
if (!connected)
{
serverIpAddress = serverIp;
if (!serverIpAddress.equals(""))
{
Log.d("UDP_Activity", "UDP broadcast launched");
uThread.stop();
uThread.start();
}
}
/*This part is used to send message via TCP/IP connection*/
/*if (!connected)
{
serverIpAddress = serverIp;
if (!serverIpAddress.equals(""))
{
Thread cThread = new Thread(new ClientThread());
Log.d("ClientActivity", "connection launched");
cThread.start();
}
}*/
}
public class WiFiScanReceiver extends BroadcastReceiver
{
private static final String TAG = "WiFiScanReceiver";
@Override
public void onReceive(Context c, Intent intent)
{
List<ScanResult> results = wifiManager.getScanResults();
for (ScanResult result : results)
{
Log.d(TAG, "Scanned SSID:"+result.SSID);
if("SSN".equals(result.SSID)) // this SSN needn't to be quoted by double-quotation marks
{
Log.d(TAG, "Target found!!!!!!!!!!!!!!!!!!!!");
// wc.SSID = "\"zzozzoro\""; "\"jjoro\""
wc.SSID = "\"SSN\""; //this part must be quoted by double quotation marks(e.g., "/"****/"")
wc.preSharedKey = "\"comsys505\""; //keys also must be quoted by double quotation marks(e.g., "/"****/"")
wc.hiddenSSID = false;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
if(found == false)
{
res = wifiManager.addNetwork(wc);
Log.d(TAG, "add Network returned "+ res );
boolean b = wifiManager.enableNetwork(res, true);
Log.d(TAG, "enableNetwork returned " + b );
//startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
found = true;
break;
}
}
}
}
}
/*Section for TCP/IP communication client part*/
public class ClientThread implements Runnable
{
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
// socket.setSoTimeout(TCP_TIMEOUT_MS);
connected = true;
while (connected)
{
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
}
catch (Exception e)
{
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
}
catch (Exception e)
{
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
/*Section for UDP broadcast*/
public class udpThread implements Runnable
{
public void run()
{
try
{
DatagramSocket socket = new DatagramSocket(DISCOVERY_PORT);
socket.setSoTimeout(TIMEOUT_MS);
// socket.setBroadcast(true);
// sendDiscoveryRequest(socket);
listenForResponses(socket);
handler.post(new Runnable() {
@Override
public void run()
{
// do whatever you want to the front end
// this is where you can be creative
aj_status.setText(udp_receive_buff);
}
});
if(socket.getSoTimeout()>0)
{
Log.d(TAG, "Socket time out, is closing. TIMEOUT_MS: " + TIMEOUT_MS);
socket.close();
}
/* int port = 9000;
DatagramSocket socket = new DatagramSocket(DISCOVERY_PORT);
socket.setBroadcast(true);
DatagramPacket packet;
for (int i = 0; i < 5; i++)
{
byte[] buf = new byte[1024];
Log.i(TAG, "Listening");
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(),0,packet.getLength());
aj_status.setText(received);
Log.i(TAG, "Quote of the Moment: " + received);
}
socket.close();*/
}
catch (IOException e)
{
Log.e(TAG, "Error: ", e);
}
}
}
/**
* Send a broadcast UDP packet containing a request for boxee services to
* announce themselves.
*
* @throws IOException
*/
private void sendDiscoveryRequest(DatagramSocket socket) throws IOException
{
String data = String
.format(
"<bdp1 cmd=\"discover\" application=\"iphone_remote\" challenge=\"%s\" signature=\"%s\"/>",
mChallenge, getSignature(mChallenge));
Log.d(TAG, "Sending data " + data);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
}
/**
* Calculate the broadcast IP we need to send the packet along. If we send it
* to 255.255.255.255, it never gets sent. I guess this has something to do
* with the mobile network not wanting to do broadcast.
*/
private InetAddress getBroadcastAddress() throws IOException
{
DhcpInfo dhcp = wifiManager.getDhcpInfo();
if (dhcp == null)
{
Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
//functions to calculate broadcastAddress from the current address
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
Log.d(TAG, "Broadcast Address" + InetAddress.getByAddress(quads));
//Returned address is 192.168.43.255
return InetAddress.getByAddress(quads);
// return InetAddress.getByName("192.168.43.1");
}
/**
* Listen on socket for responses, timing out after TIMEOUT_MS
*
* @param socket
* socket on which the announcement request was sent
* @throws IOException
*/
private void listenForResponses(DatagramSocket socket) throws IOException {
byte[] buf = new byte[1024];
try {
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
udp_receive_buff = new String(packet.getData(), 0, packet.getLength());
Log.d(TAG, "Received response " + udp_receive_buff);
}
} catch (SocketTimeoutException e) {
Log.d(TAG, "Receive timed out");
}
}
/**
* Calculate the signature we need to send with the request. It is a string
* containing the hex md5sum of the challenge and REMOTE_KEY.
*
* @return signature string
*/
private String getSignature(String challenge)
{
MessageDigest digest;
byte[] md5sum = null;
try
{
digest = java.security.MessageDigest.getInstance("MD5");
digest.update(challenge.getBytes());
digest.update(REMOTE_KEY.getBytes());
md5sum = digest.digest();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
StringBuffer hexString = new StringBuffer();
for (int k = 0; k < md5sum.length; ++k)
{
String s = Integer.toHexString((int) md5sum[k] & 0xFF);
if (s.length() == 1)
hexString.append('0');
hexString.append(s);
}
return hexString.toString();
}
/* public static void main(String[] args)
{
new Discoverer(null).start();
while (true) {
}
}*/
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView();
setContentView(R.layout.main);
wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if(wifiScanBroadcastReceiver == null)
wifiScanBroadcastReceiver = new WiFiScanReceiver();
// registerReceiver(wifiScanBroadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// Log.d(TAG, "Listener Registered");
ScanAP = (Button)findViewById(R.id.scanap);
Disassociate = (Button)findViewById(R.id.disassociatejjoro);
ForgetJJORO = (Button)findViewById(R.id.forgetjjoro);
aj_status = (TextView)findViewById(R.id.clientStatus);
udp_receive_buff = "";
ScanAP.setOnClickListener
(new OnClickListener()
{
public void onClick(View v)
{
WiFiScan();
}
}
);
Disassociate.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Disassociate();
}
});
ForgetJJORO.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
ForgetJJORO();
}
}
);
}//onCreate() end
@Override
public void onStop() {
uThread.stop();
super.onStop();
}
@Override
public void onDestroy()
{
uThread.stop();
super.onDestroy();
}
}
|