Exemplo n.º 1
1
        public async void GetNetworks()
        {
            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

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

                await firstAdapter.ScanAsync();

                deviceNetwork = firstAdapter.NetworkReport.AvailableNetworks.FirstOrDefault(N => N.Ssid == selectedDevice.GivenName);

                var qualifyingWifi = firstAdapter.NetworkReport.AvailableNetworks.Where(N => !N.Ssid.ToLower().StartsWith("ioespt-thing"));

                foreach (var network in qualifyingWifi)
                {
                    networks.Add(network);
                }

                selectedNetwork = networks.FirstOrDefault();
            }
        }
        private async void ScanButton_Click(object sender, RoutedEventArgs e)
        {
            await firstAdapter.ScanAsync();

            ConnectionBar.Visibility = Visibility.Collapsed;
            DisplayNetworkReport(firstAdapter.NetworkReport);
        }
Exemplo n.º 3
0
        public static void Main()
        {
            try
            {
                // Get the first WiFI Adapter
                WiFiAdapter wifi = WiFiAdapter.FindAllAdapters()[0];

                // Set up the AvailableNetworksChanged event to pick up when scan has completed
                wifi.AvailableNetworksChanged += Wifi_AvailableNetworksChanged;

                // Loop forever scanning every 30 seconds
                while (true)
                {
                    Debug.WriteLine("starting WiFi scan");
                    wifi.ScanAsync();

                    Thread.Sleep(30000);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("message:" + ex.Message);
                Debug.WriteLine("stack:" + ex.StackTrace);
            }

            Thread.Sleep(Timeout.Infinite);
        }
Exemplo n.º 4
0
        public static async Task <IEnumerable <WiFiNetworkInfo> > GetNetworksAsync(WiFiAdapter adapter)
        {
            List <WiFiNetworkInfo> wifiNetworks = new List <WiFiNetworkInfo>();

            await adapter.ScanAsync();

            foreach (var network in adapter.NetworkReport.AvailableNetworks)
            {
                wifiNetworks.Add(new WiFiNetworkInfo()
                {
                    BSSID = network.Bssid,
                    SSID  = network.Ssid,
                    ChannelCenterFrequencyInKilohertz = network.ChannelCenterFrequencyInKilohertz,
                    SignalBars   = network.SignalBars,
                    IsWiFiDirect = network.IsWiFiDirect,
                    NetworkRssiInDecibelMilliwatts = network.NetworkRssiInDecibelMilliwatts,
                    PhyKind            = network.PhyKind,
                    NetworkKind        = network.NetworkKind,
                    AuthenticationType = network.SecuritySettings.NetworkAuthenticationType,
                    EncryptionType     = network.SecuritySettings.NetworkEncryptionType,
                    BeaconInterval     = network.BeaconInterval,
                    Uptime             = network.Uptime
                });
            }

            return(wifiNetworks);
        }
Exemplo n.º 5
0
        public async void Scan()
        {
            var access = await WiFiAdapter.RequestAccessAsync();
            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
            if (result.Count >= 1)
            {
                 nwAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
                await nwAdapter.ScanAsync();

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

                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Return the SSIDs of the available network list.
        /// </summary>
        public async Task <List <string> > GetNetworkList()
        {
            List <string> m_networkList = new List <string>();

            if (m_wiFiAdapter == null)
            {
                while (await Initialize() != 0)
                {
                }
                return(await GetNetworkList());
            }
            else
            {
                await m_wiFiAdapter.ScanAsync();

                if (m_wiFiAdapter.NetworkReport.AvailableNetworks.Count > 0)
                {
                    foreach (WiFiAvailableNetwork network in m_wiFiAdapter.NetworkReport.AvailableNetworks.Distinct())
                    {
                        rootPage.Log(string.Format("NETWORK_MANAGER::GetNetworkList: AP {0} found.", network.Ssid));
                        m_networkList.Add(network.Ssid);
                    }
                    return(m_networkList.Distinct().ToList());
                }
            }
            return(null);
        }
Exemplo n.º 7
0
        public async void Scan()
        {
            var access = await WiFiAdapter.RequestAccessAsync();

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

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

                await nwAdapter.ScanAsync();

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

                    b.Click += B_Click;
                    s.Children.Add(b);
                    s.Children.Add(t);
                    sp.Children.Add(s);
                }
            }
        }
Exemplo n.º 8
0
        private async void ScanForWiFiNetworksAsync()
        {
            if (m_selectedWiFiAdapterIndex >= 0)
            {
                m_wiFiAdapter = m_wiFiAdapterList[m_selectedWiFiAdapterIndex];
            }

            if (m_wiFiAdapter != null)
            {
                UpdateConnectivityStatusAsync();
                NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
                UpdateStatusAsync("Scanning for available WiFi networks...", NotifyType.StatusMessage);
                await m_wiFiAdapter.ScanAsync();

                m_onboarderNetworkList.Clear();
                if (m_wiFiAdapter.NetworkReport.AvailableNetworks.Count > 0)
                {
                    foreach (WiFiAvailableNetwork network in m_wiFiAdapter.NetworkReport.AvailableNetworks)
                    {
                        m_onboarderNetworkList.Add(network);
                    }
                    ConnectPanelVisibility = Visibility.Visible;
                    UpdateStatusAsync("Scan complete. Please select a network to connect.", NotifyType.StatusMessage);
                }
                else
                {
                    UpdateStatusAsync("Scan complete. No WiFi networks found.", NotifyType.ErrorMessage);
                }
            }
        }
Exemplo n.º 9
0
        public static NetworkConfig GetNetworkConfig()
        {
            var nis = NetworkInterface.GetAllNetworkInterfaces();

            if (nis.Length <= 0)
            {
                return(new NetworkConfig(NetworkInterfaceType.Unknown, string.Empty, double.NaN, string.Empty,
                                         string.Empty));
            }

            // get the first interface
            var ni = nis[0];

            if (ni.NetworkInterfaceType != NetworkInterfaceType.Wireless80211)
            {
                return(new NetworkConfig(ni.NetworkInterfaceType, string.Empty, double.NaN, ni.IPv4Address,
                                         ni.IPv4GatewayAddress));
            }

            var wc = Wireless80211Configuration.GetAllWireless80211Configurations()[ni.SpecificConfigId];

            _wifiAdapter.ScanAsync();
            _autoResetEvent.WaitOne();
            double rssi = double.NaN;

            foreach (var networkReportAvailableNetwork in _wifiAdapter.NetworkReport.AvailableNetworks)
            {
                if (networkReportAvailableNetwork.Ssid == wc.Ssid)
                {
                    rssi = networkReportAvailableNetwork.NetworkRssiInDecibelMilliwatts;
                }
            }

            return(new NetworkConfig(ni.NetworkInterfaceType, wc.Ssid, rssi, ni.IPv4Address, ni.IPv4GatewayAddress));
        }
Exemplo n.º 10
0
        private async Task <bool> _getNetworks()
        {
            WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync();

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

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

            foreach (WiFiAvailableNetwork availableNetwork in _WiFiAdapter.NetworkReport.AvailableNetworks)
            {
                _WiFiNetworks.Add(availableNetwork.Ssid);
            }
            return(true);
        }
Exemplo n.º 11
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);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Retrieve SSID of connected wifi network
        /// </summary>
        /// <param name="wiFiAdapter"></param>
        /// <returns>String - SSID</returns>
        private static async Task <String> getConnectedWifi(WiFiAdapter wiFiAdapter)
        {
            await wiFiAdapter.ScanAsync();

            ConnectionProfile connectedProfile = await wiFiAdapter.NetworkAdapter.GetConnectedProfileAsync();

            return(connectedProfile.GetNetworkNames()[0]);
        }
