Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can fail WifiP2pManager.connect?

I have a code that perform a Wifi P2p discovery, presents the nearby devices to the user and let him select to which device he wants to connect.

The discovery is working as expected, but when I try to actually connect to the selected device, the system calls ActionListener.onFailure and passes the reason code for "Internal Error".

This is the code that initiates the connection:

public void connectToDevice(WifiP2pDevice device) {
    Log.i(TAG, "Initiating connection to " + device.deviceAddress);
    stopScan();
    WifiP2pConfig config = new WifiP2pConfig();
    config.deviceAddress = device.deviceAddress;
    config.wps.setup = WpsInfo.PBC;
    // Since we wish to send a friend request, it will be easier if
    // we'll end up as a client because we will have the group owner's
    // address immediately.
    config.groupOwnerIntent = 0;
    mP2pManager.connect(mChannel, config, mConnectionListener);
}

And the mConnectionListener is defined as follows:

protected ActionListener mConnectionListener = new ActionListener() {
    @Override
    public void onSuccess() {
        Log.i(TAG, "Conection initiated successfuly");
    }

    @Override
    public void onFailure(int reason) {
        String reasonString = reason(reason);
        Log.e(TAG, "Error while connecting to Wifi peer: " + reasonString);
    }
};

The devices are not part of any group when this error is thrown, and this happens when either device (Nexus 4 & Nexus 7) is the initiator.

Any ideas what might be the problem?

like image 720
Avi Shukron Avatar asked Nov 29 '22 01:11

Avi Shukron


1 Answers

After hours of digging inside the Android Source code, I found the problem.

The error was thrown by the WifiP2pService class. The reason was that the device I was trying to connect to was not on the internal nearby peers list.

But why the device is not on the peers list!?

After more digging I saw that when a scan is finished the peers list is cleared.

So what failed my connection is the stopScan() method that I invoked just before initiating the connection. After removing this line the connection established successfully.

Why did I stopped the scan?
I came to WiFi-Direct immediately after I finished implementing the feature in Bluetooth. The documentation on Bluetooth specifically says to stop any ongoing scan before connecting to device in order to save bandwidth and speed up the process. So I thought to do the same on WiFi-Direct. Don't do that.

like image 189
Avi Shukron Avatar answered Dec 06 '22 10:12

Avi Shukron