Пример #1
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);
                    }
                }
            }
        }
Пример #2
0
        private async void WifiApCollectionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            WifiAvailableAP selectedNetwork = e.AddedItems[0] as WifiAvailableAP;

            if (selectedNetwork == null || m_WifiAdapter == null)
            {
                //rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
                return;
            }

            WiFiConnectionResult result;

            if (selectedNetwork.network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
            {
                this.ShowProgressRing();

                result = await m_WifiAdapter.ConnectAsync(selectedNetwork.network, WiFiReconnectionKind.Automatic);

                this.CloseProgressRing();

                if (result.ConnectionStatus == WiFiConnectionStatus.Success)
                {
                    this.Frame.GoBack();
                }
            }
            else
            {
                m_ConnectInfo.Show();
            }
        }
Пример #3
0
        /// <summary>
        /// Connects desired WiFi network specified by the input SSID.
        /// </summary>
        /// <param name="ssid">SSID of the desired WiFi network</param>
        /// <param name="password">Password of the desired WiFI network</param>
        public async Task <WiFiConnectionStatus> Connect(string ssid, string password)
        {
            rootPage.Log("NETWORK_MANAGER::Connecting to " + ssid + "...");

            try
            {
                foreach (WiFiAvailableNetwork network in m_wiFiAdapter.NetworkReport.AvailableNetworks)
                {
                    if (network.Ssid == ssid)
                    {
                        WiFiConnectionResult result = null;
                        if (network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
                        {
                            result = await m_wiFiAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);
                        }
                        else
                        {
                            PasswordCredential credential = new PasswordCredential();
                            credential.Password = password;
                            result = await m_wiFiAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, credential);
                        }

                        rootPage.Log("NETWORK_MANAGER::Connection result: " + result.ConnectionStatus.ToString());
                        return(result.ConnectionStatus);
                    }
                }
                rootPage.Log("NETWORK_MANAGER::Connection result: Network not found.");
                return(WiFiConnectionStatus.NetworkNotAvailable);
            }
            catch (Exception e)
            {
                rootPage.Log("NETWORK_MANAGER::[ERROR] Hr" + e.HResult + ": " + e.Message);
            }
            return(WiFiConnectionStatus.UnspecifiedFailure);
        }
        public async Task <WiFiConnectionResult> ConnectAsync(WiFiNetworkDisplay network, WiFiReconnectionKind reconnectionKind, string password)
        {
            WiFiConnectionResult result;

            ReconnectionKind = reconnectionKind;
            if (network.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211)
            {
                result = await _firstAdapter.ConnectAsync(network.AvailableNetwork, reconnectionKind);
            }
            else
            {
                // Only the password potion of the credential need to be supplied
                var credential = new PasswordCredential {
                    Password = password
                };
                result = await _firstAdapter.ConnectAsync(network.AvailableNetwork, reconnectionKind, credential);
            }

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var net in NetworkCollection)
            {
                net.UpdateConnectivityLevel();
            }

            return(result);
        }
Пример #5
0
        private async void ConnectToNetwork(WiFiAvailableNetwork network)
        {
            lock (_stateLock)
            {
                _state = OnboardingState.ConfiguredValidating;
            }

            WiFiConnectionResult connectionResult;

            if (network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
            {
                connectionResult = await _wlanAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);
            }
            else
            {
                connectionResult = await _wlanAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, new PasswordCredential { Password = _personalApPassword });
            }

            lock (_stateLock)
            {
                if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
                {
                    _error        = OnboardingError.Validated;
                    _errorMessage = null;
                    _state        = OnboardingState.ConfiguredValidated;
                }
                else
                {
                    _state        = OnboardingState.ConfiguredError;
                    _errorMessage = connectionResult.ConnectionStatus.ToString();

                    switch (connectionResult.ConnectionStatus)
                    {
                    case WiFiConnectionStatus.AccessRevoked:
                    case WiFiConnectionStatus.InvalidCredential:
                    {
                        _error = OnboardingError.Unauthorized;
                        break;
                    }

                    case WiFiConnectionStatus.UnsupportedAuthenticationProtocol:
                    {
                        _error = OnboardingError.UnsupportedProtocol;
                        break;
                    }

                    case WiFiConnectionStatus.NetworkNotAvailable:
                    case WiFiConnectionStatus.Timeout:
                    case WiFiConnectionStatus.UnspecifiedFailure:
                    default:
                    {
                        _error = OnboardingError.ErrorMessage;
                        break;
                    }
                    }
                }
            }
        }
Пример #6
0
        private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;

            if (selectedNetwork == null || firstAdapter == null)
            {
                rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
                return;
            }
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }

            WiFiConnectionResult result;

            if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
                selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
            }
            else
            {
                // Only the password potion of the credential need to be supplied
                var credential = new PasswordCredential();
                credential.Password = NetworkKey.Password;

                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
            }

            if (result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);

                // refresh the webpage
                webViewGrid.Visibility          = Visibility.Visible;
                toggleBrowserButton.Content     = "Hide Browser Control";
                refreshBrowserButton.Visibility = Visibility.Visible;
            }
            else
            {
                rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
            }

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var network in ResultCollection)
            {
                network.UpdateConnectivityLevel();
            }
        }
Пример #7
0
        private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;

            if (selectedNetwork == null || firstAdapter == null)
            {
                rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
                return;
            }
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }

            WiFiConnectionResult result;

            if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
                selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
            }
            else
            {
                // Only the password portion of the credential need to be supplied
                var credential = new PasswordCredential();

                // Make sure Credential.Password property is not set to an empty string.
                // Otherwise, a System.ArgumentException will be thrown.
                // The default empty password string will still be passed to the ConnectAsync method,
                // which should return an "InvalidCredential" error
                if (!string.IsNullOrEmpty(NetworkKey.Password))
                {
                    credential.Password = NetworkKey.Password;
                }

                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
            }

            if (result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
            }
        }
