WifiP2pService的启动以及P2P的连接

这一章主要总结从WifiP2pService的启动到用户通过四种连接方式连接P2P的过程,四种方式包括:主动连接、被动连接、主动invite和被动invite。首先来看WifiP2pService的启动。


WifiP2pService的启动

WifiP2pService的创建以及启动是在SystemServer中,主要代码如下:
                    wifiP2p = new WifiP2pService(context);
                    ServiceManager.addService(Context.WIFI_P2P_SERVICE, wifiP2p);

                    wifiP2p.connectivityServiceReady();

进入到WifiP2pService的构造函数分析:
    public WifiP2pService(Context context) {
        mContext = context;

        //STOPSHIP: get this from native side
        mInterface = "p2p0";
        mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0, NETWORKTYPE, "");

        mP2pSupported = mContext.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_WIFI_DIRECT);

        mThisDevice.primaryDeviceType = mContext.getResources().getString(
                com.android.internal.R.string.config_wifi_p2p_device_type);

        mP2pStateMachine = new P2pStateMachine(TAG, mP2pSupported);
        mP2pStateMachine.start();
    }

WifiP2pService的构造函数很简单,主要是创建一个NetworkInfo的对象,然后通过PackageManagerService获取到系统是否支持P2P,然后创建一个P2pStateMachine并启动这个StateMachine,进入到P2pStateMachine中分析:
        P2pStateMachine(String name, boolean p2pSupported) {
            super(name);

            addState(mDefaultState);
                addState(mP2pNotSupportedState, mDefaultState);
                addState(mP2pDisablingState, mDefaultState);
                addState(mP2pDisabledState, mDefaultState);
                addState(mP2pEnablingState, mDefaultState);
                addState(mP2pEnabledState, mDefaultState);
                    addState(mInactiveState, mP2pEnabledState);
                    addState(mGroupCreatingState, mP2pEnabledState);
                        addState(mUserAuthorizingInviteRequestState, mGroupCreatingState);
                        addState(mUserAuthorizingNegotiationRequestState, mGroupCreatingState);
                        addState(mProvisionDiscoveryState, mGroupCreatingState);
                        addState(mGroupNegotiationState, mGroupCreatingState);
                        addState(mFrequencyConflictState, mGroupCreatingState);
                    addState(mGroupCreatedState, mP2pEnabledState);
                        addState(mUserAuthorizingJoinState, mGroupCreatedState);
                        addState(mOngoingGroupRemovalState, mGroupCreatedState);

            if (p2pSupported) {
                setInitialState(mP2pDisabledState);
            } else {
                setInitialState(mP2pNotSupportedState);
            }
            setLogRecSize(50);
            setLogOnlyTransitions(true);
        }

通过上面的构造函数,我们可以看出P2pStateMachine的各个State关系如下。并且若在支持P2P的情况下,InitialState是P2pDisabledState;若在不支持P2P的情况下,InitialState是P2pNotSupportedState。
WifiP2pService的启动以及P2P的连接_第1张图片

接着回到SystemServer中,会调用到WifiP2pService的connectivityServiceReady函数,这个函数比较简单,首先通过ServiceManager获取NETWORKMANAGEMENT_SERVICE,然后记录到mNwService中。这样WifiP2pService的启动流程就介绍完毕了,下面再来看当Enable Wifi时,如何Enable P2p。

Enable P2p


