Exemplo n.º 1
0
        /// <summary>
        /// Инициализация адаптера
        /// </summary>
        /// <returns></returns>
        private async Task <bool> InitializeFirstAdapter()
        {
            return(await Task.Run(async() =>
            {
                if (_wifiAdapter == null)
                {
                    bool res = false;
                    WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync();

                    if (access != WiFiAccessStatus.Allowed)
                    {
                        throw new Exception("WiFiAccessStatus not allowed");
                    }
                    else
                    {
                        var wifiAdapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                        if (wifiAdapterResults.Count >= 1)
                        {
                            _wifiAdapter = await WiFiAdapter.FromIdAsync(wifiAdapterResults[0].Id);
                            res = true;
                        }
                        else
                        {
                            throw new Exception("WiFi Adapter not found.");
                        }
                    }
                    return res;
                }
                else
                {
                    return true;
                }
            }));
        }
Exemplo n.º 2
0
        public async Task <IEnumerable <WifiNetwork> > GetWifiAsync()
        {
            _wifis          = new List <WifiNetwork>();
            _wifisOriginals = new List <WiFiNetworkDisplay>();

            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                //rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
            }
            else
            {
                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (result.Count >= 1)
                {
                    _firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                    await ScanAsync();

                    return(_wifis.OrderByDescending(w => w.SignalBars));
                }
                else
                {
                    //No WiFi Adapters detected on this machine
                }
            }

            return(null);
        }
Exemplo n.º 3
0
        private async Task <bool> _getNetworks()
        {
            WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                _done = true;
                return(false);
            }
            else
            {
                DeviceInformationCollection adapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (adapterResults.Count() >= 1)
                {
                    _WiFiAdapter = await WiFiAdapter.FromIdAsync(adapterResults[0].Id);
                }
                else
                {
                    _done = true;
                    return(false);
                }
            }
            await _WiFiAdapter.ScanAsync();

            foreach (WiFiAvailableNetwork availableNetwork in _WiFiAdapter.NetworkReport.AvailableNetworks)
            {
                _WiFiNetworks.Add(availableNetwork.Ssid);
            }
            return(true);
        }
Exemplo n.º 4
0
        public static async Task <bool> TryConnectWlan()
        {
            resetEvent = new AutoResetEvent(false);
            try
            {
                var access = await WiFiAdapter.RequestAccessAsync();

                if (access == WiFiAccessStatus.Allowed)
                {
                    TurnOnWiFi();
                    StartWiFiHotspot();

                    var result = resetEvent.WaitOne(120000);

                    DisposeWiFiPublisher();
                    return(result);
                }

                return(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            ResultCollection = new ObservableCollection <WiFiNetworkDisplay>();
            rootPage         = MainPage.Current;

            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
            }
            else
            {
                DataContext = this;

                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (result.Count >= 1)
                {
                    firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                    var button = new Button();
                    button.Content = string.Format("Scan");
                    button.Click  += Button_Click;
                    Buttons.Children.Add(button);
                }
                else
                {
                    rootPage.NotifyUser("No WiFi Adapters detected on this machine", NotifyType.ErrorMessage);
                }
            }
        }
Exemplo n.º 6
0
        private async void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            var wifiAdapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

            WiFiAdapter wa = await WiFiAdapter.FromIdAsync(wifiAdapterResults[0].Id);

            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;
            WiFiConnectionResult result;

            foreach (var availableNetwork in _report.AvailableNetworks)
            {
                if (availableNetwork.Ssid == _selectedSSID)
                {
                    if (txtPassword.Text.Length > 1)
                    {
                        var credential = new PasswordCredential();
                        credential.Password = txtPassword.Text;
                        result = await wa.ConnectAsync(availableNetwork, reconnectionKind, credential);
                    }
                    else
                    {
                        result = await wa.ConnectAsync(availableNetwork, reconnectionKind);
                    }
                }
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var result = await WiFiAdapter.RequestAccessAsync();

            if (result != WiFiAccessStatus.Allowed)
            {
                ScenarioOutput.Text = "Access denied";
            }
            else
            {
                wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();

                int index = 0;
                foreach (var adapter in wiFiAdapters)
                {
                    var button = new Button();
                    button.Tag     = index;
                    button.Content = String.Format("Adapter #{0}", index++);
                    button.Click  += Button_Click;
                    Buttons.Children.Add(button);
                }
            }
        }
Exemplo n.º 8
0
        private async Task <List <string> > GetWirelessSuits()
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

            if (result.Count >= 1)
            {
                var nwAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                await nwAdapter.ScanAsync();

                //because spelling errors
                var nw = nwAdapter.NetworkReport.AvailableNetworks.Where(network => network.Ssid.Contains("NSVR") || network.Ssid.Contains("NVSR:"));

                return(nw.Select(suit => suit.Ssid).ToList());
                //if (nw.Count() > 0)
                //{
                //	var suitAP = nw.First();
                //	var pass = SsidToPassword(suitAP.Ssid);
                //	var conn = await nwAdapter.ConnectAsync(suitAP, WiFiReconnectionKind.Automatic, new Windows.Security.Credentials.PasswordCredential("none", "none", pass));

                //	return new Tuple<WiFiConnectionStatus, string>(conn.ConnectionStatus, pass);

                //}
            }

            return(new List <string>());
        }