Пример #8
0
 private async void B_Click(object sender, RoutedEventArgs e)
 {
     Button b    = (Button)sender;
     string ssid = b.Content as string;
     var    nw   = nwAdapter.NetworkReport.AvailableNetworks.Where(y => y.Ssid.ToLower() == ssid).FirstOrDefault();
     await nwAdapter.ConnectAsync(nw, WiFiReconnectionKind.Automatic);
 }
Пример #9
0
        /// <summary>
        /// Подключится к устройству
        /// </summary>
        /// <param name="wiFi">Устройсво как точка доступа</param>
        /// <param name="credential">Пароль</param>
        /// <returns></returns>
        public async Task <bool> ConnectToDeviceAsync(WiFiAvailableNetwork wiFi, PasswordCredential credential)
        {
            _currentWiFi       = wiFi;
            _currentCredential = credential;

            WiFiConnectionResult conResult;
            bool initRes = await InitializeFirstAdapter();

            if (initRes)
            {
                do
                {
                    conResult = await _wifiAdapter.ConnectAsync(wiFi, WiFiReconnectionKind.Manual, credential);

                    if (conResult.ConnectionStatus != WiFiConnectionStatus.Success)
                    {
                        System.Diagnostics.Debug.WriteLine("Connection failed!");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Connection success!");
                    }
                }while (conResult.ConnectionStatus != WiFiConnectionStatus.Success);

                return(true);
            }
            return(false);
        }
Пример #10
0
        private async Task <bool> _connect(string ssid, string psk)
        {
            await _WiFiAdapter.ScanAsync();

            WiFiAvailableNetwork _network   = _WiFiAdapter.NetworkReport.AvailableNetworks.First(n => n.Ssid == ssid);
            PasswordCredential   credential = new PasswordCredential();

            credential.Password = psk;

            Task <WiFiConnectionResult> connected = _WiFiAdapter.ConnectAsync(_network, WiFiReconnectionKind.Manual, credential).AsTask();

            WiFiConnectionResult result = null;

            if (connected != null)
            {
                result = await connected;
            }
            if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #11
0
 private async Task <WifiErrorCode> ConnectToNetwork(WiFiAdapter adapter, string ssid, string password)
 {
     try {
         // Should already be scanned
         WiFiNetworkReport report      = adapter.NetworkReport;
         WifiErrorCode     returnValue = WifiErrorCode.NetworkNotAvailable;
         foreach (var net in report.AvailableNetworks)
         {
             if (net.Ssid == ssid)
             {
                 // TODO Will need to have multiple types of authentication
                 PasswordCredential cred = new PasswordCredential()
                 {
                     Password = password
                 };
                 returnValue = (await adapter.ConnectAsync(net, WiFiReconnectionKind.Automatic, cred)).ConnectionStatus.Convert();
                 break;
             }
         }
         if (returnValue != WifiErrorCode.Success)
         {
             this.OnError?.Invoke(this, new WifiError(returnValue));
         }
         return(returnValue);
     }
     catch (Exception e) {
         WrapErr.SafeAction(() => {
             this.OnError?.Invoke(this, new WifiError(WifiErrorCode.Unknown));
         });
         return(WifiErrorCode.Unknown);
     }
 }
Пример #12
0
        private async void OnItemClick(object sender, ItemClickEventArgs e)
        {
            var selectedNetwork = (WiFiNetworkDisplay)e.ClickedItem;
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;
            WiFiConnectionResult result;

            if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType ==
                NetworkAuthenticationType.Open80211)
            {
                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);

                ConnectResult(result);
            }
            else
            {
                if (selectedNetwork.ConnectivityLevel == "已连接")
                {
                    firstAdapter.Disconnect();
                    await selectedNetwork.UpdateConnectivityLevel();

                    return;
                }

                if (selectedNetwork.Pwd.Length >= 8)
                {
                    var credential = new PasswordCredential();
                    credential.Password = selectedNetwork.Pwd;
                    result =
                        await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);

                    ConnectResult(result);
                }
                else
                {
                    var message = new PwdControl(async(x) =>
                    {
                        var credential      = new PasswordCredential();
                        credential.Password = x;
                        result =
                            await
                            firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
                        ConnectResult(result);
                    });
                    await message.ShowAsync();
                }
            }
        }
