コード例 #1
0
ファイル: Program.cs プロジェクト: hxdhttk/WifiReconnector
        private static async Task ReconnectAsync()
        {
            var profile   = NetworkInformation.GetInternetConnectionProfile();
            var reconnect = profile == null || profile.GetNetworkConnectivityLevel() < NetworkConnectivityLevel.InternetAccess;

            if (reconnect)
            {
                Logger.Log("Lost connection, start to reconnect...");

                IReadOnlyList <WiFiAdapter> adapters = null;
                while (adapters == null || adapters.Count == 0)
                {
                    adapters = await WiFiAdapter.FindAllAdaptersAsync();

                    await Task.Yield();
                }

                var adapter = adapters.First();
                var report  = adapter.NetworkReport;
                foreach (var target in report.AvailableNetworks.OrderByDescending(n => n.NetworkRssiInDecibelMilliwatts))
                {
                    if (target.Ssid == _config.WifiSsid)
                    {
                        Logger.Log($"Reconnect to {target.Ssid}...");

                        var cred = new PasswordCredential();
                        cred.Password = _config.WifiPassword;

                        var result = await adapter.ConnectAsync(target, WiFiReconnectionKind.Automatic, cred);

                        if (result.ConnectionStatus == WiFiConnectionStatus.Success)
                        {
                            Logger.Log("Reconnection succeeded.");
                        }
                        else
                        {
                            Logger.Log($"Reconnection failed with error {result.ConnectionStatus}.");
                        }
                        break;
                    }
                }
            }
        }
コード例 #2
0
        private async void SetWifiDevice()
        {
            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                throw new Exception("WiFiAccessStatus not allowed");
            }
            else
            {
                var WifiDeviceScan = await WiFiAdapter.FindAllAdaptersAsync();

                if (WifiDeviceScan.Count >= 1)
                {
                    WifiDevice   = WifiDeviceScan[0];
                    ActiveDevice = true;
                }
            }
        }
コード例 #3
0
        public async Task <Dictionary <string, WiFiAdapter> > GetWiFiAdaptersAsync()
        {
            IReadOnlyList <WiFiAdapter> adapters = await WiFiAdapter.FindAllAdaptersAsync();

            if (adapters.Count > 0)
            {
                foreach (WiFiAdapter adapter in adapters)
                {
                    if (!WiFiAdapters.ContainsKey(adapter.NetworkAdapter.NetworkAdapterId.ToString()))
                    {
                        //https://msdn.microsoft.com/en-us/library/windows.networking.connectivity.networkadapter.ianainterfacetype.aspx
                        if (adapter.NetworkAdapter.IanaInterfaceType == 71)
                        {
                            WiFiAdapters.Add(adapter.NetworkAdapter.NetworkAdapterId.ToString(), adapter);
                        }
                    }
                }
            }
            return(WiFiAdapters);
        }
コード例 #4
0
        public static void RegisterService()
        {
            var services = new ServiceCollection();

            services.AddDbContext <DeskberryContext>(options => options.UseSqlite(@"Data Source=deskberry.db"));

            //! It's experimental
            try
            {
                services.AddSingleton(typeof(WiFiAdapter), WiFiAdapter.FindAllAdaptersAsync().GetAwaiter().GetResult()[0]);
            }
            catch (Exception)
            {
            }

            services.AddTransient <MainPageViewModel>();
            services.AddScoped <DesktopPageViewModel>();
            services.AddScoped <NotesViewModel>();
            services.AddScoped <AddNotePageViewModel>();
            services.AddScoped <AllNotesPageViewModel>();
            services.AddScoped <CalculatorViewModel>();
            services.AddScoped <BrowserViewModel>();
            services.AddScoped <SettingsViewModel>();
            services.AddScoped <PasswordSettingsPageViewModel>();
            services.AddScoped <PersonalizationSettingsPageViewModel>();
            services.AddScoped <BrowserSettingsPageViewModel>();
            services.AddScoped <NetworkSettingsPageViewModel>();
            services.AddScoped <AccountManagerPageViewModel>();

            services.AddScoped <IAccountService, AccountService>();
            services.AddScoped <IAvatarService, AvatarService>();
            services.AddSingleton <INavigationService, NavigationService>();
            services.AddSingleton <INoteNavigationService, NoteNavigationService>();
            services.AddSingleton <ISettingNavigationService, SettingNavigationService>();
            services.AddScoped <INoteService, NoteService>();
            services.AddScoped <IFavoriteService, FavoriteService>();
            services.AddScoped <IHomePageService, HomePageService>();
            services.AddScoped <IWiFiService, WiFiService>();

            Container = services.BuildServiceProvider();
        }