Exemplo n.º 9
0
        private async void ScanForWiFiAdaptersAsync()
        {
            if (m_wiFiAdapter == null)
            {
                UpdateStatusAsync("Requesting WiFi access...", NotifyType.StatusMessage);
                WiFiAccessStatus accessStatus = await WiFiAdapter.RequestAccessAsync();

                if (accessStatus != WiFiAccessStatus.Allowed)
                {
                    UpdateStatusAsync("WiFi access denied.", NotifyType.ErrorMessage);
                }
                else
                {
                    m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                    if (m_wiFiAdapterList.Count > 0)
                    {
                        for (int i = 0; i < m_wiFiAdapterList.Count; i++)
                        {
                            m_wiFiAdapterDisplayNames.Add(string.Format("Adapter {0}", (i + 1)));
                        }
                        WiFiAdapterListVisibility = Visibility.Visible;
                        UpdateStatusAsync("Please select a WiFi adapter.", NotifyType.StatusMessage);
                    }
                    else
                    {
                        UpdateStatusAsync("No WiFi adapters detected on this machine.", NotifyType.ErrorMessage);
                    }
                }
            }
        }
Exemplo n.º 10
0
        public static IAsyncAction WaitForWiFiConnection()
        {
            return(AsyncInfo.Run(async(cancel) =>
            {
                if (!await EnableWiFi())
                {
                    return;
                }

                var accessAllowed = await WiFiAdapter.RequestAccessAsync();
                if (accessAllowed == WiFiAccessStatus.Allowed)
                {
                    var adapterList = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
                    var wifiAdapter = await WiFiAdapter.FromIdAsync(adapterList[0].Id);

                    for (var i = 0; i < 5; i++)
                    {
                        cancel.ThrowIfCancellationRequested();
                        await wifiAdapter.ScanAsync();
                        await Task.Delay(100);
                        if (await wifiAdapter.NetworkAdapter.GetConnectedProfileAsync() != null)
                        {
                            break;
                        }
                    }
                }
            }));
        }
Exemplo n.º 11
0
        public async Task <int> Initialize()
        {
            if (m_wiFiAdapter == null)
            {
                //Request access of WiFi adapter.
                WiFiAccessStatus accessStatus = await WiFiAdapter.RequestAccessAsync();

                if (accessStatus != WiFiAccessStatus.Allowed)
                {
                    rootPage.Log("NETWORK_MANAGER::[ERROR]ScanForWiFiAdapterAsync: WiFi access denied.");
                }
                else
                {
                    //Find WiFi adatper
                    m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                    rootPage.Log("NETWORK_MANAGER::Found " + m_wiFiAdapterList.Count + " wifi adapter.");
                    while (m_wiFiAdapterList.Count < 1)
                    {
                        await System.Threading.Tasks.Task.Delay(3000);

                        m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                        rootPage.Log("NETWORK_MANAGER::Found " + m_wiFiAdapterList.Count + " wifi adapter.");
                    }

                    //Get the first WiFi adatper from the list.
                    //TODO: Edit this part if the system has more than one WiFi adatpers.
                    m_wiFiAdapter = m_wiFiAdapterList[0];
                }
                return(-1);
            }
            return(0);
        }
Exemplo n.º 12
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= MainPage_Loaded;
            Displays.Clear();
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                Allowed = false;
                Toast.ShowError("不允许连接wifi,请确认已开启wifi");
            }
            else
            {
                var result =
                    await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (result.Count >= 1)
                {
                    firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
                    await UpdateConnectivityStatusAsync();

                    NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
                    OnRefreshRequested(null, null);
                }
                Allowed = true;
            }
        }