Пример #13
0
        private async void ConnectToSoftAPAsync()
        {
            if (m_wiFiAdapter != null)
            {
                if (m_selectedSoftAPNetwork == null)
                {
                    UpdateStatusAsync("Network not selected. Please select a network.", NotifyType.ErrorMessage);
                }
                else
                {
                    UpdateStatusAsync(string.Format("Attempting to connect to {0}...", m_selectedSoftAPNetwork.Ssid), NotifyType.StatusMessage);
                    WiFiConnectionResult result = null;
                    if (m_selectedSoftAPNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
                    {
                        result = await m_wiFiAdapter.ConnectAsync(m_selectedSoftAPNetwork, WiFiReconnectionKind.Manual);
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(m_softAPPassword))
                        {
                            UpdateStatusAsync("No password entered.", NotifyType.ErrorMessage);
                        }
                        else
                        {
                            PasswordCredential credential = new PasswordCredential();
                            credential.Password = m_softAPPassword;
                            result = await m_wiFiAdapter.ConnectAsync(m_selectedSoftAPNetwork, WiFiReconnectionKind.Manual, credential);
                        }
                        ClearPasswords();
                    }

                    if (result != null)
                    {
                        if (result.ConnectionStatus == WiFiConnectionStatus.Success)
                        {
                            UpdateStatusAsync(string.Format("Successfully connected to {0}.", m_selectedSoftAPNetwork.Ssid), NotifyType.StatusMessage);
                            ScanForOnboardingInterfaces();
                        }
                        else
                        {
                            UpdateStatusAsync(string.Format("Failed to connect to {0} with error: {1}.", m_selectedSoftAPNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
                        }
                    }
                }
            }
        }
Пример #14
0
        public async Task ConnectWifiAsync(string bssid, string pwd)
        {
            var selectedNetwork = _wifisOriginals.First(w => w.Bssid == bssid);

            if (selectedNetwork == null || _firstAdapter == null)
            {
                //Network not selected"
                return;
            }

            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;

            WiFiConnectionResult result;

            if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
                selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                result = await _firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
            }
            else
            {
                // Only the password portion of the credential need to be supplied
                var credential = new PasswordCredential();

                // Make sure Credential.Password property is not set to an empty string.
                // Otherwise, a System.ArgumentException will be thrown.
                // The default empty password string will still be passed to the ConnectAsync method,
                // which should return an "InvalidCredential" error
                //if (!string.IsNullOrEmpty(NetworkKey.Password))
                //{
                //    credential.Password = NetworkKey.Password;
                //}

                result = await _firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
            }

            if (result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                //string.Format("Successfully connected to {0}.", selectedNetwork.Ssid)
            }
            else
            {
                //string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus)
            }
        }
Пример #15
0
        public async void DoConnect()
        {
            if (selectedNetwork == null)
            {
                return;
            }

            Views.Busy.SetBusy(true, $"WiFi connecting to  {deviceNetwork.Ssid}");

            var connectionResult = await firstAdapter.ConnectAsync(deviceNetwork, WiFiReconnectionKind.Automatic);

            if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                try
                {
                    HttpClient httpClient = new HttpClient();
                    var        stringRes  = await httpClient.GetStringAsync("http://192.168.4.1/");

                    var details = JsonConvert.DeserializeObject <DeviceDetails>(stringRes);


                    selectedDevice.DeviceDetails.Status      = DeviceStatus.Missing;
                    selectedDevice.DeviceDetails.ConnectedTo = "None";

                    selectedDevice.DeviceDetails.ChipId          = details.ChipId;
                    selectedDevice.DeviceDetails.FirmwareName    = details.FirmwareName;
                    selectedDevice.DeviceDetails.FirmwareVersion = details.FirmwareVersion;

                    selectedDevice.DeviceDetails.ModuleType = details.ModuleType;

                    WifiConfig wifi = new WifiConfig()
                    {
                        ssid     = ((WiFiAvailableNetwork)selectedNetwork).Ssid,
                        password = password
                    };

                    StringContent sc = new StringContent(JsonConvert.SerializeObject(wifi));

                    await httpClient.PostAsync("http://192.168.4.1/wifisettings", sc);

                    //DataService db = new DataService();
                    //db.InsertNewDevice(newRegisteredDevice);
                }
                catch (Exception)
                {
                }
            }
            else
            {
            }
            Views.Busy.SetBusy(false);

            showProvisioningDetails = Visibility.Collapsed;
            showDeviceDetails       = Visibility.Visible;
        }
Пример #16
0
        public async Task <string> ConnectAsync(WiFiAvailableNetwork selectedNetwork, string networkPassword)
        {
            var credentials = new PasswordCredential()
            {
                UserName = "******", Password = networkPassword
            };

            var status = await _adapter.ConnectAsync(selectedNetwork, WiFiReconnectionKind.Automatic, credentials);

            return(status.ConnectionStatus.ToString());
        }
Пример #17
0
        private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (ConnectAutomatically.IsChecked.HasValue && ConnectAutomatically.IsChecked.Value)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }

            if (availableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
            {
                await wifiAdapter.ConnectAsync(availableNetwork, reconnectionKind);
            }
            else
            {
                var credential = new PasswordCredential();
                if (!string.IsNullOrEmpty(securityKey.Password))
                {
                    credential.Password = securityKey.Password;
                }

                await wifiAdapter.ConnectAsync(availableNetwork, reconnectionKind, credential);
            }
        }
Пример #18
0
        /// <summary>
        /// This class initiates the GPIO pin output for relay control
        /// <param name="gpio"> Parameter description for s goes here.</param>
        /// </summary>
        public async void Connack()
        {
            //raw.Text = hoe.ToString();
            //hoe++;
            if (!first)
            {
                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                first = true;
            }
            if (!connacking)
            {
                try
                {
                    connacking = true;
                    try
                    {
                        await firstAdapter.ScanAsync();
                    }
                    catch { }
                    report = firstAdapter.NetworkReport;

                    foreach (var network in report.AvailableNetworks)
                    {
                        if (network.Bssid == "00:1e:2a:0c:6a:9a")
                        {
                            WiFiReconnectionKind reKind     = WiFiReconnectionKind.Automatic;
                            PasswordCredential   credential = new PasswordCredential();
                            credential.Password = "******";
                            WiFiConnectionResult results = await firstAdapter.ConnectAsync(
                                network, reKind, credential);
                        }
                    }
                }
                catch { }
                connacking = false;
            }
        }
Пример #19
0
        async public Task ConnectToTelloWifi()
        {
            await InitializeFirstAdapter();

            WiFiAdapter.Disconnect();
            await ScanForNetworks();

            var report = WiFiAdapter.NetworkReport;

            var telloNetwork = report.AvailableNetworks.First(availableNetwork => availableNetwork.Ssid.Equals(TelloSSID));

            var connectionResult = await WiFiAdapter.ConnectAsync(telloNetwork, WiFiReconnectionKind.Manual);

            if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                Debug.WriteLine("Connected to Tello network with success");
            }
            else
            {
                Debug.WriteLine("Failed to connect to Tello network : " + connectionResult.ConnectionStatus.ToString());
            }
        }
