소스 검색

Added Wifi Direct Help

Julien Clauter 9 년 전
부모
커밋
af1741e344

+ 55 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/BackgroundTask.java

@@ -0,0 +1,55 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.os.AsyncTask;
+
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class BackgroundTask extends AsyncTask<Void, Void, String> {
+
+    private boolean isInterrupted;
+
+    public void interrupt(boolean b){
+        this.isInterrupted = b;
+    }
+
+    public boolean isInterrupted() {
+        return isInterrupted;
+    }
+
+    public void setInterrupted(boolean isInterrupted) {
+        this.isInterrupted = isInterrupted;
+    }
+
+
+    public void performInBackground(){
+
+    }
+
+    @Override
+    protected String doInBackground(Void... params) {
+        this.performInBackground();
+        return null;
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
+     */
+    @Override
+    protected void onPostExecute(String result) {
+
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see android.os.AsyncTask#onPreExecute()
+     */
+    @Override
+    protected void onPreExecute() {
+
+
+    }
+
+}

+ 211 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pBroadcastReceiver.java

@@ -0,0 +1,211 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.net.NetworkInfo;
+import android.net.wifi.WpsInfo;
+import android.net.wifi.p2p.WifiP2pConfig;
+import android.net.wifi.p2p.WifiP2pDevice;
+import android.net.wifi.p2p.WifiP2pDeviceList;
+import android.net.wifi.p2p.WifiP2pInfo;
+import android.net.wifi.p2p.WifiP2pManager;
+import android.util.Log;
+
+import com.example.android.wifidirect.WiFiDirectActivity;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pBroadcastReceiver extends BroadcastReceiver implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
+
+    public interface WiFiP2pBroadcastListener {
+        public void discoveredDevices(List<WifiP2pDevice> peers);
+        public void wifiP2pIsEnabled(boolean enabled);
+        public void didConnect(boolean isHost, WifiP2pInfo connectionInfo);
+        public void failedToConnect();
+        public void didDisconnect();
+        public void failedToDisconnect();
+        public void deviceIsUpdated(WifiP2pDevice device);
+    }
+
+    private WifiP2pManager manager;
+    private WifiP2pManager.Channel channel;
+    //private WifiP2pManager.PeerListListener peerListListener;
+    //private WifiP2pManager.ConnectionInfoListener connectionInfoListener;
+
+    static boolean setIsWifiP2pEnabled;
+
+    private WiFiP2pBroadcastListener eventListener;
+
+    /**
+     * @param manager WifiP2pManager system service
+     * @param channel Wifi p2p channel
+     * @param listener WiFiP2pBroadcastListener
+     */
+    public WiFiP2pBroadcastReceiver(WifiP2pManager manager,
+                                    WifiP2pManager.Channel channel,
+                                    WiFiP2pBroadcastListener listener) {
+        super();
+        this.manager = manager;
+        this.channel = channel;
+        this.eventListener = listener;
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
+     * android.content.Intent)
+     */
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        String action = intent.getAction();
+        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
+
+            // UI update to indicate wifi p2p status.
+            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
+            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
+                // Wifi Direct mode is enabled
+                setIsWifiP2pEnabled = (true);
+            } else {
+                setIsWifiP2pEnabled =(false);
+            }
+            this.eventListener.wifiP2pIsEnabled(setIsWifiP2pEnabled);
+
+            Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
+
+        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
+            // THE DEVICE LIST CHANGED
+            // REQUEST THE LIST OF DEVICES
+            Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
+            if (manager != null) {
+                manager.requestPeers(channel, this);
+            }
+        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
+
+            if (manager == null) {
+                return;
+            }
+
+            NetworkInfo networkInfo = (NetworkInfo) intent
+                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
+
+            if (networkInfo.isConnected()) {
+
+                // we are connected with the other device, request connection
+                // info to find group owner IP
+                manager.requestConnectionInfo(channel, this);
+            } else {
+                // It's a disconnect
+                this.eventListener.didDisconnect();
+            }
+        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
+            WifiP2pDevice device = intent.getParcelableExtra( WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
+            this.eventListener.deviceIsUpdated(device);
+        }
+    }
+
+
+    // CONNECTION TO A DEVICE
+    // ConnectionInfoListener
+    @Override
+    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
+
+        //
+        // The owner IP is now known.
+        //boolean thisDeviceIsHost = info.isGroupOwner;
+        // InetAddress from WifiP2pInfo struct.
+        //String ownerIP = info.groupOwnerAddress.getHostAddress();
+
+        // After the group negotiation, we assign the group owner as the file
+        // server. The file server is single threaded, single connection server
+        // socket.
+
+        if (info.groupFormed){
+            if (info.isGroupOwner) {
+                //new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text)).execute();
+            } else  {
+                // The other device acts as the client. In this case, we enable the
+                // get file button.
+            }
+            this.eventListener.didConnect(info.isGroupOwner, info);
+        }
+    }
+
+    // AVAILABLE DEVICES
+    // PEERLISTLISTENER
+    @Override
+    public void onPeersAvailable(WifiP2pDeviceList peerList) {
+
+        List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
+        peers.addAll(peerList.getDeviceList());
+
+        if (peers.size() == 0) {
+            Log.d(WiFiDirectActivity.TAG, "No devices found");
+        }
+
+        this.eventListener.discoveredDevices(peers);
+        // DISMISS PROGRESS IF NEEDED
+    }
+
+
+    public void connect(WifiP2pDevice device){
+        WifiP2pConfig config = new WifiP2pConfig();
+        config.deviceAddress = device.deviceAddress;
+        config.wps.setup = WpsInfo.PBC;
+        manager.connect(channel, config, new WifiP2pManager.ActionListener() {
+            private WiFiP2pBroadcastListener eventListener;
+            @Override
+            public void onSuccess() {
+                // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
+            }
+
+            @Override
+            public void onFailure(int reason) {
+                this.eventListener.failedToConnect();
+            }
+
+            public WifiP2pManager.ActionListener init(WiFiP2pBroadcastListener eventListener){
+                this.eventListener = eventListener;
+                return this;
+            }
+        }.init(this.eventListener));
+    }
+
+    public void disconnect() {
+
+        manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
+            private WiFiP2pBroadcastListener eventListener;
+
+            @Override
+            public void onFailure(int reasonCode) {
+                //Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
+                this.eventListener.failedToDisconnect();
+            }
+
+            @Override
+            public void onSuccess() {
+                this.eventListener.didDisconnect();
+            }
+
+            public WifiP2pManager.ActionListener init(WiFiP2pBroadcastListener eventListener){
+                this.eventListener = eventListener;
+                return this;
+            }
+        }.init(this.eventListener));
+    }
+
+    public void discoverDevices(){
+        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
+            @Override
+            public void onSuccess() {
+            }
+            @Override
+            public void onFailure(int reasonCode) {
+            }
+        });
+    }
+}