Exemplo n.º 13
0
        private async Task <Tuple <Windows.Devices.WiFi.WiFiConnectionStatus, string> > ConnectWifiAndGetPassword(string ssid)
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

            if (result.Count >= 1)
            {
                var nwAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                await nwAdapter.ScanAsync();

                //because spelling errors
                var nw = nwAdapter.NetworkReport.AvailableNetworks.Where(network => network.Ssid.Contains(ssid));
                if (nw.Count() > 0)
                {
                    var suitAP = nw.First();
                    var pass   = SsidToPassword(suitAP.Ssid);
                    var conn   = await nwAdapter.ConnectAsync(suitAP, WiFiReconnectionKind.Automatic, new Windows.Security.Credentials.PasswordCredential("none", "none", pass));

                    return(new Tuple <WiFiConnectionStatus, string>(conn.ConnectionStatus, pass));
                }
            }

            return(new Tuple <WiFiConnectionStatus, string>(WiFiConnectionStatus.NetworkNotAvailable, ""));
        }
Exemplo n.º 14
0
        public async Task <bool> StartAsync()
        {
            // only one start allowed on the object
            lock (this)
            {
                if (_started)
                {
                    return(false);
                }

                _started = true;
            }

            if (await WiFiAdapter.RequestAccessAsync() != WiFiAccessStatus.Allowed)
            {
                return(false);
            }

            _started = true;

            // enumerate and monitor WiFi devices in the system
            string deviceSelector = WiFiAdapter.GetDeviceSelector();

            _watcher          = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(deviceSelector);
            _watcher.Added   += _watcher_Added;
            _watcher.Removed += _watcher_Removed;

            _watcher.Start();

            return(true);
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            ResultCollection = new ObservableCollection <WiFiNetworkDisplay>();
            rootPage         = MainPage.Current;

            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var result = await WiFiAdapter.RequestAccessAsync();

            if (result != WiFiAccessStatus.Allowed)
            {
                rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
            }
            else
            {
                DataContext = this;

                wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();

                int index = 0;
                foreach (var adapter in wiFiAdapters)
                {
                    var button = new Button();
                    button.Tag     = index;
                    button.Content = String.Format("WiFi Adapter {0}", ++index);
                    button.Click  += Button_Click;
                    Buttons.Children.Add(button);
                }
            }
        }
Exemplo n.º 16
0
        public async void Scan()
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

            if (result.Count >= 1)
            {
                nwAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                await nwAdapter.ScanAsync();

                sp.Children.Clear();
                foreach (var item in nwAdapter.NetworkReport.AvailableNetworks)
                {
                    StackPanel s = new StackPanel();
                    s.Orientation = Orientation.Horizontal;
                    Button    b = new Button();
                    TextBlock t = new TextBlock();
                    t.Text     = $"{item.NetworkRssiInDecibelMilliwatts} {item.ChannelCenterFrequencyInKilohertz} {item.IsWiFiDirect} {item.NetworkKind} {item.SecuritySettings.NetworkAuthenticationType} {item.SecuritySettings.NetworkAuthenticationType} {item.SignalBars} {item.Uptime}";
                    b.Content += item.Ssid;

                    b.Click += B_Click;
                    s.Children.Add(b);
                    s.Children.Add(t);
                    sp.Children.Add(s);
                }
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                ScenarioOutput.Text = "Access denied";
            }
            else
            {
                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (result.Count >= 1)
                {
                    firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                    var button = new Button();
                    button.Content = string.Format("Scan");
                    button.Click  += Button_Click;
                    Buttons.Children.Add(button);
                }
                else
                {
                    ScenarioOutput.Text = "No WiFi Adapters detected on this machine";
                }
            }
        }
Exemplo n.º 18
0
        public static async Task <string> GetSsid()
        {
            var profile = NetworkInformation.GetInternetConnectionProfile();

            if (profile != null && profile.IsWlanConnectionProfile)
            {
                return(profile.WlanConnectionProfileDetails.GetConnectedSsid());
            }

            var access = await WiFiAdapter.RequestAccessAsync();

            if (access == WiFiAccessStatus.Allowed)
            {
                var adapters = await WiFiAdapter.FindAllAdaptersAsync();

                foreach (var adapter in adapters)
                {
                    var connectedProfile = await adapter.NetworkAdapter.GetConnectedProfileAsync();

                    if (connectedProfile != null)
                    {
                        return(connectedProfile.ProfileName);
                    }
                }
            }
            return(string.Empty);
        }