还记得我们在Wifi toggle on这个章节有说过,在WifiStateMachine的DriverStartedState中,如平台支持P2P,还将会给WifiP2pService发送CMD_ENABLE_P2P的消息,在Android 4.4的平台上面,当打开Wifi时,会同时把P2p也enable,我们从这里开始分析。首先由前面的知识,我们进入P2pDisabledState看如何处理CMD_ENABLE_P2P消息:
    class P2pDisabledState extends State {
       @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiStateMachine.CMD_ENABLE_P2P:
                    try {
                        mNwService.setInterfaceUp(mInterface);
                    } catch (RemoteException re) {
                        loge("Unable to change interface settings: " + re);
                    } catch (IllegalStateException ie) {
                        loge("Unable to change interface settings: " + ie);
                    }
                    mWifiMonitor.startMonitoring();
                    transitionTo(mP2pEnablingState);
                    break;

首先通过NetworkManagementService将P2P0设置为up状态,然后通过WifiMonitor去和wpa_supplicant建立socket连接,因为在WifiStateMachine的DriverStartedState中,wpa_supplicant已经启动成功了,所以我们这里可以直接去和wpa_supplicant通信,最后转到P2pEnablingState处理和wpa_supplicant连接成功与否的消息。

    class P2pEnablingState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.SUP_CONNECTION_EVENT:
                    if (DBG) logd("P2p socket connection successful");
                    transitionTo(mInactiveState);
                    break;
                case WifiMonitor.SUP_DISCONNECTION_EVENT:
                    loge("P2p socket connection failed");
                    transitionTo(mP2pDisabledState);
                    break;
                case WifiStateMachine.CMD_ENABLE_P2P:
                case WifiStateMachine.CMD_DISABLE_P2P_REQ:
                    deferMessage(message);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

由Wifi toggle on的知识我们可以知道,当WifiMonitor与wpa_suppliant建立socket成功后,会给P2pStateMachine发送SUP_CONNECT_EVENT消息,P2pEnablingState这时会跳转到InactiveState中,由前面P2pStateMachine的State关系图我们可以知道,P2pEnabledState是InactiveState父State,我们先到P2pEnabledState的enter函数去分析:

    class P2pEnabledState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            sendP2pStateChangedBroadcast(true);
            mNetworkInfo.setIsAvailable(true);
            sendP2pConnectionChangedBroadcast();
            initializeP2pSettings();
        }

这里主要发送两个broadcast,然后初始化一些P2p的设置,包括deviceName、DeviceType、ConfigMethods,并且获取以前persistent的相关device信息。


P2p设备扫描

当用户到Settings-->P2p中点击扫描后,就开始启动discoverPeers的流程了,首先来看一下WifiP2pManager提供给我们的文档说明:
The API is asynchronous and responses to requests from an application are on listener callbacks provided by the application. The application needs to do an initialization with  initialize(Context, Looper, WifiP2pManager.ChannelListener)  before doing any p2p operation.

这段话告诉我们WifiP2pManager提供给application的函数都是异步的,并且在调用其它p2p的方法之前,需要先调用initialize方法,那我们首先来看一下initialize的实现:
    public Channel initialize(Context srcContext, Looper srcLooper, ChannelListener listener) {
        Messenger messenger = getMessenger();
        if (messenger == null) return null;

        Channel c = new Channel(srcContext, srcLooper, listener);
        if (c.mAsyncChannel.connectSync(srcContext, c.mHandler, messenger)
                == AsyncChannel.STATUS_SUCCESSFUL) {
            return c;
        } else {
            return null;
        }
    }

这段代码主要的功能是创建一个Channel对象,Channel是将application和wifi p2p framework连接的对象,当然我们知道wifi p2p framework中最核心的还是WifiP2pService,所以Channel需要将application的消息发送给WifiP2pService,所以我们就看到函数开头的getMessenger函数,通过这个函数会利用WifiP2pService中的P2pStateMachine的handler创建一个Messenger对象并返回;然后Channel对象中又会创建一个AsyncChannel对象,通过AsyncChanne将Channel自身的handler与P2pStateMachine联系起来。我们可以简单的理解Channel是对AsyncChannel的封装,用于实现applicantion与WifiP2pService之间的异步通信。流程图文章最底下图中的左上方。

接着我们就可以调用discoverPeers来进行P2P设备的扫描了,代码如下:
    public void discoverPeers(Channel c, ActionListener listener) {
        checkChannel(c);
        c.mAsyncChannel.sendMessage(DISCOVER_PEERS, 0, c.putListener(listener));
    }

由前面Enable P2p的知识,我们知道P2pEnabledState会处理DISCOVER_PEERS消息,代码如下:
                case WifiP2pManager.DISCOVER_PEERS:
                    if (mDiscoveryBlocked) {
                        replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED,
                                WifiP2pManager.BUSY);
                        break;
                    }
                    // do not send service discovery request while normal find operation.
                    clearSupplicantServiceRequest();
                    if (mWifiNative.p2pFind(DISCOVER_TIMEOUT_S)) {
                        replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_SUCCEEDED);
                        sendP2pDiscoveryChangedBroadcast(true);
                    } else {
                        replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED,
                                WifiP2pManager.ERROR);
                    }
                    break;