+ 152 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pClientTask.java

@@ -0,0 +1,152 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.util.Log;
+
+import com.example.android.wifidirect.WiFiDirectActivity;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pClientTask extends BackgroundTask {
+
+    public interface WiFiP2pCompletionListener {
+        public void didSucceed();
+        public void didFail();
+    }
+
+    private String hostIP;
+    private Socket socket;
+    private WiFiP2pCompletionListener completionListener;
+
+    public String getHostIP() {
+        return hostIP;
+    }
+
+    public void setHostIP(String hostIP) {
+        this.hostIP = hostIP;
+    }
+
+
+    public int port(){
+        return 8988;
+    }
+    public int time_out(){
+        return 1000;
+    }
+
+
+    public WiFiP2pClientTask(String hostIP, WiFiP2pCompletionListener l){
+        super();
+        this.hostIP = hostIP;
+        this.completionListener = l;
+    }
+
+
+    @Override
+    public void interrupt(boolean b){
+        super.interrupt(b);
+        if (b && this.socket != null) {
+            try {
+                this.socket.close();
+            } catch (IOException e) {
+                Log.e("WiFiP2pClientTask", e.getMessage());
+            }
+        }
+    }
+
+    @Override
+    public void performInBackground(){
+        int tryNum = 0;
+        while (!this.isInterrupted()){
+            this.socket = new Socket();
+
+            try {
+                Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
+                socket.bind(null);
+                socket.connect((new InetSocketAddress(hostIP, this.port())), this.time_out());
+
+                Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
+                this.handleConnection(socket);
+
+                Log.d("WiFiP2pClientTask", "Client: Data written");
+            } catch (ClassNotFoundException e){
+                Log.e("WiFiP2pClientTask", e.getMessage());
+                this.completionListener.didFail();
+                return;
+            } catch (IOException e) {
+                Log.e("WiFiP2pClientTask", e.getMessage());
+
+                if(tryNum >= 5) {
+                    this.interrupt(true);
+                    break;
+                }
+
+                long seconds_to_wait = (long) Math.min(60, Math.pow(2, tryNum));
+                Log.i("client", "could not connect to server. Will try again in " + seconds_to_wait + "s");
+
+                try {
+                    Thread.sleep(seconds_to_wait * 1000);
+                } catch (InterruptedException ie){
+                }
+            } finally {
+                if (socket != null) {
+                    if (socket.isConnected()) {
+                        try {
+                            socket.close();
+                        } catch (IOException e) {
+                            // Give up
+                            e.printStackTrace();
+                            this.completionListener.didFail();
+                            return;
+                        }
+                    }
+                }
+            }
+        }
+        this.completionListener.didSucceed();
+    }
+
+
+
+    private void handleConnection(Socket client) throws IOException, ClassNotFoundException {
+        InputStream is = client.getInputStream();
+        ObjectInputStream ois = new ObjectInputStream(is);
+        OutputStream os = client.getOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(os);
+
+        Object obj = null;
+
+        do {
+            WiFiP2pSerializableObject receivedObj = (  WiFiP2pSerializableObject) obj;
+            obj = null;
+            WiFiP2pSerializableObject toSend = this.handleReceivedObject(receivedObj);
+            if (toSend != null) {
+                oos.writeObject(toSend);
+                oos.flush();
+                oos.reset();
+                obj = ois.readObject();
+            }
+        } while (obj != null && obj instanceof WiFiP2pSerializableObject);
+
+        oos.close();
+        os.close();
+        ois.close();
+        is.close();
+
+        this.interrupt(true);
+    }
+
+    public WiFiP2pSerializableObject handleReceivedObject(WiFiP2pSerializableObject receivedObj){
+
+        return null;
+    }
+
+}