Exemplo n.º 19
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                ScenarioOutput.Text = "Access denied";
            }
            else
            {
                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (result.Count >= 1)
                {
                    firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                    RegisterButton.IsEnabled = true;
                }
                else
                {
                    ScenarioOutput.Text = "No WiFi Adapters detected on this machine";
                }
            }
        }
Exemplo n.º 20
0
 private static async Task <bool> TestAccess()
 {
     if (!accessStatus.HasValue)
     {
         accessStatus = await WiFiAdapter.RequestAccessAsync();
     }
     return(accessStatus == WiFiAccessStatus.Allowed);
 }
Exemplo n.º 21
0
        /// <summary>
        /// Gather Network adaptater infos
        /// </summary>
        /// <param name="returnedInfo">returned Dictionnary filled with new info</param>
        /// <returns>Dictionnary<String-String> : network informations</returns>
        public async override Task <Dictionary <string, string> > GetInfos(Dictionary <String, String> returnedInfo)
        {
            returnedInfo = await base.GetInfos(returnedInfo);

            returnedInfo.Add("------- " + LABEL + " -------", "----------------");
            incrementEthernet = 0;
            incrementUnknow   = 0;
            incrementWifi     = 0;
            increm            = 'a';
#if WINDOWS_UWP
            //Ask permission
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                returnedInfo.Add("Error", "Wifi Acces denied");
            }
            else
            {
                //Get the list of Wifi Adaptaters
                var DeviceswifiAdaptaters = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                WifiAdaptaters = new Dictionary <Guid, WiFiAdapter>();
                //Transfer list in a more convenient Dictionnary
                foreach (WiFiAdapter item in await WiFiAdapter.FindAllAdaptersAsync())
                {
                    WifiAdaptaters.Add(item.NetworkAdapter.NetworkAdapterId, item);
                }
                //Get the list of network connection
                var connectedProfiles = NetworkInformation.GetConnectionProfiles().ToList();
                //Switch is irrelevant now but can be useful if more specific treatment is needed
                foreach (var item in NetworkInformation.GetHostNames())
                {
                    switch (item.Type)
                    {
                    case HostNameType.DomainName:
                        if (!item.DisplayName.Contains(".local"))
                        {
                            returnedInfo.Add("Machine Name", item.DisplayName);
                        }
                        break;

                    case HostNameType.Ipv4:
                    case HostNameType.Ipv6:
                    case HostNameType.Bluetooth:
                        returnedInfo = await getAdaptaterType(item, returnedInfo);

                        returnedInfo.Add(increm + "- Adress : ", item.DisplayName);
                        returnedInfo.Add(increm + "- Network Type : ", getNetworkType(item));
                        increment++;
                        increm++;
                        break;
                    }
                }
            }
#endif
            return(returnedInfo);
        }