P2pEnabledState处理DISCOVER_PEERS流程中主要调用WifiNative的p2pFind函数,它会向wpa_supplicant发送P2P_FIND命令。若成功发送这个命令,就会通过WifiManager中discoverPeers的第二个参数ActionListener来告知Application执行成功;若执行失败,也会通知Application,只是回调不同的方法,一个是onSuccess(),一个是onFailure()。

wpa_supplicant收到P2P_FIND后,就会开始搜索周边的P2P设备,如果有找到,则会给WifiMonitor发送P2P-DEVICE-FOUND这样的event,这个event会带有对方设备的信息,包括MAC地址、device type、设备名字以及config methods等,例如P2P-DEVICE-FOUND 02:08:22:22:ec:fb p2p_dev_addr=02:08:22:22:ec:fb pri_dev_type=10-0050F204-5 name='Android_7a5f' config_methods=0x188 dev_capab=0x25 group_capab=0x0 wfd_dev_info=0x00000600101c440032。WifiMonitor收到这样的event后,会将P2P-DEVICE-FOUND后面的data数据封装成为一个WifiP2pDevice对象,然后发送P2P_DEVICE_FOUND_EVENT消息给WIfiStateMachine处理。接着我们到P2pEnabledState看如何处理P2P_DEVICE_FOUND_EVENT:
                case WifiMonitor.P2P_DEVICE_FOUND_EVENT:
                    WifiP2pDevice device = (WifiP2pDevice) message.obj;
                    if (mThisDevice.deviceAddress.equals(device.deviceAddress)) break;
                    mPeers.updateSupplicantDetails(device);
                    sendPeersChangedBroadcast();
                    break;

mPeers是一个WifiP2pDeviceList对象,它内部维护一个全局的HashMap来维护所有找到的P2P 设备信息,HashMpa的key是P2P设备的MAC地址,值即为上面的WifiP2pDevice对象。然后通过sendPeersChangedBroadcast发送一个 WIFI_P2P_PEERS_CHANGED_ACTION的broadcast,这样WifiP2pSettings收到这个broadcast后,就可以直接通过WifiP2pDeviceList对象来访问里面的HasmMap来显示所有的P2P设备了。

连接P2P设备

这里开始介绍四种连接方式:主动连接、被动连接、主动invite和被动invite

主动连接

先来看一下这部分的总体流程图:
WifiP2pService的启动以及P2P的连接_第2张图片

当用户选择扫描到的设备列表中的一个设备后,就会开始连接流程,通过调用WifiManager.connect(Channel c, WifiP2pConfig config, ActionListener listener),其中第一个参数Channel即从initialize中返回的,第二个参数WifiP2pConfig包含对方设备的MAC地址、WPS等信息。进入到connect函数看这个方法的实现:
    public void connect(Channel c, WifiP2pConfig config, ActionListener listener) {
        checkChannel(c);
        checkP2pConfig(config);
        c.mAsyncChannel.sendMessage(CONNECT, 0, c.putListener(listener), config);
    }

通过Channel中的AsyncChannel给P2pStateMachine发送一个CONNECT消息,由前面的扫描阶段的知识,InactiveState会处理CONNECT消息:
                case WifiP2pManager.CONNECT:
                    if (DBG) logd(getName() + " sending connect");
                    WifiP2pConfig config = (WifiP2pConfig) message.obj;
                    if (isConfigInvalid(config)) {
                        loge("Dropping connect requeset " + config);
                        replyToMessage(message, WifiP2pManager.CONNECT_FAILED);
                        break;
                    }

                    mAutonomousGroup = false;
                    mWifiNative.p2pStopFind();
                    if (reinvokePersistentGroup(config)) {
                        transitionTo(mGroupNegotiationState);
                    } else {
                        transitionTo(mProvisionDiscoveryState);
                    }
                    mSavedPeerConfig = config;
                    mPeers.updateStatus(mSavedPeerConfig.deviceAddress, WifiP2pDevice.INVITED);
                    sendPeersChangedBroadcast();
                    replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED);
                    break;