+ 74 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pEventHandler.java

@@ -0,0 +1,74 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.IntentFilter;
+import android.net.wifi.p2p.WifiP2pDevice;
+import android.net.wifi.p2p.WifiP2pManager;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pEventHandler implements WifiP2pManager.ChannelListener {
+
+    public interface WiFiP2pEventListener extends WiFiP2pBroadcastReceiver.WiFiP2pBroadcastListener{
+
+    }
+
+    private WifiP2pManager manager;
+
+    private boolean retryChannel = false;
+
+    private final IntentFilter intentFilter = new IntentFilter();
+    private WifiP2pManager.Channel channel;
+    private WiFiP2pBroadcastReceiver receiver = null;
+
+    private WiFiP2pEventListener eventListener;
+
+    private Activity activity;
+
+
+    public WiFiP2pEventHandler(Activity activity, WiFiP2pEventListener listener){
+        this.eventListener = listener;
+        this.activity = activity;
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
+
+        manager = (WifiP2pManager) activity.getSystemService(Context.WIFI_P2P_SERVICE);
+        channel = manager.initialize(activity, activity.getMainLooper(), this);
+    }
+
+    public void onResume() {
+        receiver = new WiFiP2pBroadcastReceiver(manager, channel, this.eventListener);
+        activity.registerReceiver(receiver, intentFilter);
+    }
+
+    public void onPause() {
+        activity.unregisterReceiver(receiver);
+    }
+
+    @Override
+    public void onChannelDisconnected() {
+        // we will try once more
+        if (manager != null && !retryChannel) {
+            retryChannel = true;
+            manager.initialize(this.activity, this.activity.getMainLooper(), this);
+        } else {
+
+        }
+    }
+
+    public void connect(WifiP2pDevice device){
+        this.receiver.connect(device);
+    }
+
+    public void disconnect() {
+        this.receiver.disconnect();
+    }
+
+    public void discoverDevices(){
+        this.receiver.discoverDevices();
+    }
+}