Exemplo n.º 13
0
        private static void Spp_ReceivedData(IBluetoothSpp sender, SppReceivedDataEventArgs ReadRequestEventArgs)
        {
            string message = ReadRequestEventArgs.DataString;

            Debug.WriteLine($"Received=>{message}");

            string[] args = message.Trim().Split(' ');
            if (args.Length != 0)
            {
                switch (args[0].ToLower())
                {
                // Scan for wifi networks
                case "scan":
                    InitWiFiScan();
                    sender.SendString("Scanning Networks\n");
                    wifi.ScanAsync();
                    break;

                // Dummy set WiFi credentials
                case "wifi":
                    if (args.Length != 3)
                    {
                        sender.SendString("Wrong number of arguments\n");
                        break;
                    }
                    sender.SendString("Set Wifi credentials\n");

                    // Save credentials Here

                    break;

                // Send current ESP32 native memory
                case "mem":
                    uint totalSize, totalFreeSize, largestBlock;
                    NativeMemory.GetMemoryInfo(NativeMemory.MemoryType.All, out totalSize, out totalFreeSize, out largestBlock);
                    sender.SendString($"Native memory - total:{totalSize} Free:{totalFreeSize} largest:{largestBlock}\n");
                    break;

                // Reboot device
                case "reboot":
                    sender.SendString("Rebooting now\n");
                    Thread.Sleep(100);
                    Power.RebootDevice();
                    break;

                // Some help
                case "help":
                    sender.SendString("Help\n");
                    sender.SendString("-------------------------------------------\n");
                    sender.SendString("'scan' - Scan WiFi networks\n");
                    sender.SendString("'mem' - Show native free memory\n");
                    sender.SendString("'reboot' - Reboot device\n");
                    sender.SendString("'wifi ssid password' - Set WiFI credentials\n");
                    sender.SendString("-------------------------------------------\n");
                    break;
                }
            }
        }