コード例 #5
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.Parameter is TextBlock headerTextBlock)
            {
                headerTextBlock.Text = "Ustawienia WiFi";
            }

            if (GetDeviceType() == DeviceType.IoT)
            {
                var access = await WiFiAdapter.RequestAccessAsync();

                if (access != WiFiAccessStatus.Allowed)
                {
                    WiFiProblemNotification.Show("Dostęp wzbroniony!", 5000);
                }
                else
                {
                    var result = await WiFiAdapter.FindAllAdaptersAsync();

                    if (result.Count >= 1)
                    {
                        wiFiAdapter_ = result[0];

                        RefreshWiFi();
                    }
                    else
                    {
                        WiFiProblemNotification.Show("Nie wykryto żadnego adaptera WiFi!", 5000);
                    }
                }
            }
            else
            {
                WiFiProblemNotification.Show("Błąd! Twoje urządzenie nie daje możliwości manipulacji WiFi", 5000);
                await Task.Delay(7000);

                WiFiProblemNotification.Show(AnalyticsInfo.VersionInfo.DeviceFamily);
            }
        }
コード例 #6
0
        public async Task <IEnumerable <AccessPoint> > FindAccessPoints()
        {
            List <AccessPoint> availableAccessPoints = new List <AccessPoint>();

            // Add distinct AP Ssids in sorted order
            var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

            wifiAdapterList.SelectMany(adapter => adapter.NetworkReport.AvailableNetworks).
            Select(network => network.Ssid).
            Distinct().
            OrderBy(ssid => ssid).ToList().
            ForEach(ssid => {
                var ap = new AccessPoint()
                {
                    Ssid = ssid
                };
                availableAccessPoints.Add(ap);
            });

            return(availableAccessPoints);
        }
コード例 #7
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);
                }
            }
            await WiFiAdapter.FindAllAdaptersAsync();

            while (true)
            {
                await wifiAdapter.ScanAsync();

                await Task.Delay(5000);

                List <string> ls         = new List <string>();
                List <string> sortedList = new List <string>();
                foreach (var network in wifiAdapter.NetworkReport.AvailableNetworks)
                {
                    var _dist = Math.Pow(10, 0.05 * (-20 * Math.Log10(network.ChannelCenterFrequencyInKilohertz / 1000) + 27.55 + Math.Abs(network.NetworkRssiInDecibelMilliwatts)));
                    ls.Add(Math.Round(_dist, 1) + "m " + " Name : " + network.Ssid + " , dB signal RSSID : " + network.NetworkRssiInDecibelMilliwatts);
                }


                sortedList = ls.OrderBy(s => double.Parse(s.Substring(0, s.IndexOf('m')))).ToList();

                WiFiList.ItemsSource = sortedList;

                //connectpanel.Visibility = Visibility.Collapsed;
            }
        }