这里分为persistent的连接方式和非persistent方式,对于persistent的连接,如果第一次连接成功后,wpa_supplicant会记录这次连接的所有信息,包含credential、GO MAC地址、Ssid等信息,所以判断对方是否采用persisten连接,就是去wpa_supplicant拿这些信息,并进行匹配。对于非persistent的连接方式,即采用negotiate方式,则跳转到ProvisionDiscoveryState,用于发送Provision discovery封包,ProvisionDiscoveryState的父State是GroupCreatingState。首先到GroupCreartingState和ProvisionDiscoveryState的enter函数去分析:
    class GroupCreatingState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            sendMessageDelayed(obtainMessage(GROUP_CREATING_TIMED_OUT,
                    ++mGroupCreatingTimeoutIndex, 0), GROUP_CREATING_WAIT_TIME_MS);
        }

    class ProvisionDiscoveryState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            mWifiNative.p2pProvisionDiscovery(mSavedPeerConfig);
        }

在GroupCreartingState中会发送一个delay message,用于设置P2P连接的timeout时间,timeout时间为120秒。在ProvisionDiscoveryState中调用WifiNative的p2pProvisionDiscovery向对方发送Provision discovery封包。当对方收到Provision discovery封包后,就会给我们回复provision response,wpa_supplicant处理后,会给WifiMonitor发送P2P-PROV-DISC-PBC-RESP(当WPS方式为PBC时),WifiMonitor就会给P2pStateMachine发送P2P_PROV_DISC_PBC_RSP_EVNET,来看ProvisionDiscoveryState如何处理这个消息:
                case WifiMonitor.P2P_PROV_DISC_PBC_RSP_EVENT:
                    provDisc = (WifiP2pProvDiscEvent) message.obj;
                    device = provDisc.device;
                    if (!device.deviceAddress.equals(mSavedPeerConfig.deviceAddress)) break;

                    if (mSavedPeerConfig.wps.setup == WpsInfo.PBC) {
                        if (DBG) logd("Found a match " + mSavedPeerConfig);
                        p2pConnectWithPinDisplay(mSavedPeerConfig);
                        transitionTo(mGroupNegotiationState);
                    }
                    break;

    private void p2pConnectWithPinDisplay(WifiP2pConfig config) {
        WifiP2pDevice dev = fetchCurrentDeviceDetails(config);

        String pin = mWifiNative.p2pConnect(config, dev.isGroupOwner());
        try {
            Integer.parseInt(pin);
            notifyInvitationSent(pin, config.deviceAddress);
        } catch (NumberFormatException ignore) {
            // do nothing if p2pConnect did not return a pin
        }
    }

ProvisionDiscoveryState通过调用p2pConnectWithPinDisplay,然后调用WifiNative的p2pConnect向wpa_supplicant发送P2P_CONNECT命令,如果采用keyPad的连接方式,会弹出pin码的对话框,供用户在对方设备上填入pin码;如果采用PBC的连接方式,WifiNative.p2pConnect返回”OK“,Integer.parseInt抛出异常,就不会弹出对话框了。然后ProvisionDiscoveryState跳转到GroupNegotiationState:
    class GroupNegotiationState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.P2P_GO_NEGOTIATION_SUCCESS_EVENT:
                case WifiMonitor.P2P_GROUP_FORMATION_SUCCESS_EVENT:
                    if (DBG) logd(getName() + " go success");
                    break;
                case WifiMonitor.P2P_GROUP_STARTED_EVENT:
                    mGroup = (WifiP2pGroup) message.obj;
                    if (DBG) logd(getName() + " group started");

                    if (mGroup.getNetworkId() == WifiP2pGroup.PERSISTENT_NET_ID) {
                        updatePersistentNetworks(NO_RELOAD);
                        String devAddr = mGroup.getOwner().deviceAddress;
                        mGroup.setNetworkId(mGroups.getNetworkId(devAddr,
                                mGroup.getNetworkName()));
                    }

                    if (mGroup.isGroupOwner()) {
                        if (!mAutonomousGroup) {
                            mWifiNative.setP2pGroupIdle(mGroup.getInterface(), GROUP_IDLE_TIME_S);
                        }
                        startDhcpServer(mGroup.getInterface());
                    } else {
                        mWifiNative.setP2pGroupIdle(mGroup.getInterface(), GROUP_IDLE_TIME_S);
                        mDhcpStateMachine = DhcpStateMachine.makeDhcpStateMachine(mContext,
                                P2pStateMachine.this, mGroup.getInterface());
                        // TODO: We should use DHCP state machine PRE message like WifiStateMachine
                        mWifiNative.setP2pPowerSave(mGroup.getInterface(), false);
                        mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_START_DHCP);
                        WifiP2pDevice groupOwner = mGroup.getOwner();
                        WifiP2pDevice peer = mPeers.get(groupOwner.deviceAddress);
                        if (peer != null) {
                            // update group owner details with peer details found at discovery
                            groupOwner.updateSupplicantDetails(peer);
                            mPeers.updateStatus(groupOwner.deviceAddress, WifiP2pDevice.CONNECTED);
                            sendPeersChangedBroadcast();
                        } else {
                            logw("Unknown group owner " + groupOwner);
                        }
                    }
                    transitionTo(mGroupCreatedState);
                    break;

