async internal void testconnectAsync()
        {
            string result         = "";
            string deviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
            DeviceInformationCollection devInfoCollection = await DeviceInformation.FindAllAsync(deviceSelector);

            String deviceId = devInfoCollection[0].Id;

            wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(deviceId);

            if (wfdDevice == null)
            {
                result = "Connection to " + deviceId + " failed.";
            }

            // Register for connection status change notification.
            wfdDevice.ConnectionStatusChanged += new TypedEventHandler <Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(OnConnectionChanged);

            // Get the EndpointPair information.
            var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs();

            if (EndpointPairCollection.Count > 0)
            {
                var endpointPair = EndpointPairCollection[0];
                result = "Local IP address " + endpointPair.LocalHostName.ToString() +
                         " connected to remote IP address " + endpointPair.RemoteHostName.ToString();
            }
            else
            {
                result = "Connection to " + deviceId + " failed.";
            }
        }
Ejemplo n.º 2
0
        public bool StartScan(string searchForDevice = null)
        {
            _searchingFor = searchForDevice;
            _publisher.Start();

            if (_publisher.Status != WiFiDirectAdvertisementPublisherStatus.Started)
            {
                LastErrorMessage = "Failed to start advertisement.";
                return(false);
            }

            _discoveredDevices.Clear();
            LastErrorMessage = "Finding Devices...";

            String deviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.DeviceInterface);

            _deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });

            _deviceWatcher.Added   += OnDeviceAdded;
            _deviceWatcher.Removed += OnDeviceRemoved;
            _deviceWatcher.Updated += OnDeviceUpdated;
            _deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
            _deviceWatcher.Stopped += OnStopped;

            _deviceWatcher.Start();
            _scanning = true;

            return(true);
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
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; });
            }
        }
 private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
 {
     WiFiDirectConnectionRequest ConnectionRequest = args.GetConnectionRequest();
     WiFiDirectDevice wfdDevice = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);
     EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
     _ConnectionEstablishState = ConnectionEstablishState.Succeeded;
     OnConnectionEstalblishResult?.Invoke(this, _ConnectionEstablishState);
 }
Ejemplo n.º 6
0
 private void Disconnect()
 {
     if (_wfdDevice != null)
     {
         var device = _wfdDevice;
         _wfdDevice = null;
         device.Dispose();
     }
 }
Ejemplo n.º 7
0
        private async Task <bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
        {
            string deviceName = connectionRequest.DeviceInformation.Name;

            bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) ||
                            (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id));

            //rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage);

            // Pair device if not already paired and not using legacy settings
            if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing))
                {
                    return(false);
                }
            }

            WiFiDirectDevice wfdDevice = null;

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);
            }
            catch (Exception ex)
            {
                //rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage);
                return(false);
            }

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

            StreamSocketListener listenerSocket = new StreamSocketListener();

            // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made.
            _pendingConnections[listenerSocket] = wfdDevice;

            IReadOnlyList <Windows.Networking.EndpointPair> EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
            try
            {
                await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);
            }
            catch (Exception ex)
            {
                //rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return(false);
            }

            //rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" +
            //$" Port: {Globals.strServerPort}", NotifyType.StatusMessage);
            return(true);
        }
        private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
        {
            rootPage.NotifyUserFromBackground($"Connection status changed: {sender.ConnectionStatus}", NotifyType.StatusMessage);

            if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
            {
                // TODO: Should we remove this connection from the list?
                // (Yes, probably.)
            }
        }
        private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
        {
            StatusBlock.Text = $"Connection status changed: {sender.ConnectionStatus}";

            if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
            {
                // TODO: Should we remove this connection from the list?
                // (Yes, probably.)
            }
        }