+ 29 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pSerializableObject.java

@@ -0,0 +1,29 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import java.io.Serializable;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pSerializableObject implements Serializable {
+
+    private String methodName;
+
+    public Serializable getObjectToSend() {
+        return objectToSend;
+    }
+
+    public void setObjectToSend(Serializable objectToSend) {
+        this.objectToSend = objectToSend;
+    }
+
+    private Serializable objectToSend;
+
+    public void setMethodName(String m){
+        this.methodName = m;
+    }
+    public String getMethodName(){
+        return this.methodName;
+    }
+
+}

+ 90 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pServerTask.java

@@ -0,0 +1,90 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.os.Environment;
+import android.util.Log;
+
+import com.example.android.wifidirect.WiFiDirectActivity;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pServerTask extends BackgroundTask {
+
+    private ServerSocket serverSocket;
+
+    @Override
+    public void interrupt(boolean b){
+        super.interrupt(b);
+        if (b && this.serverSocket != null) {
+            try {
+                this.serverSocket.close();
+            } catch (IOException e) {
+                Log.e("WiFiP2pServerTask", e.getMessage());
+            }
+        }
+    }
+
+    @Override
+    public void performInBackground(){
+        while (!this.isInterrupted()){
+            try {
+                this.serverSocket = new ServerSocket(8988);
+                Log.d("WiFiP2pServerTask", "Server: Socket opened");
+                Socket client = this.serverSocket.accept();
+                Log.d("WiFiP2pServerTask", "Server: connection done");
+
+                this.handleConnection(client, this.serverSocket);
+
+                client.close();
+                serverSocket.close();
+            } catch (ClassNotFoundException e){
+                Log.e(WiFiDirectActivity.TAG, e.getMessage());
+            } catch (IOException  e) {
+                Log.e(WiFiDirectActivity.TAG, e.getMessage());
+            }
+        }
+    }
+
+
+
+    private void handleConnection(Socket client, ServerSocket server) throws IOException, ClassNotFoundException {
+        InputStream is = client.getInputStream();
+        ObjectInputStream ois = new ObjectInputStream(is);
+        OutputStream os = client.getOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(os);
+
+        Object obj = ois.readObject();
+
+        while (obj != null && obj instanceof WiFiP2pSerializableObject) {
+            WiFiP2pSerializableObject receivedObj = (  WiFiP2pSerializableObject) obj;
+            obj = null;
+            WiFiP2pSerializableObject toSend = this.handleReceivedObject(receivedObj);
+            if (toSend != null) {
+                oos.writeObject(toSend);
+                oos.flush();
+                oos.reset();
+            }
+            obj = ois.readObject();
+        }
+
+        oos.close();
+        os.close();
+        ois.close();
+        is.close();
+    }
+
+    public WiFiP2pSerializableObject handleReceivedObject(WiFiP2pSerializableObject receivedObj){
+
+        return null;
+    }
+}