开始Group negotiate后,wpa_supplicant会发送多个event给WifiMonitor,包括P2P-GO-NEG-SUCCESS、WPS-SUCCESS、P2P-GROUP-FORMATION-SUCCESS、P2P-GROUP-STARTED等,其中比较重要的是P2P-GROUP-STARTED这个event,WifiMonitor收到这个event后会给P2pStateMachine发送P2P_GROUP_STARTED_EVENT,收到这个消息后,GroupNegotiationState主要调用DHCP相关的StateMachine开始会两端分配IP,这里比较重要的一点是,P2pStateMachine不会调用DhcpStateMachine的registerForPreDhcpNotification,所以不会收到CMD_PRE_DHCP_ACTION等消息。然后更新group owner的相关信息,最后跳转至GroupCreatedState就表示连接完成了。

    class GroupCreatedState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            // Once connected, peer config details are invalid
            mSavedPeerConfig.invalidate();
            mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);

            updateThisDevice(WifiP2pDevice.CONNECTED);

            //DHCP server has already been started if I am a group owner
            if (mGroup.isGroupOwner()) {
                setWifiP2pInfoOnGroupFormation(NetworkUtils.numericToInetAddress(SERVER_ADDRESS));
            }

            // In case of a negotiation group, connection changed is sent
            // after a client joins. For autonomous, send now
            if (mAutonomousGroup) {
                sendP2pConnectionChangedBroadcast();
            }
        }

在DhcpStateMachine获取到IP地址以后,就会发送DhcpStateMachine.CMD_POST_DHCP_ACTION消息给P2pStateMachine,相关的处理代码如下:
                case DhcpStateMachine.CMD_POST_DHCP_ACTION:
                    DhcpResults dhcpResults = (DhcpResults) message.obj;
                    if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS &&
                            dhcpResults != null) {
                        if (DBG) logd("DhcpResults: " + dhcpResults);
                        setWifiP2pInfoOnGroupFormation(dhcpResults.serverAddress);
                        sendP2pConnectionChangedBroadcast();
                        //Turn on power save on client
                        mWifiNative.setP2pPowerSave(mGroup.getInterface(), true);
                    } else {
                        loge("DHCP failed");
                        mWifiNative.p2pGroupRemove(mGroup.getInterface());
                    }
                    break;

这里主要调用sendP2pConnectionChangedBroadcast用于广播当前连接状态的改变,WifiP2pSettings会捕获这个WIFI_P2P_CONNECTION_CHANGED_ACTION并更新UI状态为已连接
    private void sendP2pConnectionChangedBroadcast() {
        if (DBG) logd("sending p2p connection changed broadcast");
        Intent intent = new Intent(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
        intent.putExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO, new WifiP2pInfo(mWifiP2pInfo));
        intent.putExtra(WifiP2pManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo));
        intent.putExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP, new WifiP2pGroup(mGroup));
        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
        mWifiChannel.sendMessage(WifiP2pService.P2P_CONNECTION_CHANGED,
                new NetworkInfo(mNetworkInfo));
    }