Ejemplo n.º 10
0
        public static async void GetDevices()
        {
            string deviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(deviceSelector);

            foreach (DeviceInformation device in devices)
            {
                Send.Devices.Add(new Device(device.Name, device.Id));
            }
            MessagingCenter.Send("P2PShare", "WFDSearchIsEnabled", true);
        }
        void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
        {
            JSONObject eventData = createEventData(EVENT_CONNECTION_CHANGED);

            ((JSONObject)eventData[TAG_DATA])[TAG_CONNECTED] = (sender.ConnectionStatus == WiFiDirectConnectionStatus.Connected) ? TAG_TRUE : TAG_FALSE;
            if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
            {
                mConnected.Remove(extractMAC(sender.DeviceId));
            }
            native_.PostMessageToJS(new JavaScriptSerializer().Serialize(createEventData(EVENT_PEERS_CHANGED)));
            native_.PostMessageToJS(new JavaScriptSerializer().Serialize(eventData));
        }
        private void btnWatcher_Click(object sender, RoutedEventArgs e)
        {
            if (_fWatcherStarted == false)
            {
                _publisher.Start();

                if (_publisher.Status != WiFiDirectAdvertisementPublisherStatus.Started)
                {
                    rootPage.NotifyUser("Failed to start advertisement.", NotifyType.ErrorMessage);
                    return;
                }

                DiscoveredDevices.Clear();
                rootPage.NotifyUser("Finding Devices...", NotifyType.StatusMessage);

                String deviceSelector = WiFiDirectDevice.GetDeviceSelector(
                    Utils.GetSelectedItemTag <WiFiDirectDeviceSelectorType>(cmbDeviceSelector));

                _deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });

                _deviceWatcher.Added   += OnDeviceAdded;
                _deviceWatcher.Removed += OnDeviceRemoved;
                _deviceWatcher.Updated += OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
                _deviceWatcher.Stopped += OnStopped;

                _deviceWatcher.Start();

                btnWatcher.Content = "Stop Watcher";
                _fWatcherStarted   = true;
            }
            else
            {
                _publisher.Stop();

                btnWatcher.Content = "Start Watcher";
                _fWatcherStarted   = false;

                _deviceWatcher.Added   -= OnDeviceAdded;
                _deviceWatcher.Removed -= OnDeviceRemoved;
                _deviceWatcher.Updated -= OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
                _deviceWatcher.Stopped -= OnStopped;

                _deviceWatcher.Stop();

                rootPage.NotifyUser("Device watcher stopped.", NotifyType.StatusMessage);
            }
        }
Ejemplo n.º 13
0
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
        {
            WiFiDirectConnectionRequest ConnectionRequest = args.GetConnectionRequest();

            // Prompt the user to accept/reject the connection request
            // If rejected, exit

            // Connect to the remote device
            WiFiDirectDevice wfdDevice = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);

            // Get the local and remote IP addresses
            IReadOnlyList <Windows.Networking.EndpointPair> EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            // Establish standard WinRT socket with above IP addresses
        }