Пример #20
0
        /// <summary>
        /// Connect to Wireless Network
        /// </summary>
        /// <param name="_network">Wireless Network Name (SSID)</param>
        /// <param name="_password">Password Creditentials</param>
        /// <returns></returns>
        public async Task Connect(string _network, string _password, string id)
        {
            try
            {
                // Get WiFi Adapter from ID
                this._wifi = await WiFiAdapter.FromIdAsync(id);

                // Scan for Wireless Networks
                await this._wifi.ScanAsync();

                // Select Wireless Network
                List <WiFiAvailableNetwork> _list = new List <WiFiAvailableNetwork>();
                _list.AddRange(_wifi.NetworkReport.AvailableNetworks.ToList());
                _nets = _list.FirstOrDefault(x => x.Ssid.Equals(_network));

                // Enter Password Creditentials
                var credential = new PasswordCredential()
                {
                    Password = _password
                };

                // Wireless Connection Result
                _conn = await _wifi.ConnectAsync(_nets, WiFiReconnectionKind.Automatic, credential);

                // Connected Status
                if (_conn.ConnectionStatus != WiFiConnectionStatus.Success)
                {
                    _connected = false;
                }
                else
                {
                    _connected = true;
                }
            }
            catch
            {
                _connected = false;
            }
        }
Пример #21
0
        public async Task ConnectToWifi()
        {
            try
            {
                if ((adapterStatus = await GetWifiAdaptors()) == AdaptersStatus.hasAdapters)
                {
                    await wifiAdapter.ScanAsync();

                    var network    = wifiAdapter.NetworkReport.AvailableNetworks.Where(y => y.Ssid == SSID).FirstOrDefault();
                    var credential = new PasswordCredential
                    {
                        Password = this.Password
                    };
                    WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;
                    await wifiAdapter.ConnectAsync(network, reconnectionKind, credential);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ConnectToWifi() Exception: " + ex.Message);
                throw;
            }
        }
        private async void DoWifiConnect(object sender, RoutedEventArgs e, bool pushButtonConnect)
        {
            var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;

            if (selectedNetwork == null || firstAdapter == null)
            {
                rootPage.NotifyUser("Network not selected", NotifyType.ErrorMessage);
                return;
            }
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (selectedNetwork.ConnectAutomatically)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }

            Task <WiFiConnectionResult> didConnect = null;
            WiFiConnectionResult        result     = null;

            if (pushButtonConnect)
            {
                if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5, 0))
                {
                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, null, String.Empty, WiFiConnectionMethod.WpsPushButton).AsTask <WiFiConnectionResult>();
                }
            }
            else if (selectedNetwork.IsEapAvailable)
            {
                if (selectedNetwork.UsePassword)
                {
                    var credential = new PasswordCredential();
                    if (!String.IsNullOrEmpty(selectedNetwork.Domain))
                    {
                        credential.Resource = selectedNetwork.Domain;
                    }
                    credential.UserName = selectedNetwork.UserName ?? "";
                    credential.Password = selectedNetwork.Password ?? "";

                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential).AsTask <WiFiConnectionResult>();
                }
                else
                {
                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind).AsTask <WiFiConnectionResult>();
                }
            }
            else if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
                     selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind).AsTask <WiFiConnectionResult>();
            }
            else
            {
                // Only the password potion of the credential need to be supplied
                if (String.IsNullOrEmpty(selectedNetwork.Password))
                {
                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind).AsTask <WiFiConnectionResult>();
                }
                else
                {
                    var credential = new PasswordCredential();
                    credential.Password = selectedNetwork.Password ?? "";

                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential).AsTask <WiFiConnectionResult>();
                }
            }

            SwitchToItemState(selectedNetwork, WifiConnectingState, false);

            if (didConnect != null)
            {
                result = await didConnect;
            }

            if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);

                // refresh the webpage
                webViewGrid.Visibility          = Visibility.Visible;
                toggleBrowserButton.Content     = "Hide Browser Control";
                refreshBrowserButton.Visibility = Visibility.Visible;

                ResultCollection.Remove(selectedNetwork);
                ResultCollection.Insert(0, selectedNetwork);
                ResultsListView.SelectedItem = ResultsListView.Items[0];
                ResultsListView.ScrollIntoView(ResultsListView.SelectedItem);

                SwitchToItemState(selectedNetwork, WifiConnectedState, false);
            }
            else
            {
                rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
                SwitchToItemState(selectedNetwork, WifiConnectState, false);
            }

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var network in ResultCollection)
            {
                network.UpdateConnectivityLevel();
            }
        }