Exemplo n.º 14
0
        public async Task ScanAsync()
        {
            if (_firstAdapter != null)
            {
                await _firstAdapter.ScanAsync();

                DisplayNetworkReport(_firstAdapter.NetworkReport);
            }
        }
Exemplo n.º 15
0
 private async void Scan()
 {
     if (ActiveDevice)
     {
         await WifiDevice.ScanAsync();
     }
     else
     {
         return;
     }
 }
Exemplo n.º 16
0
        public static void Main()
        {
            Debug.WriteLine("Hello World :-)!");

            try
            {
                int connectRetry = 0;

                // Get the first WiFI Adapter
                WiFiAdapter wifi = WiFiAdapter.FindAllAdapters()[0];
                Debug.WriteLine("Getting wifi adaptor");

                wifi.AvailableNetworksChanged += WifiAvailableNetworksChanged;

rescan:
                wifi.ScanAsync();
                Debug.WriteLine("Scanning...");

                var timeout = DateTime.UtcNow.AddSeconds(10);
                while (!_isConnected)
                {
                    Thread.Sleep(100);
                    if (DateTime.UtcNow > timeout)
                    {
                        goto rescan;
                    }
                }

                NetworkHelpers.SetupAndConnectNetwork(false);

                Debug.WriteLine("Waiting for network up and IP address...");

                while (!NetworkHelpers.CheckIP())
                {
                    Thread.Sleep(500);
                    connectRetry++;
                    if (connectRetry == 5)
                    {
                        connectRetry = 0;
                        goto rescan;
                    }
                }

                using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(ApiController) }))
                {
                    server.Start();
                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Handles the <see cref="WiFiAdapter.AvailableNetworksChanged"/> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private void WiFiAdapter_AvailableNetworksChanged(WiFiAdapter sender, object e)
        {
            Debug.WriteLine(string.Empty);
            WiFiAvailableNetwork[] networks = sender.NetworkReport.AvailableNetworks;
            Debug.WriteLine($"Network scan complete, found {networks.Length} networks");
            foreach (var network in networks)
            {
                Debug.WriteLine(network.Ssid);
            }

            sender.ScanAsync();
        }
Exemplo n.º 18
0
        public static void Main()
        {
            Debug.WriteLine("Hello from nanoFramework wifi!");

            try
            {
                // Get the first WiFI Adapter
                WiFiAdapter wifi = WiFiAdapter.FindAllAdapters()[0];

                // Set up the AvailableNetworksChanged event to pick up when scan has completed
                wifi.AvailableNetworksChanged += Wifi_AvailableNetworksChanged;

                Debug.WriteLine("starting WiFi scan");
                wifi.ScanAsync();


                var remoteIp    = IPAddress.Any;
                var receivePort = 12345;

                Debug.WriteLine("receive message");

                using (var udpReceive = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    udpReceive.Bind(new IPEndPoint(remoteIp, receivePort));

                    var resBytes = new byte[1024];

                    while (true)
                    {
                        Debug.WriteLine("wait...");

                        var resSize = udpReceive.Receive(resBytes);

                        var receiveMsg = Encoding.UTF8.GetString(resBytes, 0, resSize);

                        Debug.WriteLine($"receiveData   : {receiveMsg}");

                        if (receiveMsg == "exit")
                        {
                            break;
                        }
                    }
                    udpReceive.Close();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("message:" + ex.Message);
                Debug.WriteLine("stack:" + ex.StackTrace);
            }

            Thread.Sleep(Timeout.Infinite);
        }
 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         await firstAdapter.ScanAsync();
     }
     catch (Exception err)
     {
         rootPage.NotifyUser(String.Format("Error scanning WiFi adapter: 0x{0:X}: {1}", err.HResult, err.Message), NotifyType.ErrorMessage);
         return;
     }
     await DisplayNetworkReportAsync(firstAdapter.NetworkReport);
 }