Ejemplo n.º 14
0
        private async void GetData(WiFiDirectConnectionRequest connectionRequest)
        {
            try
            {
                var wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);

                var    endPoint = wfdDevice.GetConnectionEndpointPairs();
                string result   = string.Empty;
                foreach (var item in endPoint)
                {
                    result = item.LocalHostName + "\r\n";
                }
            }
            catch (Exception ex)
            {
            }
        }
        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";
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 广播者接收到请求连接消息后的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
        {
            try
            {
                WiFiDirectConnectionRequest ConnectionRequest = args.GetConnectionRequest();
                WiFiDirectDevice            wfdDevice         = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);

                //与之连接过的列表
                EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
                //StartUDPServer("50001");
                //EstablishSocketFromAdvertiser(EndpointPairs[0].LocalHostName, "50001");
                //Invoke(() => { TextBlock_ConnectedState.Text = "连接到" + EndpointPairs[0].LocalHostName.ToString(); });
            }
            catch (Exception exp)
            {
                Invoke(() => { TextBlock_ConnectedState.Text = exp.Message; });
            }
        }
        void discoverPeers(Dictionary <String, Object> jsonOutput)
        {
            try {
                advertise();
                mDiscovered.Clear();
                mDeviceWatcher = DeviceInformation.CreateWatcher(
                    WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint),
                    new string[] { "System.Devices.WiFiDirect.InformationElements" });

                mDeviceWatcher.Added   += OnDeviceAdded;
                mDeviceWatcher.Removed += OnDeviceRemoved;
                mDeviceWatcher.Updated += OnDeviceUpdated;
                mDeviceWatcher.Stopped += OnStopped;

                mDeviceWatcher.Start();
                jsonOutput[TAG_DATA] = TAG_TRUE;
            } catch (Exception ex) {
                setError(jsonOutput, ex.ToString(), ex.HResult);
            }
            native_.PostMessageToJS(new JavaScriptSerializer().Serialize(jsonOutput));
        }
        void connect(JSONObject response)
        {
            WiFiDirectDevice wfdDevice = null;

            try {
                JSONObject device = (JSONObject)response[TAG_DATA];
                if (device == null)
                {
                    setError(response, ERROR_INVALID_CALL_NO_DATA_MSG, 0);
                    native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
                    return;
                }

                DeviceInformation deviceInfo = findDiscoveredById((string)device[TAG_MAC]);
                if (deviceInfo == null)
                {
                    setError(response, ERROR_INVALID_CALL_DEVICE_NOT_AVAILABLE + device[TAG_MAC], 0);
                    native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
                    return;
                }

                wfdDevice = WiFiDirectDevice.FromIdAsync(deviceInfo.Id).AsTask().Result;
                wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                var endpointPairs = wfdDevice.GetConnectionEndpointPairs();
                mConnected[extractMAC(wfdDevice.DeviceId)] = wfdDevice;

                response[TAG_DATA]      = TAG_TRUE;
                response[TAG_SERVER_IP] = endpointPairs[0].RemoteHostName;
                mGroupOwner             = false;
            } catch (Exception ex) {
                setError(response, ex.ToString(), ex.HResult);
                wfdDevice = null;
            }
            native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
            if (wfdDevice != null)
            {
                OnConnectionStatusChanged(wfdDevice, null);
            }
        }
        private void btnWatcher_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (_fWatcherStarted == false)
            {
                btnWatcher.Content = "Stop Watcher";
                _fWatcherStarted   = true;

                _discoveredDevices.Clear();
                rootPage.NotifyUser("Finding Devices...", NotifyType.StatusMessage);

                _deviceWatcher = null;
                String deviceSelector = WiFiDirectDevice.GetDeviceSelector((cmbDeviceSelector.ToString().Equals("Device Interface") == true) ?
                                                                           WiFiDirectDeviceSelectorType.DeviceInterface : WiFiDirectDeviceSelectorType.AssociationEndpoint);

                _deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });

                _deviceWatcher.Added   += OnDeviceAdded;
                _deviceWatcher.Removed += OnDeviceRemoved;
                _deviceWatcher.Updated += OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
                _deviceWatcher.Stopped += OnStopped;

                _deviceWatcher.Start();
            }
            else
            {
                btnWatcher.Content = "Start Watcher";
                _fWatcherStarted   = false;

                _deviceWatcher.Added   -= OnDeviceAdded;
                _deviceWatcher.Removed -= OnDeviceRemoved;
                _deviceWatcher.Updated -= OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
                _deviceWatcher.Stopped -= OnStopped;

                _deviceWatcher.Stop();
            }
        }
        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);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 连接者开始搜索发出广播的设备
        /// </summary>
        public async void StartConnecting()
        {
            string deviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);

            //获取所有检测到的Wi-Fi直连设备
            DeviceInformationCollection devInfoCollection = await DeviceInformation.FindAllAsync(deviceSelector);

            Invoke(() =>
            {
                if (devInfoCollection.Count == 0)
                {
                    TextBlock_ConnectedState.Text = "找不到设备";
                }
                else
                {
                    TextBlock_ConnectedState.Text = "";
                    foreach (var devInfo in devInfoCollection)
                    {
                        TextBlock_ConnectedState.Text += devInfo.Id + '\n';
                    }
                    TextBox_SelectedIP.Text = devInfoCollection[0].Id;
                }
            });
        }
Ejemplo n.º 22
0
        private void OnConnectionStatusChanged(WiFiDirectDevice wfdDeviceSender, object obj)
        {
            try
            {
                switch (wfdDeviceSender.ConnectionStatus)
                {
                case WiFiDirectConnectionStatus.Disconnected:
                {
                    string deviceId = wfdDeviceSender.DeviceId;
                    if (_connectedDevices.ContainsKey(deviceId))
                    {
                        _connectedDevices[deviceId].ConnectionStatusChanged -= OnConnectionStatusChanged;
                        _connectedDevices.Remove(deviceId);
                    }
                    // Notify listener of disconnect
                    if (_listener != null)
                    {
                        _listener.OnDeviceDisconnected(deviceId);
                    }
                    break;
                }

                case WiFiDirectConnectionStatus.Connected:
                    //ignored
                    break;
                }
            }
            catch (Exception ex)
            {
                if (_listener != null)
                {
                    _listener.OnAsyncException(ex.ToString());
                }
                return;
            }
        }