Пример #23
0
        private async void DoWifiConnect(object sender, RoutedEventArgs e, bool pushButtonConnect)
        {
            var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;

            if (selectedNetwork == null || firstAdapter == null)
            {
                rootPage.NotifyUser("Network not selected", NotifyType.ErrorMessage);
                return;
            }


            var ssid = selectedNetwork.AvailableNetwork.Ssid;

            if (string.IsNullOrEmpty(ssid))
            {
                if (string.IsNullOrEmpty(selectedNetwork.HiddenSsid))
                {
                    rootPage.NotifyUser("Ssid required for connection to hidden network.", NotifyType.ErrorMessage);
                    return;
                }
                else
                {
                    ssid = selectedNetwork.HiddenSsid;
                }
            }

            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (selectedNetwork.ConnectAutomatically)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }

            Task <WiFiConnectionResult> didConnect = null;
            WiFiConnectionResult        result     = null;

            if (pushButtonConnect)
            {
                if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5, 0))
                {
                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, null, string.Empty, WiFiConnectionMethod.WpsPushButton).AsTask();
                }
            }
            else
            {
                PasswordCredential credential = new PasswordCredential();
                if (selectedNetwork.IsEapAvailable && selectedNetwork.UsePassword)
                {
                    if (!String.IsNullOrEmpty(selectedNetwork.Domain))
                    {
                        credential.Resource = selectedNetwork.Domain;
                    }

                    credential.UserName = selectedNetwork.UserName ?? "";
                    credential.Password = selectedNetwork.Password ?? "";
                }
                else if (!String.IsNullOrEmpty(selectedNetwork.Password))
                {
                    credential.Password = selectedNetwork.Password;
                }

                if (selectedNetwork.IsHiddenNetwork)
                {
                    // Hidden networks require the SSID to be supplied
                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential, ssid).AsTask();
                }
                else
                {
                    didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential).AsTask();
                }
            }

            SwitchToItemState(selectedNetwork, WifiConnectingState, false);

            if (didConnect != null)
            {
                result = await didConnect;
            }

            if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);

                // refresh the webpage
                webViewGrid.Visibility          = Visibility.Visible;
                toggleBrowserButton.Content     = "Hide Browser Control";
                refreshBrowserButton.Visibility = Visibility.Visible;

                ResultCollection.Remove(selectedNetwork);
                ResultCollection.Insert(0, selectedNetwork);
                ResultsListView.SelectedItem = ResultsListView.Items[0];
                ResultsListView.ScrollIntoView(ResultsListView.SelectedItem);

                SwitchToItemState(selectedNetwork, WifiConnectedState, false);
            }
            else
            {
                // Entering the wrong password may cause connection attempts to timeout
                // Disconnecting the adapter will return it to a non-busy state
                if (result.ConnectionStatus == WiFiConnectionStatus.Timeout)
                {
                    firstAdapter.Disconnect();
                }
                rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, (result != null ? result.ConnectionStatus : WiFiConnectionStatus.UnspecifiedFailure)), NotifyType.ErrorMessage);
                SwitchToItemState(selectedNetwork, WifiConnectState, false);
            }

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var network in ResultCollection)
            {
                var task = network.UpdateConnectivityLevelAsync();
            }
        }
Пример #24
0
        private void Send(object sender, object e)
#endif
        {
            timeTick = SEND_INTERVAL;
            if (client.Messages() == 0) return;
#if _CREATE_WIFI_CONNECTION
            SetStatus("RequestAccessAsync");

            var access = await WiFiAdapter.RequestAccessAsync();
            if (access == WiFiAccessStatus.Allowed)
            {
                var wifiDevices = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
                if (wifiDevices?.Count > 0)
                {
                    wifi = await WiFiAdapter.FromIdAsync(wifiDevices[0].Id);

                    await WriteStatus(true);
                    await client.SaveQueueAsync();

                    SetStatus("ScanAsync");
                    IAsyncAction a = wifi?.ScanAsync();
                    await a;

                    await WriteStatus(false);

                    if (a.Status == AsyncStatus.Completed && wifi?.NetworkReport?.AvailableNetworks?.Count > 0)
                    {
                        foreach (var network in wifi.NetworkReport.AvailableNetworks)
                        {
                            bool found = false;
                            uint wlan = 0;
                            for (uint i = 0; i < Access.Networks; i++)
                            {
                                if (network.Ssid == Access.SSID(i))
                                {
                                    wlan = i;   
                                    found = true;
                                    break;
                                }
                            }
                            if (found)
                            {
                                var passwordCredential = new PasswordCredential();
                                passwordCredential.Password = Access.WIFI_Password(wlan);

                                SetStatus("ConnectAsync");
                                var result = await wifi.ConnectAsync(network, WiFiReconnectionKind.Automatic, passwordCredential);

                                if (result.ConnectionStatus.Equals(WiFiConnectionStatus.Success))
                                {
#endif
                                    try
                                    {
                                        AsyncActionCompletedHandler handler = (IAsyncAction asyncInfo, AsyncStatus asyncStatus) =>
                                        {
                                            var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                            {
                                                switch (asyncStatus)
                                                {
                                                    case AsyncStatus.Completed:
                                                        errorText.Text = client.Sent() + " Messages sent";
                                                        SetStatus("OK");
                                                        networkError = 0;
                                                        break;
                                                    case AsyncStatus.Canceled:
                                                    case AsyncStatus.Error:
                                                        errorText.Text = "Send: " + asyncInfo.ErrorCode;
                                                        SetStatus("Error");
                                                        break;
                                                }
                                                if (rebootPending) reboot = true;
#if _CREATE_WIFI_CONNECTION
                                                wifi.Disconnect();
                                                wifi = null;
#endif
                                            });
                                        };            
                                        SetStatus("Sending messages");
                                        client.SendMessagesAsync(handler);       
                                    }
                                    catch (Exception ex)
                                    {
                                        Error("Send: " + ex.ToString() + " " + ex.Message + " " + ex.HResult);
                                    }
#if _CREATE_WIFI_CONNECTION
                                }
                                else NoConnection(false, result.ConnectionStatus.ToString());
                                return;
                            }
                        }
                        NoConnection(rebootPending  || (++networkError == 5), Access.Ssid + " not found.");
                    }
                    else NoConnection(rebootPending || (++networkError == 5), "No wifi networks found " + a.Status.ToString());
                }   
                else NoConnection(true, "No wifi adapter found");                    
            }
            else NoConnection(true, "Wifi access denied" + access.ToString());
#endif
        }