Exemplo n.º 20
0
 public async Task ScanNetworksAsync()
 {
     try
     {
         await _wifiAdapter.ScanAsync();
     }
     catch (Exception ex)
     {
         Status = WiFiSettingsStatus.Error;
         Debug.WriteLine(ex.Message);
     }
     await InitializeNetworksAsync(_wifiAdapter.NetworkReport);
 }
Exemplo n.º 21
0
        public async Task <WiFiAvailableNetwork> GetSpecificNetwork(WiFiAdapter adapter, string bssid, string ssid)
        {
            await adapter.ScanAsync();

            foreach (var network in adapter.NetworkReport.AvailableNetworks)
            {
                if (network.Bssid.Equals(bssid) && network.Ssid.Equals(ssid))
                {
                    return(network);
                }
            }
            return(null);
        }
Exemplo n.º 22
0
        private async void ScanButton_Click(object sender, RoutedEventArgs e)
        {
            await wifiAdapter.ScanAsync();

            List <string> ls = new List <string>();

            foreach (var network in wifiAdapter.NetworkReport.AvailableNetworks)
            {
                ls.Add(network.Ssid);
            }

            WiFiList.ItemsSource    = ls;
            connectpanel.Visibility = Visibility.Collapsed;
        }
Exemplo n.º 23
0
        private async void Scan_Click(object sender, RoutedEventArgs e)
        {
            ScanButton.IsEnabled = false;
            ScanButton.Content   = "Scanning...";
            networks.Clear();
            await adapter.ScanAsync();

            ScanButton.IsEnabled = true;
            ScanButton.Content   = "Scan networks";
            foreach (var network in adapter.NetworkReport.AvailableNetworks)
            {
                networks.Add(new WiFiNetworkDisplay(network, adapter));
            }
        }
Exemplo n.º 24
0
        private async void OnRefreshRequested(object sender, RefreshRequestedEventArgs e)
        {
            if (!Allowed)
            {
                Toast.ShowError("不允许连接wifi,请确认已开启wifi,重新打开应用");
                return;
            }
            await firstAdapter.ScanAsync();

            LoadingVisibility = Visibility.Visible;
            await DisplayNetworkReport(firstAdapter.NetworkReport);

            e?.GetDeferral();
        }