Ejemplo n.º 23
0
        private async void OnConnectionRequested(WiFiDirectConnectionListener listener, WiFiDirectConnectionRequestedEventArgs eventArgs)
        {
            if (_listener != null)
            {
                _listener.LogMessage("Connection Requested...");
            }
            bool acceptConnection = true;

            if (!AutoAccept && _prompt != null)
            {
                acceptConnection = _prompt.AcceptIncommingConnection();
            }

            try
            {
                WiFiDirectConnectionRequest request = eventArgs.GetConnectionRequest();
                if (acceptConnection)
                {
                    DeviceInformation deviceInformation = request.DeviceInformation;
                    string            deviceId          = deviceInformation.Id;

                    // Must call FromIdAsync first
                    var tcsWiFiDirectDevice = new TaskCompletionSource <WiFiDirectDevice>();
                    var wfdDeviceTask       = tcsWiFiDirectDevice.Task;
                    tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(deviceId));
                    // Get the WiFiDirectDevice object
                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Now retrieve the endpoint pairs, which includes the IP address assigned to the peer
                    var    endpointPairs  = wfdDevice.GetConnectionEndpointPairs();
                    string remoteHostName = "";
                    if (endpointPairs.Any())
                    {
                        EndpointPair endpoint = endpointPairs[0];
                        remoteHostName = endpoint.RemoteHostName.DisplayName;
                    }
                    else
                    {
                        throw new Exception("Can't retrieve endpoint pairs");
                    }

                    // Add handler for connection status changed
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    // Store the connected peer
                    lock (_threadObject)
                    {
                        _connectedDevices.Add(wfdDevice.DeviceId, wfdDevice);
                    }

                    // Notify Listener
                    if (_listener != null)
                    {
                        _listener.OnDeviceConnected(remoteHostName);
                    }
                }
                else
                {
                    if (_listener != null)
                    {
                        _listener.LogMessage("Declined");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_listener != null)
                {
                    _listener.OnAsyncException(ex.ToString());
                }
                return;
            }
        }
        private async void SetupWifiDirect()
        {
            ListenForIncomingConnections();
            if (_fWatcherStarted == false)
            {
                _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
                //make this device known
                _publisher.Start();

                if (_publisher.Status != WiFiDirectAdvertisementPublisherStatus.Started)
                {
                    NotifyUser("Failed to start advertisement.", NotifyType.ErrorMessage);
                    return;
                }

                //detect other devices
                DiscoveredDevices.Clear();
                NotifyUser("Finding Devices...", NotifyType.StatusMessage);

                String deviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);//WiFiDirectDevice.GetDeviceSelector(
                //Utils.GetSelectedItemTag<WiFiDirectDeviceSelectorType>(cmbDeviceSelector));

                _deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });

                _deviceWatcher.Added   += OnDeviceAdded;
                _deviceWatcher.Removed += OnDeviceRemoved;
                _deviceWatcher.Updated += OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
                _deviceWatcher.Stopped += OnStopped;

                _deviceWatcher.Start();

                //btnWatcher.Content = "Stop Watcher";
                _fWatcherStarted = true;
            }
            else
            {
                _publisher.Stop();

                //btnWatcher.Content = "Start Watcher";
                _fWatcherStarted = false;

                _deviceWatcher.Added   -= OnDeviceAdded;
                _deviceWatcher.Removed -= OnDeviceRemoved;
                _deviceWatcher.Updated -= OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
                _deviceWatcher.Stopped -= OnStopped;

                _deviceWatcher.Stop();

                NotifyUser("Device watcher stopped.", NotifyType.StatusMessage);
            }


            string ServiceSelector = WiFiDirectService.GetSelector("WalkieTalkie");

            // Get all WiFiDirect services that are advertising and in range
            //DeviceInformationCollection devInfoCollection = await DeviceInformation.FindAllAsync(ServiceSelector);

            //// Get a Service Seeker object
            //WiFiDirectService Service = await WiFiDirectService.FromIdAsync(devInfoCollection[0].Id);

            //// Connect to the Advertiser
            //WiFiDirectServiceSession Session = await Service.ConnectAsync();

            //// Get the local and remote IP addresses
            //var EndpointPairs = Session.GetConnectionEndpointPairs();
        }
 public WiFiDirectDeviceEvents(WiFiDirectDevice This)
 {
     this.This = This;
 }