被动连接

首先来看一下三种方式的连接流程图:
WifiP2pService的启动以及P2P的连接_第3张图片

当在InactiveState中,收到对方发送的P2P-PROV-DISC-PBC-REQ消息后,WifiMonitor就会给P2pStateMachine发送P2P_PROV_DISC_PBC_REQ_EVENT,来看InactiveState对这个消息的解释:
                case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT:
                case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT:
                case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT:
                    //We let the supplicant handle the provision discovery response
                    //and wait instead for the GO_NEGOTIATION_REQUEST_EVENT.
                    //Handling provision discovery and issuing a p2p_connect before
                    //group negotiation comes through causes issues
                    break;

InactiveState并不关系这些消息,而是让wpa_supplicant自行处理,等待收到GO_NEGOTIATION_REQUEST_EVENT时再来处理,再来看InactiveState如何处理GO_NEGOTIATION_REQUEST_EVENT消息:
                case WifiMonitor.P2P_GO_NEGOTIATION_REQUEST_EVENT:
                    config = (WifiP2pConfig) message.obj;
                    if (isConfigInvalid(config)) {
                        loge("Dropping GO neg request " + config);
                        break;
                    }
                    mSavedPeerConfig = config;
                    mAutonomousGroup = false;
                    mJoinExistingGroup = false;
                    transitionTo(mUserAuthorizingNegotiationRequestState);
                    break;

直接跳转至UserAuthorizingNegotiationRequsetState,到UserAuthorizingNegotiationRequsetState的enter函数去分析:
    class UserAuthorizingNegotiationRequestState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            notifyInvitationReceived();
        }

notifyInvitationReceived作用是弹出对话框,供用户选择取消或者确认,如果WPS方式是keypad或者display,则还有输入pin码的输入框或者显示框。以PBC为例,当用户点击确认后,则会给自身发送PEER_CONNECTION_USER_ACCEPT消息,来看UserAuthorizingNegotiationRequsetState如何处理:
                case PEER_CONNECTION_USER_ACCEPT:
                    mWifiNative.p2pStopFind();
                    p2pConnectWithPinDisplay(mSavedPeerConfig);
                    mPeers.updateStatus(mSavedPeerConfig.deviceAddress, WifiP2pDevice.INVITED);
                    sendPeersChangedBroadcast();
                    transitionTo(mGroupNegotiationState);
                   break;

这里也是调用p2pConnectWithPinDisplay,然后调用WifiNative的p2pConnect向wpa_supplicant发送P2P_CONNECT命令,后面transition到GroupNegoTiationState,与前面主动连接的方式一样了。

主动Invite

当设备已经形成Group时,则可以邀请其他设备加入到这个Group,形成两个及两个以上P2P设备形成的Group,从前面Group形成的知识我们知道,这时P2pStateMachine处于GroupCreatedState,WifiP2pSettings会给当前State发送CONNECT的消息,来看具体处理代码:
                case WifiP2pManager.CONNECT:
                    WifiP2pConfig config = (WifiP2pConfig) message.obj;
                    if (isConfigInvalid(config)) {
                        loge("Dropping connect requeset " + config);
                        replyToMessage(message, WifiP2pManager.CONNECT_FAILED);
                        break;
                    }
                    logd("Inviting device : " + config.deviceAddress);
                    mSavedPeerConfig = config;
                    if (mWifiNative.p2pInvite(mGroup, config.deviceAddress)) {
                        mPeers.updateStatus(config.deviceAddress, WifiP2pDevice.INVITED);
                        sendPeersChangedBroadcast();
                        replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED);
                    } else {
                        replyToMessage(message, WifiP2pManager.CONNECT_FAILED,
                                WifiP2pManager.ERROR);
                    }
                    // TODO: figure out updating the status to declined when invitation is rejected
                    break;