コード例 #8
0
        public async Task <ResultCommandAvailableNetworks> GetAvailableNetworkListHandler()
        {
            try
            {
                var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                var wifiList = from adapter in wifiAdapterList
                               from network in adapter.NetworkReport.AvailableNetworks
                               select network.Ssid;
                var networks = wifiList.OrderBy(x => x).Distinct();

                return(new ResultCommandAvailableNetworks()
                {
                    Networks = networks, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAvailableNetworkListHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandAvailableNetworks>($"Error GetAvailableNetworkListHandler: {e.Message}."));
            }
        }
コード例 #9
0
    private async void Scan()
    {
        if (IsReady)
        {
            IsReady = false;
            Signal signal = new Signal("", "", 1);
            var    result = await WiFiAdapter.FindAllAdaptersAsync();

            if (result.Count >= 1)
            {
                var firstAdapter = result[0];
                await firstAdapter.ScanAsync();

                if (!string.IsNullOrEmpty(Ssid))
                {
                    signal = GetNetworkSignal(firstAdapter.NetworkReport, Ssid);
                }
            }
            IsReady = true;
            Signal  = signal;
        }
    }
コード例 #10
0
ファイル: WiFi.cs プロジェクト: zhouzu/NETworkManager
        public static async Task <List <WiFiAdapterInfo> > GetAdapterAsync()
        {
            List <WiFiAdapterInfo>      wifiAdapters      = new List <WiFiAdapterInfo>();
            List <NetworkInterfaceInfo> networkInterfaces = await NetworkInterface.GetNetworkInterfacesAsync();

            foreach (WiFiAdapter wifiAdapter in await WiFiAdapter.FindAllAdaptersAsync())
            {
                foreach (NetworkInterfaceInfo networkInterface in networkInterfaces)
                {
                    if (!wifiAdapter.NetworkAdapter.NetworkAdapterId.ToString().Equals(networkInterface.Id.TrimStart('{').TrimEnd('}'), StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    wifiAdapters.Add(new WiFiAdapterInfo
                    {
                        NetworkInterfaceInfo = networkInterface,
                        WiFiAdapter          = wifiAdapter
                    });
                }
            }

            return(wifiAdapters);
        }
コード例 #11
0
        private async void BScan_Click(object sender, RoutedEventArgs e)
        {
            listBox1.Items.Clear();
            areaNb++;
            Areas.Add(areaNb, "area" + areaNb);
            // 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)
            {
                MesajFin.Text = "acces denied!";
            }
            else
            {
                MesajFin.Text = "acces allowed!";
                if (wiFiAdapters == null)
                {
                    wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();
                }
                adapter = wiFiAdapters.First();

                //ten scans to build the map
                for (int cnt = 0; cnt < 10; cnt++)
                {
                    await adapter.ScanAsync(); //scan

                    report = adapter.NetworkReport;
                    foreach (var network in report.AvailableNetworks)
                    {
                        // listBox1.Items.Add(network.Ssid + " " + network.NetworkRssiInDecibelMilliwatts + "dBm");
                        scanVals.Add(network.Ssid, network.NetworkRssiInDecibelMilliwatts.ToString());
                    }
                }//end of ten scans

                //next take the mean of the values obtained for each network
                //and replace the stored values with only the mean
                //we use an aux list to store the values for each network and to use Average() fct.
                List <int> dbmValues; //aux list
                foreach (String key in scanVals.AllKeys)
                {
                    dbmValues = scanVals.GetValues(key).Select(int.Parse).ToList();
                    scanVals.Set(key, Math.Truncate(dbmValues.Average()).ToString());
                    //  listBox1.Items.Add(key + " " + scanVals[key]);
                }

                AreaWifiMap = NvcToDictionary(scanVals); //convert to dictionary
                scanVals.Clear();

                WifiMap.Add(Areas[areaNb], AreaWifiMap); //add new entry for each scan *a dictionary of dicts
                foreach (KeyValuePair <string, Dictionary <string, object> > kvp in WifiMap)
                {
                    listBox1.Items.Add(kvp.Key + " >>>>> ");
                    foreach (KeyValuePair <string, object> kvp2 in kvp.Value)
                    {
                        listBox1.Items.Add(kvp2.Key + " " + kvp2.Value);
                    }
                }
                listBox1.Items.Add("::::::::::::::::::::::::::::::::::::::::");
                //  MesajFin.Text = String.Format("DSDSdss");
            }
        }
コード例 #12
0
    // returns whether we are successfullly connected or not
    async public Task <bool> ConnectToSenteraWifi()
    {
#if !UNITY_EDITOR && UNITY_WSA
        // request access
        var access = await WiFiAdapter.RequestAccessAsync();

        if (access == WiFiAccessStatus.Allowed)
        {
            printToDebug("Wifi Access allowed");
        }
        else
        {
            printToDebug("Wifi Access not allowed");
        }

        // get adapter so we can connect
        var wifiAdapterResult = await WiFiAdapter.FindAllAdaptersAsync();

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

        if (result.Count >= 1)
        {
            var firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); // get our adapter

            printToDebug("Wifi Adapter found");

            // check if we are already connected
            var connectedProfile = await firstAdapter.NetworkAdapter.GetConnectedProfileAsync();

            if (connectedProfile != null)
            {
                if (connectedProfile.ProfileName.Contains("Sentera"))
                {
                    return(true);
                }
            }

            // if we are here, we are not connected to sentera
            firstAdapter.Disconnect();               // disconnect first so we don't get struck at "connecting to VuNet"
            var report = firstAdapter.NetworkReport; // get a list of available networks
            foreach (var network in report.AvailableNetworks)
            {
                if (network.Ssid.Contains("Sentera"))
                {
                    printToDebug("Sentera found");
                    await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);

                    printToDebug("Sentera connected. Going to freeze for 5 seconds so Sentera can set up its website");
                    await Task.Delay(5000);

                    printToDebug("We are back now");
                    return(true);
                }
            }
        }
        else
        {
            printToDebug("Wifi adapter not found");
        }
#endif
        return(false);
    }
コード例 #13
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
            savePicker.FileTypeChoices.Add("Plain Text", new List <string>()
            {
                ".txt"
            });
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            sb.AppendLine("time;ssid1;strength1;ssid2;strength2;ssid3;strength3;ssid4;strength4;ssid5;strength5");
            WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync();

            DateTimeOffset time = DateTimeOffset.Now;

            sb.AppendLine(time.ToString() + time.Millisecond);
            if (access == WiFiAccessStatus.Allowed)
            {
                DataContext = this;
                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

                //time = DateTimeOffset.Now;
                //sb.AppendLine(time.ToString() + time.Millisecond);
                if (result.Count >= 1)
                {
                    wifiAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                    //time = DateTimeOffset.Now;
                    //sb.AppendLine(time.ToString() + time.Millisecond);
                }
            }
            time = DateTimeOffset.Now;
            //sb.AppendLine(time.ToString() + time.Millisecond);
            var result1 = await WiFiAdapter.FindAllAdaptersAsync();

            sb.AppendLine(result1.GetType().ToString());
            while (true)
            {
                var firstadapter = result1[0];
                await firstadapter.ScanAsync();

                time = DateTimeOffset.Now;

                //await Task.Delay(5000);
                sb.Append("  " + time.Hour + ":" + time.Minute + ":" + time.Second + ":" + time.Millisecond + "   ;   ");

                // List<string> sortedList = new List<string>();
                foreach (var network in firstadapter.NetworkReport.AvailableNetworks)
                {
                    //var _dist = Math.Pow(10, 0.05 * (-20 * Math.Log10(network.ChannelCenterFrequencyInKilohertz / 1000) + 27.55 + Math.Abs(network.NetworkRssiInDecibelMilliwatts)));
                    //ls.Add(Math.Round(_dist, 1) + "m " + " Name : " + network.Ssid + " , dB signal RSSID : " + network.NetworkRssiInDecibelMilliwatts+network.Uptime.ToString(@"\:mm\:ss\:fff"));
                    sb.Append(network.Ssid + "    ;    " + network.NetworkRssiInDecibelMilliwatts + " ;  " + network.Bssid + " ;  " + network.ChannelCenterFrequencyInKilohertz + " ; ");
                }

                sb.AppendLine();
                messageb.Text = sb.ToString();
                //connectpanel.Visibility = Visibility.Collapsed;
                await Windows.Storage.FileIO.WriteTextAsync(file, sb.ToString());

                //sortedList = ls.OrderBy(s => double.Parse(s.Substring(0, s.IndexOf('m')))).ToList();
            }
        }