Пример #25
0
        private async Task <WiFiConnectionStatus> ConnectToNetwork(WiFiAdapter adapter, WiFiAvailableNetwork network)
        {
            lock (_stateLock)
            {
                _state = OnboardingState.ConfiguredValidating;
            }

            string resultPassword = "";
            WiFiConnectionResult connectionResult;

            // For all open networks (when no PSK was provided) connect without a password
            // Note, that in test, we have seen some WEP networks identify themselves as Open even though
            // they required a PSK, so use the PSK as a determining factor
            if ((network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211) &&
                string.IsNullOrEmpty(_personalApPassword))
            {
                connectionResult = await adapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);
            }
            // Otherwise for all WEP/WPA/WPA2 networks convert the PSK back from a hex-ized format back to a passphrase, if necessary,
            // and onboard this device to the requested network.
            else
            {
                PasswordCredential pwd = new PasswordCredential();
                resultPassword   = ConvertHexToPassPhrase(network.SecuritySettings.NetworkAuthenticationType, _personalApPassword);
                pwd.Password     = resultPassword;
                connectionResult = await adapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, pwd);
            }

            lock (_stateLock)
            {
                if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
                {
                    _error        = OnboardingError.Validated;
                    _errorMessage = null;
                    _state        = OnboardingState.ConfiguredValidated;
                }
                else
                {
                    _state        = OnboardingState.ConfiguredError;
                    _errorMessage = connectionResult.ConnectionStatus.ToString();

                    switch (connectionResult.ConnectionStatus)
                    {
                    case WiFiConnectionStatus.AccessRevoked:
                    case WiFiConnectionStatus.InvalidCredential:
                    {
                        _error = OnboardingError.Unauthorized;
                        break;
                    }

                    case WiFiConnectionStatus.UnsupportedAuthenticationProtocol:
                    {
                        _error = OnboardingError.UnsupportedProtocol;
                        break;
                    }

                    case WiFiConnectionStatus.NetworkNotAvailable:
                    case WiFiConnectionStatus.Timeout:
                    case WiFiConnectionStatus.UnspecifiedFailure:
                    default:
                    {
                        _error = OnboardingError.ErrorMessage;
                        break;
                    }
                    }
                }
            }
#if DEBUG
            var folder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file   = await folder.CreateFileAsync("ConnectionResult.Txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            string myout = "ConnectionResult= " + connectionResult.ConnectionStatus.ToString() + "\r\n";
            myout += "Type=" + network.SecuritySettings.NetworkAuthenticationType.ToString() + "\r\n";
            myout += "InputPassword= "******"\r\n";
            myout += "ResultPassword= "******"\r\n";
            await Windows.Storage.FileIO.WriteTextAsync(file, myout);
#endif
            return(connectionResult.ConnectionStatus);
        }
Пример #26
0
        public async Task ConnectAsync()
        {
            if (SelectedWiFiNetwork == null)
            {
                OnError?.Invoke(this, new ArgumentException("Network not selected"));
                return;
            }
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (SelectedWiFiNetwork.ConnectAutomatically)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }
            Task <WiFiConnectionResult> didConnect = null;
            WiFiConnectionResult        result     = null;

            if (SelectedWiFiNetwork.IsEapAvailable)
            {
                if (SelectedWiFiNetwork.UsePassword)
                {
                    var credential = new PasswordCredential();
                    if (!String.IsNullOrEmpty(SelectedWiFiNetwork.Domain))
                    {
                        credential.Resource = SelectedWiFiNetwork.Domain;
                    }
                    credential.UserName = SelectedWiFiNetwork.UserName ?? "";
                    credential.Password = SelectedWiFiNetwork.Password ?? "";

                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind, credential).AsTask();
                }
                else
                {
                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask();
                }
            }
            else if (SelectedWiFiNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
                     SelectedWiFiNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask();
            }
            else
            {
                // Only the password potion of the credential need to be supplied
                if (String.IsNullOrEmpty(SelectedWiFiNetwork.Password))
                {
                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask();
                }
                else
                {
                    var credential = new PasswordCredential();
                    credential.Password = SelectedWiFiNetwork.Password ?? "";

                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind, credential).AsTask();
                }
            }

            OnConnecting?.Invoke(this, EventArgs.Empty);

            if (didConnect != null)
            {
                result = await didConnect;
            }

            if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                WiFiNetworks.Remove(SelectedWiFiNetwork);
                WiFiNetworks.Insert(0, SelectedWiFiNetwork);
                OnSelect?.Invoke(this, EventArgs.Empty);
                OnConnected?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                OnError?.Invoke(this, new Exception("Could not connect to network"));
                OnDisconnected?.Invoke(this, EventArgs.Empty);
            }

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var network in WiFiNetworks)
            {
                await network.UpdateConnectivityLevel();
            }
        }