上面的实现中主要调用WifiNative的p2pInvite来实现邀请对方加入当前的Group中,如果成功执行并向对方发送invitate request后,WifiMonitor会收到P2P-INVITATION-RESULT,然后给P2pStateMachine发送P2P_INVITATION_RESULT_EVENT消息,来看一下处理代码:
                case WifiMonitor.P2P_INVITATION_RESULT_EVENT:
                    P2pStatus status = (P2pStatus)message.obj;
                    if (status == P2pStatus.SUCCESS) {
                        // invocation was succeeded.
                        break;
                    }
                    loge("Invitation result " + status);
                    if (status == P2pStatus.UNKNOWN_P2P_GROUP) {
                        // target device has already removed the credential.
                        // So, remove this credential accordingly.
                        int netId = mGroup.getNetworkId();
                        if (netId >= 0) {
                            if (DBG) logd("Remove unknown client from the list");
                            if (!removeClientFromList(netId,
                                    mSavedPeerConfig.deviceAddress, false)) {
                                // not found the client on the list
                                loge("Already removed the client, ignore");
                                break;
                            }
                            // try invitation.
                            sendMessage(WifiP2pManager.CONNECT, mSavedPeerConfig);
                        }
                    }
                    break;

这里主要根据P2P-INVITATION-RESULT后面带到status状态来处理persistent连接的情况,比如device A和device B前面有连接过,这时再去连接的话,应该走invitation这条路,但如果在device B上面已经把和device A连接的credential给删除了。关于persistent的连接以后再来分析。接着会收到wpa_supplicant发送的P2P_PROV_DISC_PBC_REQ或者P2P_PROV_DISC_ENTER_PIN或者P2P_PROV_DISC_SHOW_PIN的event,wifiMonitor分别会发送P2P_PROV_DISC_PBC_REQ_EVENT、P2P_PROV_DISC_ENTER_PIN_EVENT和P2P_PROV_DISC_SHOW_PIN_EVENT三个消息给P2pStateMachine,来看相关处理代码:
                case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT:
                case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT:
                case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT:
                    WifiP2pProvDiscEvent provDisc = (WifiP2pProvDiscEvent) message.obj;
                    mSavedPeerConfig = new WifiP2pConfig();
                    mSavedPeerConfig.deviceAddress = provDisc.device.deviceAddress;
                    if (message.what == WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT) {
                        mSavedPeerConfig.wps.setup = WpsInfo.KEYPAD;
                    } else if (message.what == WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT) {
                        mSavedPeerConfig.wps.setup = WpsInfo.DISPLAY;
                        mSavedPeerConfig.wps.pin = provDisc.pin;
                    } else {
                        mSavedPeerConfig.wps.setup = WpsInfo.PBC;
                    }
                    transitionTo(mUserAuthorizingJoinState);
                    break;

以P2P_PROV_DISC_PBC_REQ_EVENT为例,这里主要通过provision discovery中的消息来设置mSavedPeerConfig,记录这次连接的配置信息,然后就transition到UserAuthorizingJoinState中:
    class UserAuthorizingJoinState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            notifyInvitationReceived();
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT:
                case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT:
                case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT:
                    //Ignore more client requests
                    break;
                case PEER_CONNECTION_USER_ACCEPT:
                    //Stop discovery to avoid failure due to channel switch
                    mWifiNative.p2pStopFind();
                    if (mSavedPeerConfig.wps.setup == WpsInfo.PBC) {
                        mWifiNative.startWpsPbc(mGroup.getInterface(), null);
                    } else {
                        mWifiNative.startWpsPinKeypad(mGroup.getInterface(),
                                mSavedPeerConfig.wps.pin);
                    }
                    transitionTo(mGroupCreatedState);
                    break;
                case PEER_CONNECTION_USER_REJECT:
                    if (DBG) logd("User rejected incoming request");
                    transitionTo(mGroupCreatedState);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }

