Exemple #1
0
        /// <summary>
        /// 建立连接
        /// </summary>
        public async void Connecting()
        {
            //连接参数
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            connectionParams.GroupOwnerIntent = 1;

            WiFiDirectDevice wfdDevice;
            string           deviceId = TextBox_SelectedIP.Text;

            try
            {
                wfdDevice = await WiFiDirectDevice.FromIdAsync(deviceId, connectionParams);

                Invoke(() =>
                {
                    TextBlock_ConnectedState.Text = "连接到设备" + deviceId;
                });
                EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
                EstablishSocketFromConnector(EndpointPairs[0].RemoteHostName, "50001");
            }
            catch (Exception exp)
            {
                Invoke(() => { TextBlock_ConnectedState.Text = exp.Message; });
            }
        }
Exemple #2
0
        public static async System.Threading.Tasks.Task ConnectAsync(string deviceId, bool IsReceiver)
        {
            try
            {
                WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                WiFiDirectDevice wfdDevice = null;
                connectionParams.GroupOwnerIntent          = (short)(IsReceiver ? 15 : 0);
                connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
                connectionParams.PreferenceOrderedConfigurationMethods.Clear();
                connectionParams.PreferenceOrderedConfigurationMethods.Add(WiFiDirectConfigurationMethod.PushButton);
                wfdDevice = await WiFiDirectDevice.FromIdAsync(deviceId, connectionParams);

                // Register for the ConnectionStatusChanged event handler
                wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
                var endpointPairs = wfdDevice.GetConnectionEndpointPairs();
                MessagingCenter.Send("P2PShare", "WFDConnectError", "Connected IP Address: " + endpointPairs[0].RemoteHostName);
                MessagingCenter.Send("P2PShare", "WFDConnected", endpointPairs[0].RemoteHostName.ToString());
            }
            catch (Exception)
            {
                /*MessagingCenter.Send("P2PShare", "WFDConnectError", "Connection to " + deviceId + " failed " + err.Message);
                 * DependencyService.Get<IPlatformDependent>().Dispose();
                 * DependencyService.Get<IPlatformDependent>().Init(true);
                 * System.Threading.Thread.Sleep(1000);
                 *
                 * if (--ConnectionAttempt > 0)
                 *  await ConnectAsync(deviceId, IsReceiver);
                 * else
                 * {
                 *  ConnectionAttempt = 50;
                 * }*/
            }
            MessagingCenter.Send("P2PShare", "WFDConnectIsEnabled", true);
        }
        private async void PairWithSelectedDevice(DeviceInformation selectedDevice)
        {
            //set the group owner intent to indicate that we want the receiver to be the owner
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            connectionParams.GroupOwnerIntent = 1;

            //connect to the selected device
            try
            {
                var wfdDevice = await WiFiDirectDevice.FromIdAsync(selectedDevice.Id, connectionParams);
            }
            catch (Exception e)
            {
                StatusBlock.Text = "Unable to connect";
            }
        }
        public async Task <bool> RequestPairDeviceAsync(DeviceInformationPairing pairing)
        {
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            short?groupOwnerIntent = Utils.GetSelectedItemTag <short?>(cmbGOIntent);

            if (groupOwnerIntent.HasValue)
            {
                connectionParams.GroupOwnerIntent = groupOwnerIntent.Value;
            }

            DevicePairingKinds devicePairingKinds = DevicePairingKinds.None;

            if (_supportedConfigMethods.Count > 0)
            {
                // If specific configuration methods were added, then use them.
                foreach (var configMethod in _supportedConfigMethods)
                {
                    connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod);
                    devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod);
                }
            }
            else
            {
                // If specific configuration methods were not added, then we'll use these pairing kinds.
                devicePairingKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin;
            }

            connectionParams.PreferredPairingProcedure = Utils.GetSelectedItemTag <WiFiDirectPairingProcedure>(cmbPreferredPairingProcedure);
            DeviceInformationCustomPairing customPairing = pairing.Custom;

            customPairing.PairingRequested += OnPairingRequested;

            DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams);

            if (result.Status != DevicePairingResultStatus.Paired)
            {
                //rootPage.NotifyUser($"PairAsync failed, Status: {result.Status}", NotifyType.ErrorMessage);
                return(false);
            }
            return(true);
        }
        public async Task <bool> RequestPairDeviceAsync(DeviceInformationPairing pairing)
        {
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            short?groupOwnerIntent = 1;

            if (groupOwnerIntent.HasValue)
            {
                connectionParams.GroupOwnerIntent = groupOwnerIntent.Value;
            }

            DevicePairingKinds devicePairingKinds = DevicePairingKinds.None;

            //if (_supportedConfigMethods.Count > 0)
            //{
            //    // If specific configuration methods were added, then use them.
            //    foreach (var configMethod in _supportedConfigMethods)
            //    {
            //        connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod);
            //        devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod);
            //    }
            //}
            //else
            {
                // If specific configuration methods were not added, then we'll use these pairing kinds.
                devicePairingKinds = DevicePairingKinds.ConfirmOnly;// | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin;
            }

            connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
            DeviceInformationCustomPairing customPairing = pairing.Custom;

            customPairing.PairingRequested += OnPairingRequested;

            DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams);

            if (result.Status != DevicePairingResultStatus.Paired)
            {
                StatusBlock.Text = $"PairAsync failed, Status: {result.Status}";
                return(false);
            }
            return(true);
        }
        public async Task<bool> RequestPairDeviceAsync(DeviceInformationPairing pairing)
        {
            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();

            short? groupOwnerIntent = Utils.GetSelectedItemTag<short?>(cmbGOIntent);
            if (groupOwnerIntent.HasValue)
            {
                connectionParams.GroupOwnerIntent = groupOwnerIntent.Value;
            }

            DevicePairingKinds devicePairingKinds = DevicePairingKinds.None;
            if (_supportedConfigMethods.Count > 0)
            {
                // If specific configuration methods were added, then use them.
                foreach (var configMethod in _supportedConfigMethods)
                {
                    connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod);
                    devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod);
                }
            }
            else
            {
                // If specific configuration methods were not added, then we'll use these pairing kinds.
                devicePairingKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin;
            }

            connectionParams.PreferredPairingProcedure = Utils.GetSelectedItemTag<WiFiDirectPairingProcedure>(cmbPreferredPairingProcedure);
            DeviceInformationCustomPairing customPairing = pairing.Custom;
            customPairing.PairingRequested += OnPairingRequested;

            DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams);
            if (result.Status != DevicePairingResultStatus.Paired)
            {
                rootPage.NotifyUser($"PairAsync failed, Status: {result.Status}", NotifyType.ErrorMessage);
                return false;
            }
            return true;
        }
        void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            WiFiDirectDevice wfdDevice;

            try {
                var connectionRequest = connectionEventArgs.GetConnectionRequest();
                WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                connectionParams.GroupOwnerIntent = 15;
                wfdDevice = WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams).AsTask().Result;

                // Register for the ConnectionStatusChanged event handler
                wfdDevice.ConnectionStatusChanged         += OnConnectionStatusChanged;
                mConnected[extractMAC(wfdDevice.DeviceId)] = wfdDevice;
                mGroupOwner = true;
            } catch (Exception ex) {
                Debug.WriteLine("Connect operation threw an exception: " + ex.Message);
                wfdDevice = null;
            }
            if (wfdDevice != null)
            {
                OnConnectionStatusChanged(wfdDevice, null);
            }
        }
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            try
            {
                var connectionRequest = connectionEventArgs.GetConnectionRequest();

                var tcs = new TaskCompletionSource<bool>();
                var dialogTask = tcs.Task;
                var messageDialog = new MessageDialog("Connection request received from " + connectionRequest.DeviceInformation.Name, "Connection Request");

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers 
                messageDialog.Commands.Add(new UICommand("Accept", null, 0));
                messageDialog.Commands.Add(new UICommand("Decline", null, 1));

                // Set the command that will be invoked by default 
                messageDialog.DefaultCommandIndex = 1;

                // Set the command to be invoked when escape is pressed 
                messageDialog.CancelCommandIndex = 1;

                await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                {
                    // Show the message dialog 
                    var commandChosen = await messageDialog.ShowAsync();

                    tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
                });

                var fProceed = await dialogTask;

                if (fProceed == true)
                {
                    var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
                    var wfdDeviceTask = tcsWiFiDirectDevice.Task;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                    {
                        try
                        {
                            rootPage.NotifyUser("Connecting to " + connectionRequest.DeviceInformation.Name + "...", NotifyType.StatusMessage);

                            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                            connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);

                            // IMPORTANT: FromIdAsync needs to be called from the UI thread
                            tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams));
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser("FromIdAsync task threw an exception: " + ex.ToString(), NotifyType.ErrorMessage);
                        }
                    });

                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Register for the ConnectionStatusChanged event handler
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        ConnectedDevice connectedDevice = new ConnectedDevice("Waiting for client to connect...", wfdDevice, null);
                        _connectedDevices.Add(connectedDevice);
                    });

                    var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    _listenerSocket = null;
                    _listenerSocket = new StreamSocketListener();
                    _listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
                    await _listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);

                    rootPage.NotifyUserFromBackground("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() +
                                            " Port: " + Globals.strServerPort, NotifyType.StatusMessage);
                }
                else
                {
                    // Decline the connection request
                    rootPage.NotifyUserFromBackground("Connection request from " + connectionRequest.DeviceInformation.Name + " was declined", NotifyType.ErrorMessage);
                    connectionRequest.Dispose();
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUserFromBackground("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
        private async void btnFromId_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (lvDiscoveredDevices.SelectedItems.Count == 0)
            {
                rootPage.NotifyUser("No device selected, please select atleast one.", NotifyType.ErrorMessage);
                return;
            }

            var selectedDevices = lvDiscoveredDevices.SelectedItems;

            foreach (DiscoveredDevice discoveredDevice in selectedDevices)
            {
                rootPage.NotifyUser("Connecting to " + discoveredDevice.DeviceInfo.Name + "...", NotifyType.StatusMessage);

                try
                {
                    WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                    connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);

                    _cancellationTokenSource = new CancellationTokenSource();

                    // IMPORTANT: FromIdAsync needs to be called from the UI thread
                    var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id, connectionParams).AsTask(_cancellationTokenSource.Token);

                    // Register for the ConnectionStatusChanged event handler
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    var endpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    rootPage.NotifyUser("Devices connected on L2 layer, connecting to IP Address: " + endpointPairs[0].RemoteHostName +
                                        " Port: " + Globals.strServerPort, NotifyType.StatusMessage);

                    // Wait for server to start listening on a socket
                    await Task.Delay(2000);

                    // Connect to Advertiser on L4 layer
                    StreamSocket clientSocket = new StreamSocket();
                    await clientSocket.ConnectAsync(endpointPairs[0].RemoteHostName, Globals.strServerPort);

                    SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

                    string sessionId = "Session: " + Path.GetRandomFileName();
                    ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
                    _connectedDevices.Add(connectedDevice);

                    socketRW.ReadMessage();
                    socketRW.WriteMessage(sessionId);

                    rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
                }
                catch (TaskCanceledException)
                {
                    rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
                }

                _cancellationTokenSource = null;
            }
        }
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            try
            {
                var connectionRequest = connectionEventArgs.GetConnectionRequest();

                var tcs           = new TaskCompletionSource <bool>();
                var dialogTask    = tcs.Task;
                var messageDialog = new MessageDialog("Connection request received from " + connectionRequest.DeviceInformation.Name, "Connection Request");

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
                messageDialog.Commands.Add(new UICommand("Accept", null, 0));
                messageDialog.Commands.Add(new UICommand("Decline", null, 1));

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 1;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
                {
                    // Show the message dialog
                    var commandChosen = await messageDialog.ShowAsync();

                    tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
                });

                var fProceed = await dialogTask;

                if (fProceed == true)
                {
                    var tcsWiFiDirectDevice = new TaskCompletionSource <WiFiDirectDevice>();
                    var wfdDeviceTask       = tcsWiFiDirectDevice.Task;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
                    {
                        try
                        {
                            rootPage.NotifyUser("Connecting to " + connectionRequest.DeviceInformation.Name + "...", NotifyType.StatusMessage);

                            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                            connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);

                            // IMPORTANT: FromIdAsync needs to be called from the UI thread
                            tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams));
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser("FromIdAsync task threw an exception: " + ex.ToString(), NotifyType.ErrorMessage);
                        }
                    });

                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Register for the ConnectionStatusChanged event handler
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        ConnectedDevice connectedDevice = new ConnectedDevice("Waiting for client to connect...", wfdDevice, null);
                        _connectedDevices.Add(connectedDevice);
                    });

                    var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    _listenerSocket = null;
                    _listenerSocket = new StreamSocketListener();
                    _listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
                    await _listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);

                    rootPage.NotifyUserFromBackground("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() +
                                                      " Port: " + Globals.strServerPort, NotifyType.StatusMessage);
                }
                else
                {
                    // Decline the connection request
                    rootPage.NotifyUserFromBackground("Connection request from " + connectionRequest.DeviceInformation.Name + " was declined", NotifyType.ErrorMessage);
                    connectionRequest.Dispose();
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUserFromBackground("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
        private async void btnFromId_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (lvDiscoveredDevices.SelectedItems.Count == 0)
            {
                rootPage.NotifyUser("No device selected, please select atleast one.", NotifyType.ErrorMessage);
                return;
            }

            var selectedDevices = lvDiscoveredDevices.SelectedItems;

            foreach (DiscoveredDevice discoveredDevice in selectedDevices)
            {
                rootPage.NotifyUser("Connecting to " + discoveredDevice.DeviceInfo.Name + "...", NotifyType.StatusMessage);

                try
                {
                    WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                    connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);

                    _cancellationTokenSource = new CancellationTokenSource();

                    // IMPORTANT: FromIdAsync needs to be called from the UI thread
                    var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id, connectionParams).AsTask(_cancellationTokenSource.Token);

                    // Register for the ConnectionStatusChanged event handler
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    var endpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    rootPage.NotifyUser("Devices connected on L2 layer, connecting to IP Address: " + endpointPairs[0].RemoteHostName +
                                        " Port: " + Globals.strServerPort, NotifyType.StatusMessage);

                    // Wait for server to start listening on a socket
                    await Task.Delay(2000);

                    // Connect to Advertiser on L4 layer
                    StreamSocket clientSocket = new StreamSocket();
                    await clientSocket.ConnectAsync(endpointPairs[0].RemoteHostName, Globals.strServerPort);

                    SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

                    string          sessionId       = "Session: " + Path.GetRandomFileName();
                    ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
                    _connectedDevices.Add(connectedDevice);

                    socketRW.ReadMessage();
                    socketRW.WriteMessage(sessionId);

                    rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
                }
                catch (TaskCanceledException)
                {
                    rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
                }

                _cancellationTokenSource = null;
            }
        }