Exemplo n.º 22
0
        public async void Start()
        {
            try
            {
                _iconFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///IoTOnboardingService/icon72x72.png"));

                var connectionProfiles = NetworkInformation.GetConnectionProfiles();
                foreach (var profile in connectionProfiles)
                {
                    if (profile.IsWlanConnectionProfile)
                    {
                        lock (_stateLock)
                        {
                            _state = OnboardingState.ConfiguredValidated;
                        }
                        break;
                    }
                }

                if (_softAccessPoint == null)
                {
                    _softAccessPoint = new OnboardingAccessPoint(string.Format(_resourceLoader.GetString("SoftApSsidTemplate"), _onboardingInstanceId), _resourceLoader.GetString("SoftApPassword"));
                }

                if (_busAttachment == null)
                {
                    _busAttachment = new AllJoynBusAttachment();
                    _busAttachment.AboutData.DefaultDescription  = string.Format(_resourceLoader.GetString("DefaultDescriptionTemplate"), _onboardingInstanceId);
                    _busAttachment.AboutData.DefaultManufacturer = _resourceLoader.GetString("DefaultManufacturer");
                    _busAttachment.AboutData.ModelNumber         = _resourceLoader.GetString("ModelNumber");

                    _onboardingProducer         = new OnboardingProducer(_busAttachment);
                    _onboardingProducer.Service = this;

                    _iconProducer         = new IconProducer(_busAttachment);
                    _iconProducer.Service = this;
                }

                if (_deviceWatcher == null)
                {
                    var accessStatus = await WiFiAdapter.RequestAccessAsync();

                    if (accessStatus == WiFiAccessStatus.Allowed)
                    {
                        _deviceWatcher          = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector());
                        _deviceWatcher.Added   += this.HandleAdapterAdded;
                        _deviceWatcher.Removed += this.HandleAdapterRemoved;

                        _deviceWatcher.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 23
0
        private async void ClientBtn_Click(object sender, RoutedEventArgs e)
        {
            var access2 = await WiFiAdapter.RequestAccessAsync();

            if (access2 != WiFiAccessStatus.Allowed)
            {
                MesajFin.Text = "acces denied!";
            }
            else
            {
                MesajFin.Text = "acces allowed!";
                if (wiFiAdapters == null)
                {
                    wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();
                }
                adapter2 = wiFiAdapters.First();
                await adapter2.ScanAsync(); //scan

                report = adapter2.NetworkReport;
                scanVals.Clear();
                foreach (var network in report.AvailableNetworks)
                {
                    //listBox1.Items.Add(network.Ssid + " " + network.NetworkRssiInDecibelMilliwatts + "dBm");
                    scanVals.Add(network.Ssid, network.NetworkRssiInDecibelMilliwatts.ToString());
                }
                List <int> dbmValues;
                foreach (String key in scanVals.AllKeys)
                {
                    dbmValues = scanVals.GetValues(key).Select(int.Parse).ToList();
                    scanVals.Set(key, Math.Truncate(dbmValues.Average()).ToString()); //take the mean of the values for each network
                                                                                      //  listBox1.Items.Add(key + " " + scanVals[key]);
                }
                var rez = NvcToDictionary(scanVals);
                ClientScan = rez.ToDictionary(pair => pair.Key, pair => Convert.ToDouble(pair.Value));
                scanVals.Clear();
                myList = ClientScan.ToList();

                myList.Sort((firstPair, nextPair) =>
                {
                    return(nextPair.Value.CompareTo(firstPair.Value));
                }
                            );
                listBox1.Items.Clear();
                foreach (KeyValuePair <string, double> netw in myList)
                {
                    listBox1.Items.Add(netw.Key + " " + netw.Value);
                }// look first three networks or if nb < 3 put that nb.If zero network.. -> messsage. if no area - > error
                 //if key(SSID) in area - compute error and save it to an nvc for area 1, look in next area, do the same, iterate for next
                 //network found and so on. If a network is not found in an area , add maxerror to nvc. if no area contains a network raise flag and take
                 //another network. in de end, do a mean for all nvc entries, convert nvc to dictionary then to dict double and select the one with smallest
                 //error
            }
        }
Exemplo n.º 24
0
 public async Task RequestWifiAccess()
 {
     try
     {
         wiFiaccess = await WiFiAdapter.RequestAccessAsync();
     }
     catch (Exception ex)
     {
         Debug.WriteLine("RequestWifiAccess() Exception: " + ex.Message);
         throw;
     }
 }
Exemplo n.º 25
0
        public async Task GetNetworksAsync(bool repeat, int intervalMs, Action <ServiceResult> complete)
        {
            if (complete == null)
            {
                return;
            }
            try
            {
                //  check if we have access to wifi
                var status = await WiFiAdapter.RequestAccessAsync();

                if (status != WiFiAccessStatus.Allowed)
                {
                    complete(new ServiceResult {
                        Status = ServiceResultStatus.Failure, Message = "Access to WIFI is denied."
                    });
                }
                //  get a list of adapters
                var adapters = await WiFiAdapter.FindAllAdaptersAsync();

                foreach (var adapter in adapters)
                {
                    adapter.AvailableNetworksChanged += (a, o) =>
                    {
                        var signals = new List <NetworkSignal>();
                        foreach (var network in a.NetworkReport.AvailableNetworks)
                        {
                            signals.Add(new NetworkSignal {
                                MacAddress = network.Bssid, Ssid = (string.IsNullOrEmpty(network.Ssid)) ? "[hidden]" : network.Ssid, Level = network.NetworkRssiInDecibelMilliwatts
                            });
                        }
                        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            complete(new ServiceResult <List <NetworkSignal> > {
                                Status = ServiceResultStatus.Success, Payload = signals
                            });
                        });
                    };
                    await adapter.ScanAsync();
                }
            }
            catch (Exception ex)
            {
                complete(new ServiceResult <Exception> {
                    Status = ServiceResultStatus.Error, Payload = ex
                });
            }
        }
        public static async Task <WiFiConnectionStatus> ConnectToWiFiNetwork(string ssid = DefaultSsid, string password = DefaultPassword)
        {
            var connectionStatus = WiFiConnectionStatus.NetworkNotAvailable;

            // SSID 및 비밀번호 유효성 확인
            if (!string.IsNullOrEmpty(ssid) && !string.IsNullOrEmpty(password))
            {
                // 앱이 와이파이 기능에 액세스할 수 있는지 확인
                var hasAccess = await WiFiAdapter.RequestAccessAsync();

                // 액세스 가능하면, 첫 번째 와이파이 어댑터를 사용해 사용 가능한 네트워크 검색
                if (hasAccess == WiFiAccessStatus.Allowed)
                {
                    // 사용 가능한 첫 번째 와이파이 어댑터 획득
                    var wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();

                    var firstWiFiAdapterAvailable = wiFiAdapters.FirstOrDefault();

                    if (firstWiFiAdapterAvailable != null)
                    {
                        // 네트워크 검색
                        await firstWiFiAdapterAvailable.ScanAsync();

                        // 사용 가능한 네트워크 목록을 SSID로 필터링
                        var wiFiNetwork = firstWiFiAdapterAvailable.NetworkReport.
                                          AvailableNetworks.Where(network => network.Ssid == ssid).FirstOrDefault();

                        if (wiFiNetwork != null)
                        {
                            // 제공된 암호를 사용해 네트워크에 연결 시도
                            var passwordCredential = new PasswordCredential()
                            {
                                Password = password
                            };

                            var connectionResult = await firstWiFiAdapterAvailable.
                                                   ConnectAsync(wiFiNetwork,
                                                                WiFiReconnectionKind.Automatic, passwordCredential);

                            // 연결 상태 반환
                            connectionStatus = connectionResult.ConnectionStatus;
                        }
                    }
                }
            }

            return(connectionStatus);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Gets connection ssid for the current Wifi Connection.
        /// </summary>
        /// <returns> string value of current ssid/></returns>
        ///
        public static async Task <string> GetNetwoksSSid()
        {
            try
            {
                WiFiAdapter firstAdapter;
                var         access = await WiFiAdapter.RequestAccessAsync();

                if (access != WiFiAccessStatus.Allowed)
                {
                    return("Acess Denied");
                }
                else
                {
                    var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                    if (result.Count >= 1)
                    {
                        firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
                    }
                    else
                    {
                        return("No WiFi Adapters Detected");
                    }
                    var connectedProfile = await firstAdapter.NetworkAdapter.GetConnectedProfileAsync();

                    if (connectedProfile != null)
                    {
                        if (connectedProfile.ProfileName.ToLower().Equals("vit2.4g") || connectedProfile.ProfileName.ToLower().Equals("vit5g"))
                        {
                            return("OK");
                        }
                        else
                        {
                            return(connectedProfile.ProfileName);
                        }
                    }
                    else if (connectedProfile == null)
                    {
                        return("WiFi adapter disconnected");
                    }
                }
            }
            catch
            {
            }

            return(null);
        }
Exemplo n.º 28
0
        public async Task <WiFiScanResultTypes> LoadData()
        {
            Enabled_btnRefresh = false;

            ShowRunning();

            WifiNetworks = new ObservableCollection <WiFiAvailableNetwork>();

            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                Enabled_btnRefresh = true;

                HideRunning();

                return(WiFiScanResultTypes.NO_ACCESS_TO_WIFI_CARD);
            }

            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

            if (result.Count > 0)
            {
                PrimaryAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
            }
            else
            {
                Enabled_btnRefresh = true;
                HideRunning();

                return(WiFiScanResultTypes.NO_WIFI_CARD);
            }

            await PrimaryAdapter.ScanAsync();

            foreach (var network in PrimaryAdapter.NetworkReport.AvailableNetworks)
            {
                WifiNetworks.Add(network);
            }

            WifiNetworks = new ObservableCollection <WiFiAvailableNetwork>(WifiNetworks.OrderByDescending(a => a.SignalBars));

            Enabled_btnRefresh = true;

            HideRunning();

            return(WiFiScanResultTypes.SUCCESS);
        }
Exemplo n.º 29
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access == WiFiAccessStatus.Allowed)
            {
                DataContext = this;

                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                if (result.Count >= 1)
                {
                    wifiAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
                }
            }
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access == WiFiAccessStatus.Allowed)
            {
                var radios = await Radio.GetRadiosAsync();

                foreach (var radio in radios)
                {
                    if (radio.Kind == RadioKind.WiFi)
                    {
                        await radio.SetStateAsync(RadioState.Off);
                    }
                }
            }
        }