Пример #27
0
        private async void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            string Pass = WiFiList[WiFiControl.SelectedIndex].Password;

            if (Pass != "" && Pass.Length >= 8)
            {
                WiFiList[WiFiControl.SelectedIndex].HideMessage();
                (WiFiControl.ContainerFromItem(WiFiControl.SelectedItem) as ListViewItem).ContentTemplate = WiFiConnectingState;

                WiFiInfo           Info       = WiFiList[WiFiControl.SelectedIndex];
                PasswordCredential Credential = new PasswordCredential
                {
                    Password = Info.Password
                };

                var ConnectResult = await WiFi.ConnectAsync(Info.GetWiFiAvailableNetwork(), Info.AutoConnect?WiFiReconnectionKind.Automatic : WiFiReconnectionKind.Manual, Credential);

                if (ConnectResult.ConnectionStatus == WiFiConnectionStatus.Success)
                {
                    foreach (var WiFiInfo in from WiFiInfo in WiFiList
                             where WiFiInfo.IsConnected == true
                             select WiFiInfo)
                    {
                        WiFiInfo.ChangeConnectionStateAsync(false);
                    }

                    Info.HideMessage();
                    Info.ChangeConnectionStateAsync(true, true);

                    (WiFiControl.ContainerFromItem(WiFiControl.SelectedItem) as ListViewItem).ContentTemplate = WiFiConnectedState;

                    bool IsExist = false;

                    foreach (var WiFiInfo in from WiFiInfo in StoragedWiFiInfoCollection
                             where WiFiInfo.SSID == Info.Name
                             select WiFiInfo)
                    {
                        if (WiFiInfo.Password != Info.Password)
                        {
                            await SQLite.GetInstance().UpdateWiFiDataAsync(Info.Name, Info.Password);
                        }
                        else if (WiFiInfo.Password == Info.Password)
                        {
                            IsExist = true;
                        }

                        if (WiFiInfo.AutoConnect != Info.AutoConnect)
                        {
                            await SQLite.GetInstance().UpdateWiFiDataAsync(Info.Name, Info.AutoConnect);
                        }

                        break;
                    }

                    if (!IsExist)
                    {
                        IsExist = false;
                        StoragedWiFiInfoCollection.Add(new WiFiInDataBase(Info.Name, Info.Password, Info.AutoConnect ? "True" : "False"));
                        await SQLite.GetInstance().SetWiFiDataAsync(Info.Name, Info.Password, Info.AutoConnect);
                    }
                }
                else
                {
                    WiFi.Disconnect();
                    (WiFiControl.ContainerFromItem(WiFiControl.SelectedItem) as ListViewItem).ContentTemplate = WiFiErrorState;
                    Info.ShowMessage("连接失败");
                }

                //连接完成后重新开始搜索
                WiFiScanTimer.Tick += WiFiScanTimer_Tick;
                WiFiScanTimer.Start();
            }
            else
            {
                WiFiList[WiFiControl.SelectedIndex].ShowMessage("密码必须非空且大于8位");
            }
        }
        private async void Connect_Click(object sender, RoutedEventArgs e)
        {
            var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;

            if (selectedNetwork == null || adapter == null)
            {
                ConnectionStatusText.Text = "No network selected";
                return;
            }
            WiFiReconnectionKind reconnectionKind = IsAutomaticReconnection.IsChecked.GetValueOrDefault() ? WiFiReconnectionKind.Automatic : WiFiReconnectionKind.Manual;

            WiFiConnectionResult result;

            if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
                selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                result = await adapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
            }
            else
            {
                // Only the password potion of the credential need to be supplied
                var credential = new PasswordCredential();
                try
                {
                    credential.Password = NetworkKey.Password;
                } catch (ArgumentException)
                {
                    ConnectionStatusText.Text = "Password is invalid.";
                    return;
                }

                result = await adapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
            }

            var requiresWebview = false;

            if (result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                var connectedProfile = await adapter.NetworkAdapter.GetConnectedProfileAsync();

                var level = connectedProfile.GetNetworkConnectivityLevel();
                if (level == NetworkConnectivityLevel.ConstrainedInternetAccess || level == NetworkConnectivityLevel.LocalAccess)
                {
                    ConnectionStatusText.Text = string.Format("Limited access on {0}.", selectedNetwork.Ssid);
                    requiresWebview           = true;
                }
                else
                {
                    ConnectionStatusText.Text = string.Format("Successfully connected to {0}.", selectedNetwork.Ssid);
                }
            }
            else
            {
                ConnectionStatusText.Text = string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus);
            }
            webView.Visibility = requiresWebview ? Visibility.Visible : Visibility.Collapsed;

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var network in networks)
            {
                network.UpdateConnectivityLevel();
            }
        }
