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 async Task <AsyncHandleListResult> DiscoverServicesAsync(string serviceName, bool fExpectResults = true, string serviceInfo = "")
        {
            List <WFDSvcWrapperHandle> results = new List <WFDSvcWrapperHandle>();
            Exception error   = null;
            bool      success = false;

            try
            {
                ThrowIfDisposed();

                WiFiDirectTestLogger.Log("Discover Services... (ServiceName={0}, ServiceInfo={1})", serviceName, serviceInfo);

                string serviceSelector = "";
                if (serviceInfo == "")
                {
                    serviceSelector = WiFiDirectService.GetSelector(serviceName);
                }
                else
                {
                    using (var serviceInfoDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                    {
                        serviceInfoDataWriter.WriteString(serviceInfo);
                        serviceSelector = WiFiDirectService.GetSelector(serviceName, serviceInfoDataWriter.DetachBuffer());
                    }
                }

                WiFiDirectTestLogger.Log("FindAllAsync... Using Selector: {0}", serviceSelector);

                List <string> additionalProperties = new List <string>();
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceAddress");
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceName");
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceInformation");
                additionalProperties.Add("System.Devices.WiFiDirectServices.AdvertisementId");
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceConfigMethods");

                DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(serviceSelector, additionalProperties);

                WiFiDirectTestLogger.Log(
                    "FindAllAsync...DONE Got {0} results",
                    (deviceInfoCollection == null) ? 0 : deviceInfoCollection.Count
                    );

                if (deviceInfoCollection == null || deviceInfoCollection.Count == 0)
                {
                    if (fExpectResults)
                    {
                        WiFiDirectTestLogger.Error("No services found!");
                        throw new Exception("Expected services discovered, found none!");
                    }
                    else
                    {
                        WiFiDirectTestLogger.Log("No services found (expected)");
                    }
                }
                else
                {
                    if (!fExpectResults)
                    {
                        WiFiDirectTestLogger.Error("Services found, none expected!");
                        throw new Exception("Expected no services discovered, found at least 1!");
                    }
                    else
                    {
                        // NOTE: we don't clear this list
                        // Possible to discover A, discover B, then connect to A because its entry still exists
                        foreach (DeviceInformation deviceInfo in deviceInfoCollection)
                        {
                            WiFiDirectTestLogger.Log(
                                "Adding discovered service (Id={0}, Name={1})",
                                deviceInfo.Id,
                                deviceInfo.Name
                                );

                            DiscoveredService discovered = new DiscoveredService(deviceInfo, this, this, this);
                            discoveryCollection.Add(discovered.Handle, discovered);

                            results.Add(discovered.Handle);
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                WiFiDirectTestLogger.Error("Exception in DiscoverServicesAsync");
                error = ex;
            }

            return(new AsyncHandleListResult(results, success, error));
        }
            private void OnSessionDeferred(WiFiDirectService sender, WiFiDirectServiceSessionDeferredEventArgs args)
            {
                string deferredSessionInfo = "";
                if (args.DeferredSessionInfo != null && args.DeferredSessionInfo.Length > 0)
                {
                    using (DataReader sessionInfoDataReader = DataReader.FromBuffer(args.DeferredSessionInfo))
                    {
                        deferredSessionInfo = sessionInfoDataReader.ReadString(args.DeferredSessionInfo.Length);
                    }
                }

                manager.NotifyUser("Session Connection was deferred... (" + deferredSessionInfo + ")", NotifyType.StatusMessage);
            }
            /// <summary>
            /// Calls service.ConnectAsync() to connect the session
            /// If the session is not already opened, it calls OpenSessionAsync
            /// </summary>
            /// <param name="pin">Optional PIN if needed</param>
            public async void ConnectAsync(string pin = "")
            {
                ThrowIfDisposed();

                // Must call FromIdAsync first
                if (service == null)
                {
                    await OpenSessionAsync();
                }

                WiFiDirectServiceSession session = null;

                manager.NotifyUser("Connecting...", NotifyType.StatusMessage);

                try
                {
                    if (pin.Length > 0)
                    {
                        session = await service.ConnectAsync(pin);
                    }
                    else
                    {
                        session = await service.ConnectAsync();
                    }
                    
                    manager.NotifyUser("Done Connecting", NotifyType.StatusMessage);

                    // Now we are done with this WiFiDirectService instance
                    // Clear state so a new connection can be started
                    service.SessionDeferred -= OnSessionDeferred;
                    service = null;

                    SessionWrapper sessionWrapper = new SessionWrapper(session, manager);
                    manager.AddSession(sessionWrapper);
                }
                catch (Exception ex)
                {
                    // This could fail due to driver or network issues
                    manager.NotifyUser("ConnectAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            /// <summary>
            /// Calls WiFiDirectService.FromId to open the seeker session
            /// Caller can then use this.Service to modify settings before connecting
            /// </summary>
            public async Task OpenSessionAsync()
            {
                ThrowIfDisposed();

                // This wrapper can only be used for FromIdAsync once
                if (service != null)
                {
                    throw new Exception("Attempted to connect to discovered service a second time!");
                }

                manager.NotifyUser("Open session...", NotifyType.StatusMessage);

                try
                {
                    // NOTE: This MUST be called from the UI thread
                    service = await WiFiDirectService.FromIdAsync(deviceInfo.Id);
                    service.SessionDeferred += OnSessionDeferred;
                }
                catch (Exception ex)
                {
                    manager.NotifyUser("FromIdAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
 public WiFiDirectServiceEvents(WiFiDirectService This)
 {
     this.This = This;
 }
Esempio n. 7
0
            public async void DiscoverServicesAsync(string serviceName, string requestedServiceInfo)
            {
                try
                {
                    ThrowIfDisposed();

                    RootPage.NotifyUser("Discover services... (name='" + serviceName + "', requestedInfo='" + requestedServiceInfo + "')", NotifyType.StatusMessage);

                    // Clear old results
                    discoveredDevices.Clear();

                    // Discovery depends on whether service information is requested
                    string serviceSelector = "";
                    if (requestedServiceInfo == "")
                    {
                        // Just search by name
                        serviceSelector = WiFiDirectService.GetSelector(serviceName);
                    }
                    else
                    {
                        using (var serviceInfoDataWriter = new DataWriter(new InMemoryRandomAccessStream()))
                        {
                            serviceInfoDataWriter.WriteString(requestedServiceInfo);
                            // Discover by name and try to discover service information
                            serviceSelector = WiFiDirectService.GetSelector(serviceName, serviceInfoDataWriter.DetachBuffer());
                        }
                    }

                    List <string> additionalProperties = new List <string>();
                    additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceAddress");
                    additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceName");
                    additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceInformation");
                    additionalProperties.Add("System.Devices.WiFiDirectServices.AdvertisementId");
                    additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceConfigMethods");

                    // Note: This sample demonstrates finding services with FindAllAsync, which does a discovery and returns a list
                    // It is also possible to use DeviceWatcher to receive updates as soon as services are found and to continue the discovery until it is stopped
                    // See the DeviceWatcher sample for an example on how to use that class instead of DeviceInformation.FindAllAsync
                    DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(serviceSelector, additionalProperties);

                    if (deviceInfoCollection != null && deviceInfoCollection.Count > 0)
                    {
                        RootPage.NotifyUser("Done discovering services, found " + deviceInfoCollection.Count + " services", NotifyType.StatusMessage);

                        foreach (var device in deviceInfoCollection)
                        {
                            discoveredDevices.Add(new DiscoveredDeviceWrapper(device, this));
                        }
                    }
                    else
                    {
                        RootPage.NotifyUser("Done discovering services, No services found", NotifyType.StatusMessage);
                    }

                    // Update UI list
                    if (scenario3 != null)
                    {
                        scenario3.UpdateDiscoveryList(discoveredDevices);
                    }
                }
                catch (Exception ex)
                {
                    RootPage.NotifyUser(String.Format("Failed to discover services: {0}", ex.Message), NotifyType.ErrorMessage);
                    throw ex;
                }
            }