Exemplo n.º 25
0
        /// <summary>
        /// Возвращает список доступных устройств
        /// </summary>
        /// <returns></returns>
        public async Task <IEnumerable <WiFiAvailableNetwork> > GetAvailableDevicesAsAPAsync()
        {
            bool initRes = await InitializeFirstAdapter();

            if (initRes)
            {
                await _wifiAdapter.ScanAsync();

                return(await Task <IEnumerable <WiFiAvailableNetwork> > .Factory.StartNew(() =>
                {
                    return _wifiAdapter.NetworkReport.AvailableNetworks.Where(dev => dev.Ssid.IndexOf(Consts.ESP) != -1);
                }));
            }

            return(new List <WiFiAvailableNetwork>());
        }
Exemplo n.º 26
0
        public IAsyncOperation <OnboardingGetScanInfoResult> GetScanInfoAsync(AllJoynMessageInfo info)
        {
            return(Task.Run(async() =>
            {
                await _wlanAdapter.ScanAsync();

                var availableNetworks = new List <OnboardingScanListItem>();
                foreach (var network in _wlanAdapter.NetworkReport.AvailableNetworks)
                {
                    var listItem = new OnboardingScanListItem {
                        Value1 = network.Ssid
                    };

                    switch (network.SecuritySettings.NetworkAuthenticationType)
                    {
                    case NetworkAuthenticationType.Open80211:
                        {
                            listItem.Value2 = (short)AuthType.Open;
                            break;
                        }

                    case NetworkAuthenticationType.Wpa:
                        {
                            listItem.Value2 = (short)AuthType.WPA_AUTO;
                            break;
                        }

                    default:
                        {
                            listItem.Value2 = (short)AuthType.Any;
                            break;
                        }
                    }

                    if (availableNetworks.Find(x => x.Value1 == listItem.Value1 && x.Value2 == listItem.Value2) == null)
                    {
                        availableNetworks.Add(listItem);
                    }
                }

                return OnboardingGetScanInfoResult.CreateSuccessResult(0, availableNetworks);
            }).AsAsyncOperation());
        }
Exemplo n.º 27
0
 public async Task GetAvailableNetWorksAsync()
 {
     try
     {
         if (adapter != null)
         {
             await adapter.ScanAsync();
         }
     }
     catch (Exception err)
     {
         throw new WifiAdaperAccessDeniedException();
     }
     Networks = new List <WifiNetwork>();
     foreach (var network in adapter.NetworkReport.AvailableNetworks)
     {
         Networks.Add(new WifiNetwork(network, adapter));
     }
 }
Exemplo n.º 28
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;
            }
        }
Exemplo n.º 29
0
        async void _watcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            WiFiAdapter device = await WiFiAdapter.FromIdAsync(args.Id);

            if (device != null)
            {
                // add the device to the list (this will keep the object around
                lock (this)
                {
                    _deviceList.Add(device);
                }

                // register for changes
                device.AvailableNetworksChanged += device_AvailableNetworksChanged;

                // issue a scan
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    await device.ScanAsync().AsTask();
                });
            }
        }
Exemplo n.º 30
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;
            }
        }
Exemplo n.º 31
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            PopupFailMessage.IsOpen = false;
            try
            {
                var access = await WiFiAdapter.RequestAccessAsync();

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

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

                        await m_WifiAdapter.ScanAsync();

                        DisplayNetworkReport(m_WifiAdapter.NetworkReport);

                        m_ScanButton.IsEnabled = true;
                    }
                    else
                    {
                        //rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                PopupFailMessage.IsOpen = true;
                //this.Frame.GoBack();
                Message.Text = ex.ToString();
            }
        }
Exemplo n.º 32
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");
            }
        }
        public async void GetNetworks()
        {
            var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());

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

                await firstAdapter.ScanAsync();

                deviceNetwork = firstAdapter.NetworkReport.AvailableNetworks.FirstOrDefault(N => N.Ssid == selectedDevice.GivenName); 

                var qualifyingWifi = firstAdapter.NetworkReport.AvailableNetworks.Where(N => !N.Ssid.ToLower().StartsWith("ioespt-thing"));

                foreach(var network in qualifyingWifi)
                {
                    networks.Add(network);
                }

                selectedNetwork = networks.FirstOrDefault();
            }
        }