Пример #29
0
        async void device_AvailableNetworksChanged(WiFiAdapter sender, object args)
        {
            if (isEnter)
            {
                return;
            }
            isEnter = true;

            if (hasAutoPassResult)
            {
                return;
            }
            WiFiNetworkReport networkReport = sender.NetworkReport;
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                txtStatus.Visibility = Visibility.Collapsed;

                listWiFi.Items.Clear();

                int remainingCount = App.WifiName.Count;
                //uint sigstrengthPassCnt = 0;

                //look for the requested network
                foreach (WiFiAvailableNetwork network in networkReport.AvailableNetworks)
                {
                    // Remove duplicated SSID
                    String strSsid = network.Ssid;
                    if (!String.IsNullOrEmpty(strSsid))
                    {
                        foreach (Customer item in listWiFi.Items)
                        {
                            if (item.Ssid.ToUpper() == network.Ssid.ToUpper())
                            {
                                strSsid = String.Empty;
                                break;
                            }
                        }
                    }

                    if (strSsid == string.Empty)
                    {
                        continue;
                    }

                    // Try to connect network if <ConnectionName> setting exists in SFTConfig.xml
                    if (!isConnection && (network.Ssid.ToUpper() == App.WifiNameConnection.ToUpper()))
                    {
                        var connectioResult = await sender.ConnectAsync(network, WiFiReconnectionKind.Automatic);

                        if (connectioResult.ConnectionStatus == WiFiConnectionStatus.Success)
                        {
                            isConnection = true;
                            App.LogComment(network.Ssid + " : Connection OK!");
                            sender.Disconnect();
                        }
                    }

                    // Set signal strength image
                    string image = String.Format(CultureInfo.CurrentCulture, "/Assets/Wifi{0}",
                                                 (Application.Current.RequestedTheme == ApplicationTheme.Dark) ? "Dark" : "Light");

                    int signalStrength = network.SignalBars;
                    if (signalStrength > 4)
                    {
                        signalStrength = 4;
                    }
                    if (signalStrength < 1)
                    {
                        signalStrength = 1;
                    }
                    signalStrength--;
                    image += signalStrength.ToString(CultureInfo.CurrentCulture) + ".png";

                    // Set Authentication Type
                    String authType = App.LoadString("Secure");
                    switch (network.SecuritySettings.NetworkAuthenticationType)
                    {
                    case NetworkAuthenticationType.Open80211:
                        authType = App.LoadString("Open");
                        break;

                    case NetworkAuthenticationType.None:
                        authType = App.LoadString("Open");
                        break;

                    case NetworkAuthenticationType.Unknown:
                        authType = App.LoadString("Open");
                        break;
                    }

                    // convert from rssi to quality: https://msdn.microsoft.com/en-us/library/windows/desktop/ms706828(v=vs.85).aspx
                    int quality = (Math.Min(Math.Max((int)network.NetworkRssiInDecibelMilliwatts, -100), -50) + 100) * 2;
                    // mark 2.4G and 5G APs in the list
                    string details = authType + ", " + App.LoadString("Signal") + " " + quality + "%" + ", " + PhyTypes[(int)network.PhyKind];
                    // Add a scanned network to list box
                    listWiFi.Items.Add(new Customer(network.Ssid, details, image));
                    // App.LogComment("Available network: " + network.Ssid + ", " + authType + ", Bars=" + network.SignalBars.ToString(CultureInfo.CurrentCulture));
                    App.LogComment("Available network: " + network.Ssid + ", " + details + ", Bars=" + network.SignalBars.ToString(CultureInfo.CurrentCulture));

                    // Auto pass: check how many AP passed signal strength threshold value
                    //if (curConfig.SigStrength_ThresholdCount > 0)
                    //{
                    //    if (network.SignalBars >= curConfig.SigStrength_ThresholdSigBar)
                    //        sigstrengthPassCnt++;
                    //}

                    // Auto pass if WiFi test meet auto pass critera: found all WiFi predefined name list
                    if (remainingCount > 0)
                    {
                        bool isAboveThreshold   = false;
                        int qualityInPercentage = 0;
                        if (curConfig.SigStrength_ThresholdSigQuality > 0)
                        {
                            qualityInPercentage = (Math.Min(Math.Max((int)network.NetworkRssiInDecibelMilliwatts, -100), -50) + 100) * 2;
                            if (App.WifiName.Contains(network.Ssid) && qualityInPercentage >= curConfig.SigStrength_ThresholdSigQuality)
                            {
                                isAboveThreshold = true;
                            }
                        }
                        else if (curConfig.SigStrength_ThresholdSigBar > 0)
                        {
                            if (App.WifiName.Contains(network.Ssid) && network.SignalBars >= curConfig.SigStrength_ThresholdSigBar)
                            {
                                remainingCount--;
                            }
                        }
                        if (isAboveThreshold)
                        {
                            remainingCount--;
                            App.LogComment(network.Ssid + " Found; Rssi=" + network.NetworkRssiInDecibelMilliwatts + "dBm(%" + qualityInPercentage + "), SigBar=" + network.SignalBars + "; PhyType=" + network.PhyKind);
                        }
                    }
                }

                // Enter Auto-Pass/Auto-Faill condition if one of <AvailableName>, <ConnectionName>, or <Threshold> setting exists in SFTConfig.xml
                if (App.WifiName.Count > 0 || !String.IsNullOrEmpty(App.WifiNameConnection)
                    // || curConfig.SigStrength_ThresholdCount > 0
                    )
                {
                    hasAutoPassResult = true;
                    // App.LogComment("Require " + curConfig.SigStrength_ThresholdCount + " AP that has SignalBar >= " + curConfig.SigStrength_ThresholdSigBar + ": Found " + sigstrengthPassCnt);
                    if (remainingCount == 0 && isConnection) // && sigstrengthPassCnt >= curConfig.SigStrength_ThresholdCount)
                    {
                        App.ResultControl("btnPass", this.Name);
                    }
                    else
                    {
                        App.ResultControl("btnFail", this.Name);
                    }
                }

                isEnter = false;
            });
        }
Пример #30
0
        private async void ConnectToNetwork(WiFiAdapter adapter, WiFiAvailableNetwork network)
        {
            lock (_stateLock)
            {
                _state = OnboardingState.ConfiguredValidating;
            }

            WiFiConnectionResult connectionResult;
            if (network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
            {
                connectionResult = await adapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);
            }
            else
            {
                connectionResult = await adapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, new PasswordCredential { Password = _personalApPassword });
            }

            lock (_stateLock)
            {
                if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
                {
                    _error = OnboardingError.Validated;
                    _errorMessage = null;
                    _state = OnboardingState.ConfiguredValidated;
                }
                else
                {
                    _state = OnboardingState.ConfiguredError;
                    _errorMessage = connectionResult.ConnectionStatus.ToString();

                    switch (connectionResult.ConnectionStatus)
                    {
                        case WiFiConnectionStatus.AccessRevoked:
                        case WiFiConnectionStatus.InvalidCredential:
                            {
                                _error = OnboardingError.Unauthorized;
                                break;
                            }
                        case WiFiConnectionStatus.UnsupportedAuthenticationProtocol:
                            {
                                _error = OnboardingError.UnsupportedProtocol;
                                break;
                            }
                        case WiFiConnectionStatus.NetworkNotAvailable:
                        case WiFiConnectionStatus.Timeout:
                        case WiFiConnectionStatus.UnspecifiedFailure:
                        default:
                            {
                                _error = OnboardingError.ErrorMessage;
                                break;
                            }
                    }
                }
            }
        }