Ejemplo n.º 26
0
 static private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
 {
     //rootPage.NotifyUserFromBackground("Connection status changed: " + sender.ConnectionStatus, NotifyType.StatusMessage);
 }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     this.socketRW = socketRW;
     this.wfdDevice = wfdDevice;
     this.displayName = displayName;
 }
        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);
            }
        }
Ejemplo n.º 29
0
        private async void btnFromId_Click(object sender, RoutedEventArgs e)
        {
            var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem;

            if (discoveredDevice == null)
            {
                rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
                return;
            }

            rootPage.NotifyUser($"Connecting to {discoveredDevice.DeviceInfo.Name}...", NotifyType.StatusMessage);

            if (!discoveredDevice.DeviceInfo.Pairing.IsPaired)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(discoveredDevice.DeviceInfo.Pairing))
                {
                    return;
                }
            }

            WiFiDirectDevice wfdDevice = null;

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id);
            }
            catch (TaskCanceledException)
            {
                rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
                return;
            }

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

            IReadOnlyList <EndpointPair> endpointPairs = wfdDevice.GetConnectionEndpointPairs();
            HostName remoteHostName = endpointPairs[0].RemoteHostName;

            rootPage.NotifyUser($"Devices connected on L2 layer, connecting to IP Address: {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();

            try
            {
                await clientSocket.ConnectAsync(remoteHostName, Globals.strServerPort);

                rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return;
            }

            SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

            string          sessionId       = Path.GetRandomFileName();
            ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);

            ConnectedDevices.Add(connectedDevice);

            // The first message sent over the socket is the name of the connection.
            await socketRW.WriteMessageAsync(sessionId);

            while (await socketRW.ReadMessageAsync() != null)
            {
                // Keep reading messages
            }
        }
        private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
        {
            rootPage.NotifyUserFromBackground($"Connection status changed: {sender.ConnectionStatus}", NotifyType.StatusMessage);

            if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
            {
                // TODO: Should we remove this connection from the list?
                // (Yes, probably.)
            }
        }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     DisplayName = displayName;
     WfdDevice = wfdDevice;
     SocketRW = socketRW;
 }
 private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
 {
     rootPage.NotifyUserFromBackground("Connection status changed: " + sender.ConnectionStatus, NotifyType.StatusMessage);
 }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     this.socketRW    = socketRW;
     this.wfdDevice   = wfdDevice;
     this.displayName = displayName;
 }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     DisplayName = displayName;
     WfdDevice   = wfdDevice;
     SocketRW    = socketRW;
 }
        private async Task <bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
        {
            string deviceName = connectionRequest.DeviceInformation.Name;

            bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) ||
                            (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id));

            // Show the prompt only in case of WiFiDirect reconnection or Legacy client connection.
            if (isPaired || _publisher.Advertisement.LegacySettings.IsEnabled)
            {
                var messageDialog = new MessageDialog($"Connection request received from {deviceName}", "Connection Request");

                // Add two commands, distinguished by their tag.
                // The default command is "Decline", and if the user cancels, we treat it as "Decline".
                messageDialog.Commands.Add(new UICommand("Accept", null, true));
                messageDialog.Commands.Add(new UICommand("Decline", null, null));
                messageDialog.DefaultCommandIndex = 1;
                messageDialog.CancelCommandIndex  = 1;

                // Show the message dialog
                var commandChosen = await messageDialog.ShowAsync();

                if (commandChosen.Id == null)
                {
                    return(false);
                }
            }

            rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage);

            // Pair device if not already paired and not using legacy settings
            if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing))
                {
                    return(false);
                }
            }

            WiFiDirectDevice wfdDevice = null;

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage);
                return(false);
            }

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

            var listenerSocket = new StreamSocketListener();

            // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made.
            _pendingConnections[listenerSocket] = wfdDevice;

            var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            listenerSocket.ConnectionReceived += this.OnSocketConnectionReceived;
            try
            {
                await listenerSocket.BindServiceNameAsync(Globals.strServerPort);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return(false);
            }

            rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" +
                                $" Port: {Globals.strServerPort}", NotifyType.StatusMessage);


            return(true);
        }