在UserAuthorizingJoinState的enter函数中,通过notifyInvitationReceived来弹出对话框给用户选择确认或者取消,以及输入pin码等。当用户点击确认后,就会发送PEER_CONNECTION_USER_ACCEPT给它自身,接看看上面代码中处理PEER_CONNECTION_USER_ACCEPT消息,主要通过调用WifiNative的startWpsPbc进行连接,然后transition到GroupCreatedState中。在GroupCreatedState会收到WPS-SUCCESS以及AP-STA-CONNECT表示连接是否成功,当WifiMonitor收到AP-STA-CONNECT后,就会给P2pStateMachine发送AP_STA_CONNECTED_EVENT,来看这一段的处理代码:
                case WifiMonitor.AP_STA_CONNECTED_EVENT:
                    WifiP2pDevice device = (WifiP2pDevice) message.obj;
                    String deviceAddress = device.deviceAddress;
                    // Clear timeout that was set when group was started.
                    mWifiNative.setP2pGroupIdle(mGroup.getInterface(), 0);
                    if (deviceAddress != null) {
                        if (mPeers.get(deviceAddress) != null) {
                            mGroup.addClient(mPeers.get(deviceAddress));
                        } else {
                            mGroup.addClient(deviceAddress);
                        }
                        mPeers.updateStatus(deviceAddress, WifiP2pDevice.CONNECTED);
                        if (DBG) logd(getName() + " ap sta connected");
                        sendPeersChangedBroadcast();
                    } else {
                        loge("Connect on null device address, ignore");
                    }
                    sendP2pConnectionChangedBroadcast();
                    break;

被动Invite

当已经形成Group的设备点击连接我们设备后,就会给我们设备发送invitation request,由前面的知识我们知道,这个request会被WifiMonitor接收并转换为P2P_INVITATION_RECEIVED_EVENT发送给P2pStateMachine,由于当前设备处于InactiveState,来看这个消息的处理:
                case WifiMonitor.P2P_INVITATION_RECEIVED_EVENT:
                    WifiP2pGroup group = (WifiP2pGroup) message.obj;
                    WifiP2pDevice owner = group.getOwner();

                    if (owner == null) {
                        loge("Ignored invitation from null owner");
                        break;
                    }

                    config = new WifiP2pConfig();
                    config.deviceAddress = group.getOwner().deviceAddress;

                    if (isConfigInvalid(config)) {
                        loge("Dropping invitation request " + config);
                        break;
                    }
                    mSavedPeerConfig = config;

                    if ((owner = mPeers.get(owner.deviceAddress)) != null) {
                        if (owner.wpsPbcSupported()) {
                            mSavedPeerConfig.wps.setup = WpsInfo.PBC;
                        } else if (owner.wpsKeypadSupported()) {
                            mSavedPeerConfig.wps.setup = WpsInfo.KEYPAD;
                        } else if (owner.wpsDisplaySupported()) {
                            mSavedPeerConfig.wps.setup = WpsInfo.DISPLAY;
                        }
                    }

                    mAutonomousGroup = false;
                    mJoinExistingGroup = true;
                    transitionTo(mUserAuthorizingInviteRequestState);
                    break;

首先通过P2P_INVITATION_RECEIVED带的group owner的mac地址构造一个配置信息,并保存到mSavedPeerConfig中,然后根据group owner所有的WpsInfo会选择一个WSC方式,优选PBC方式,接着transition到UserAuthorizingInviteRequestState中:
    class UserAuthorizingInviteRequestState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            notifyInvitationReceived();
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            boolean ret = HANDLED;
            switch (message.what) {
                case PEER_CONNECTION_USER_ACCEPT:
                    mWifiNative.p2pStopFind();
                    if (!reinvokePersistentGroup(mSavedPeerConfig)) {
                        // Do negotiation when persistence fails
                        p2pConnectWithPinDisplay(mSavedPeerConfig);
                    }
                    mPeers.updateStatus(mSavedPeerConfig.deviceAddress, WifiP2pDevice.INVITED);
                    sendPeersChangedBroadcast();
                    transitionTo(mGroupNegotiationState);
                   break;

UserAuthorizingInviteRequestState和UserAuthorizingNegotiationRequsetState类似,首先弹出对话框给用户选择同意或者拒绝,若选择keypad或者display的方式,还需要显示pin码等。当用户点击同意后,就会给自身发送PEER_CONNECTION_USER_ACCEPT,看上面处理PEER_CONNECTION_USER_ACCEPT的代码,首先尝试用persistent的方式连接;如果失败,则调用p2pConnectWithPinDisplay,然后调用WifiNative的p2pConnect向wpa_supplicant发送P2P_CONNECT命令,这样就回到与之前主动连接一样的流程当中了。

你可能感兴趣的:(Android,p2p,android,wifi)