コード例 #14
0
        private async Task <WifiConnectResult> ConnectWifi(string ssid, string password)
        {
            if (password == null)
            {
                password = "";
            }

            var access = await WiFiAdapter.RequestAccessAsync();

            if (access != WiFiAccessStatus.Allowed)
            {
                return(WifiConnectResult.WifiAccessDenied);
            }
            else
            {
                var allAdapters = await WiFiAdapter.FindAllAdaptersAsync();

                if (allAdapters.Count >= 1)
                {
                    var firstAdapter = allAdapters[0];
                    await firstAdapter.ScanAsync();

                    //0525       var network = firstAdapter.NetworkReport.AvailableNetworks.SingleOrDefault(n => n.Ssid == ssid);//0525
                    try
                    {
                        var network = firstAdapter.NetworkReport.AvailableNetworks.FirstOrDefault(n => n.Ssid == ssid);

                        if (network != null)
                        {
                            WiFiConnectionResult wifiConnectionResult;
                            if (network.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211)
                            {
                                wifiConnectionResult = await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);
                            }
                            else
                            {
                                // Only the password potion of the credential need to be supplied
                                var credential = new Windows.Security.Credentials.PasswordCredential();
                                credential.Password = password;

                                wifiConnectionResult = await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, credential);
                            }
                            //for get ip
                            if (firstAdapter.NetworkAdapter.GetConnectedProfileAsync() != null)
                            {
                                var connectedProfile = await firstAdapter.NetworkAdapter.GetConnectedProfileAsync();

                                //WriteMessageText("\nconnectedProfile:" + connectedProfile.ProfileName + "\n");
                                if (connectedProfile != null && connectedProfile.ProfileName.Equals(savedProfileName))
                                {
                                    foreach (HostName localHostName in NetworkInformation.GetHostNames())
                                    {
                                        if (localHostName.IPInformation != null)
                                        {
                                            if (localHostName.Type == HostNameType.Ipv4)
                                            {
                                                ipget = localHostName.ToString();
                                                break;
                                            }
                                        }
                                    }
                                    // WriteMessageText("\nIP=localHostName.ToString:" + ipget);
                                }//
                                else
                                {
                                    // WriteMessageText("\n !!!!< >" + Not connected to :"+connectedProfile.ProfileName+"\n");
                                }
                            }

                            if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
                            {
                                return(WifiConnectResult.Success);
                            }
                            else
                            {
                                if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.UnspecifiedFailure)
                                {
                                    //return WifiConnectResult.UnspecifiedFailure;
                                    WriteMessageText("\nUnspecified Failure");
                                }
                                else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.AccessRevoked)
                                {
                                    // return WifiConnectResult.AccessRevoked;
                                    WriteMessageText("\nAccess Revoked");
                                }
                                else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.InvalidCredential)
                                {
                                    // return WifiConnectResult.InvalidCredential;
                                    WriteMessageText("\nInvalid Credential");
                                }
                                else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.NetworkNotAvailable)
                                {
                                    //    return WifiConnectResult.NetworkNotAvailable;
                                    WriteMessageText("\nNetwork NotAvailable");
                                }
                                else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.Timeout)
                                {
                                    //return WifiConnectResult.Timeout;
                                    WriteMessageText("\nTimeout");
                                }
                                else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.UnsupportedAuthenticationProtocol)
                                {
                                    //return WifiConnectResult.UnsupportedAuthenticationProtocol; */
                                    WriteMessageText("\nUnsupported Authentication Protocol");
                                }
                                return(WifiConnectResult.CouldNotConnect);
                            }
                        }
                        else
                        {
                            return(WifiConnectResult.SsidNotFound);
                        }
                        //try 0706
                    }
                    catch (Exception ex)
                    {
                        return(WifiConnectResult.SsidNotFound);
                    }
                }
                else
                {
                    return(WifiConnectResult.NoWifiDevice);
                }
            }
        }