public async Task<WiFiScanResultTypes> LoadData() { Enabled_btnRefresh = false; ShowRunning(); WifiNetworks = new ObservableCollection<WiFiAvailableNetwork>(); var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { Enabled_btnRefresh = true; HideRunning(); return WiFiScanResultTypes.NO_ACCESS_TO_WIFI_CARD; } var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count > 0) { PrimaryAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); } else { Enabled_btnRefresh = true; HideRunning(); return WiFiScanResultTypes.NO_WIFI_CARD; } await PrimaryAdapter.ScanAsync(); foreach (var network in PrimaryAdapter.NetworkReport.AvailableNetworks) { WifiNetworks.Add(network); } WifiNetworks = new ObservableCollection<WiFiAvailableNetwork>(WifiNetworks.OrderByDescending(a => a.SignalBars)); Enabled_btnRefresh = true; HideRunning(); return WiFiScanResultTypes.SUCCESS; }
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); } } }
public WiFiNetworkDisplay(WiFiAvailableNetwork availableNetwork, WiFiAdapter adapter) { AvailableNetwork = availableNetwork; this.adapter = adapter; UpdateWiFiImage(); UpdateConnectivityLevel(); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { ResultCollection = new ObservableCollection <WiFiNetworkDisplay>(); rootPage = MainPage.Current; // RequestAccessAsync must have been called at least once by the app before using the API // Calling it multiple times is fine but not necessary // RequestAccessAsync must be called from the UI thread var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage); } else { DataContext = this; var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); var button = new Button(); button.Content = string.Format("Scan"); button.Click += Button_Click; Buttons.Children.Add(button); } else { rootPage.NotifyUser("No WiFi Adapters detected on this machine", NotifyType.ErrorMessage); } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { ResultCollection = new ObservableCollection <WiFiNetworkDisplay>(); rootPage = MainPage.Current; // RequestAccessAsync must have been called at least once by the app before using the API // Calling it multiple times is fine but not necessary // RequestAccessAsync must be called from the UI thread var result = await WiFiAdapter.RequestAccessAsync(); if (result != WiFiAccessStatus.Allowed) { rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage); } else { DataContext = this; wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync(); int index = 0; foreach (var adapter in wiFiAdapters) { var button = new Button(); button.Tag = index; button.Content = String.Format("WiFi Adapter {0}", ++index); button.Click += Button_Click; Buttons.Children.Add(button); } } }
// Call this method before accessing WiFiAdapters Dictionary private async Task UpdateAdapters() { Log.Enter(); bool fInit = false; foreach (var adapter in WiFiAdapters) { if (adapter.Value == null) { // New Adapter plugged-in which requires Initialization fInit = true; } } if (fInit) { List <String> WiFiAdaptersID = new List <string>(WiFiAdapters.Keys); for (int i = 0; i < WiFiAdaptersID.Count; i++) { string id = WiFiAdaptersID[i]; try { WiFiAdapters[id] = await WiFiAdapter.FromIdAsync(id); } catch (Exception) { WiFiAdapters.Remove(id); } } } Log.Leave(); }
private static void ConnectWlan(string ssid, string password) { try { IAsyncOperation <IReadOnlyList <WiFiAdapter> > operation1 = WiFiAdapter.FindAllAdaptersAsync(); var adapters = operation1.GetResults(); var adapter = adapters.FirstOrDefault(); var ignore = adapter.ScanAsync(); foreach (var network in adapter.NetworkReport.AvailableNetworks) { if (network.Ssid.Equals(ssid)) { PasswordCredential passwordCredential = new PasswordCredential(); passwordCredential.Password = password; var operation2 = adapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, passwordCredential); operation2.AsTask().Wait(); var result = operation2.GetResults(); if (result.ConnectionStatus != WiFiConnectionStatus.Success) { throw new Exception("Connect WiFi failed! Reason: " + result.ConnectionStatus.ToString()); } } } } catch (Exception ex) { throw ex; } }
public static async Task <bool> TryConnectWlan() { resetEvent = new AutoResetEvent(false); try { var access = await WiFiAdapter.RequestAccessAsync(); if (access == WiFiAccessStatus.Allowed) { TurnOnWiFi(); StartWiFiHotspot(); var result = resetEvent.WaitOne(120000); DisposeWiFiPublisher(); return(result); } return(false); } catch (Exception ex) { throw ex; } }
/// <summary> /// Event handler for when WiFi scan completes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void Wifi_AvailableNetworksChanged(WiFiAdapter sender, object e) { Debug.WriteLine("Wifi_AvailableNetworksChanged - get report"); // Get Report of all scanned WiFi networks WiFiNetworkReport report = sender.NetworkReport; // Enumerate though networks looking for our network foreach (WiFiAvailableNetwork net in report.AvailableNetworks) { // Show all networks found Debug.WriteLine($"Net SSID :{net.Ssid}, BSSID : {net.Bsid}, rssi : {net.NetworkRssiInDecibelMilliwatts.ToString()}, signal : {net.SignalBars.ToString()}"); // If its our Network then try to connect if (net.Ssid == MYSSID) { // Disconnect in case we are already connected sender.Disconnect(); // Connect to network WiFiConnectionResult result = sender.Connect(net, WiFiReconnectionKind.Automatic, MYPASSWORD); // Display status if (result.ConnectionStatus == WiFiConnectionStatus.Success) { Debug.WriteLine("Connected to Wifi network"); } else { Debug.WriteLine($"Error {result.ConnectionStatus.ToString()} connecting o Wifi network"); } } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { ResultCollection = new ObservableCollection<WiFiNetworkDisplay>(); rootPage = MainPage.Current; // RequestAccessAsync must have been called at least once by the app before using the API // Calling it multiple times is fine but not necessary // RequestAccessAsync must be called from the UI thread var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage); } else { DataContext = this; var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); RegisterButton.IsEnabled = true; } else { rootPage.NotifyUser("No WiFi Adapters detected on this machine", NotifyType.ErrorMessage); } } }
private static void AddWindowsHandlers(this IServiceCollection services) { services.AddSingleton(async s => (await WiFiAdapter.FindAllAdaptersAsync()).First()); services.AddSingleton <ISignalReader <WiFiNetworkReport>, WindowsSignalReader>(); services.AddSingleton <ISignalParser <WiFiNetworkReport>, WindowsSignalParser>(); services.AddHostedService <SignalService <WiFiNetworkReport> >(); }
public async Task <int> Initialize() { if (m_wiFiAdapter == null) { //Request access of WiFi adapter. WiFiAccessStatus accessStatus = await WiFiAdapter.RequestAccessAsync(); if (accessStatus != WiFiAccessStatus.Allowed) { rootPage.Log("NETWORK_MANAGER::[ERROR]ScanForWiFiAdapterAsync: WiFi access denied."); } else { //Find WiFi adatper m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync(); rootPage.Log("NETWORK_MANAGER::Found " + m_wiFiAdapterList.Count + " wifi adapter."); while (m_wiFiAdapterList.Count < 1) { await System.Threading.Tasks.Task.Delay(3000); m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync(); rootPage.Log("NETWORK_MANAGER::Found " + m_wiFiAdapterList.Count + " wifi adapter."); } //Get the first WiFi adatper from the list. //TODO: Edit this part if the system has more than one WiFi adatpers. m_wiFiAdapter = m_wiFiAdapterList[0]; } return(-1); } return(0); }
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); } } }
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); }
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); }
private async void Scan() { if (IsReady) { IsReady = false; uint signal = 0; #if !UNITY_EDITOR var result = await WiFiAdapter.FindAllAdaptersAsync(); if (result.Count >= 1) { var firstAdapter = result[0]; await firstAdapter.ScanAsync(); GenerateNetworkReport(firstAdapter.NetworkReport); if (!string.IsNullOrEmpty(Ssid)) { signal = GetNetworkSignal(firstAdapter.NetworkReport, Ssid); } } #endif IsReady = true; Signal = signal; } }
public async Task <IEnumerable <WifiNetwork> > GetWifiAsync() { _wifis = new List <WifiNetwork>(); _wifisOriginals = new List <WiFiNetworkDisplay>(); var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { //rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage); } else { var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { _firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await ScanAsync(); return(_wifis.OrderByDescending(w => w.SignalBars)); } else { //No WiFi Adapters detected on this machine } } return(null); }
private static void WifiAvailableNetworksChanged(WiFiAdapter sender, object e) { var wifiNetworks = sender.NetworkReport.AvailableNetworks; foreach (var net in wifiNetworks) { Debug.WriteLine($"SSID: {net.Ssid}, strength: {net.SignalBars}"); if (net.Ssid == MySsid) { if (_isConnected) { sender.Disconnect(); _isConnected = false; Thread.Sleep(3000); } // Connect to network WiFiConnectionResult result = sender.Connect(net, WiFiReconnectionKind.Automatic, MyPassword); // Display status if (result.ConnectionStatus == WiFiConnectionStatus.Success) { Debug.WriteLine($"Connected to Wifi network {net.Ssid}"); _isConnected = true; break; } else { Debug.WriteLine($"Error {result.ConnectionStatus} connecting to Wifi network"); } } } }
public static async Task <string> GetSsid() { var profile = NetworkInformation.GetInternetConnectionProfile(); if (profile != null && profile.IsWlanConnectionProfile) { return(profile.WlanConnectionProfileDetails.GetConnectedSsid()); } var access = await WiFiAdapter.RequestAccessAsync(); if (access == WiFiAccessStatus.Allowed) { var adapters = await WiFiAdapter.FindAllAdaptersAsync(); foreach (var adapter in adapters) { var connectedProfile = await adapter.NetworkAdapter.GetConnectedProfileAsync(); if (connectedProfile != null) { return(connectedProfile.ProfileName); } } } return(string.Empty); }
private async Task <Tuple <Windows.Devices.WiFi.WiFiConnectionStatus, string> > ConnectWifiAndGetPassword(string ssid) { var access = await WiFiAdapter.RequestAccessAsync(); var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { var nwAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await nwAdapter.ScanAsync(); //because spelling errors var nw = nwAdapter.NetworkReport.AvailableNetworks.Where(network => network.Ssid.Contains(ssid)); if (nw.Count() > 0) { var suitAP = nw.First(); var pass = SsidToPassword(suitAP.Ssid); var conn = await nwAdapter.ConnectAsync(suitAP, WiFiReconnectionKind.Automatic, new Windows.Security.Credentials.PasswordCredential("none", "none", pass)); return(new Tuple <WiFiConnectionStatus, string>(conn.ConnectionStatus, pass)); } } return(new Tuple <WiFiConnectionStatus, string>(WiFiConnectionStatus.NetworkNotAvailable, "")); }
/// <summary> /// Отправить устройству параметры для подключения к роутеру /// </summary> /// <param name="connectionParams"></param> /// <returns></returns> public async Task <bool> SendConnectionParamsToDeviceAsAP(IConnectionParams connectionParams) { return(await Task.Run(async() => { List <CommandParameter> content = new List <CommandParameter> { new CommandParameter("ssid", connectionParams.Ssid), new CommandParameter("password", connectionParams.Password) }; //TODO: изменить на устройстве код приёма параметров подключения Communicator communicator = new Communicator(); OperationResult result = await communicator.SendToDevice(_ip, CommandNames.ConnectionParams, content); if (!result.Success) { ConnectorByWiFi connector = new ConnectorByWiFi(); WiFiAdapter wiFiAdapter = await connector.GetWiFiAdapter(); if (wiFiAdapter.NetworkAdapter.NetworkItem.GetNetworkTypes() == Windows.Networking.Connectivity.NetworkTypes.None) { result.Success = await connector.Reconnect(); } } return result.Success; })); }
private async Task <List <string> > GetWirelessSuits() { var access = await WiFiAdapter.RequestAccessAsync(); var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { var nwAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await nwAdapter.ScanAsync(); //because spelling errors var nw = nwAdapter.NetworkReport.AvailableNetworks.Where(network => network.Ssid.Contains("NSVR") || network.Ssid.Contains("NVSR:")); return(nw.Select(suit => suit.Ssid).ToList()); //if (nw.Count() > 0) //{ // var suitAP = nw.First(); // var pass = SsidToPassword(suitAP.Ssid); // var conn = await nwAdapter.ConnectAsync(suitAP, WiFiReconnectionKind.Automatic, new Windows.Security.Credentials.PasswordCredential("none", "none", pass)); // return new Tuple<WiFiConnectionStatus, string>(conn.ConnectionStatus, pass); //} } return(new List <string>()); }
private async Task RefreshWiFiNetworkName() { string wiFiName = "No WiFi !"; if (_wifiAdapter == null) { _wifiAdapter = await FetchWiFiAdapter(); } if (_wifiAdapter != null) { var connectedProfile = await _wifiAdapter.NetworkAdapter.GetConnectedProfileAsync(); if (connectedProfile != null) { wiFiName = connectedProfile.ProfileName; } } ; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { wifiNetworkButton.Content = wiFiName; if (wiFiName.ToLower() != "#racing") { wifiNetworkButton.Background = _tomatoBrush; wifiNetworkButton.Foreground = _whiteBrush; } else { wifiNetworkButton.Background = _transparentBrush; wifiNetworkButton.Foreground = _lightGreenBrush; } }); }
public async Task <bool> StartAsync() { // only one start allowed on the object lock (this) { if (_started) { return(false); } _started = true; } if (await WiFiAdapter.RequestAccessAsync() != WiFiAccessStatus.Allowed) { return(false); } _started = true; // enumerate and monitor WiFi devices in the system string deviceSelector = WiFiAdapter.GetDeviceSelector(); _watcher = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(deviceSelector); _watcher.Added += _watcher_Added; _watcher.Removed += _watcher_Removed; _watcher.Start(); return(true); }
private async void ScanForWiFiAdaptersAsync() { if (m_wiFiAdapter == null) { UpdateStatusAsync("Requesting WiFi access...", NotifyType.StatusMessage); WiFiAccessStatus accessStatus = await WiFiAdapter.RequestAccessAsync(); if (accessStatus != WiFiAccessStatus.Allowed) { UpdateStatusAsync("WiFi access denied.", NotifyType.ErrorMessage); } else { m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync(); if (m_wiFiAdapterList.Count > 0) { for (int i = 0; i < m_wiFiAdapterList.Count; i++) { m_wiFiAdapterDisplayNames.Add(string.Format("Adapter {0}", (i + 1))); } WiFiAdapterListVisibility = Visibility.Visible; UpdateStatusAsync("Please select a WiFi adapter.", NotifyType.StatusMessage); } else { UpdateStatusAsync("No WiFi adapters detected on this machine.", NotifyType.ErrorMessage); } } } }
private async Task <bool> UpdateInfoAsync() { if ((await TestAccessAsync()) == false) { return(false); } networkNameToInfo = new Dictionary <WiFiAvailableNetwork, WiFiAdapter>(); var adapters = WiFiAdapter.FindAllAdaptersAsync(); foreach (var adapter in await adapters) { await adapter.ScanAsync(); if (adapter.NetworkReport == null) { continue; } foreach (var network in adapter.NetworkReport.AvailableNetworks) { if (!HasSsid(networkNameToInfo, network.Ssid)) { networkNameToInfo[network] = adapter; } } } return(true); }
public static IAsyncAction WaitForWiFiConnection() { return(AsyncInfo.Run(async(cancel) => { if (!await EnableWiFi()) { return; } var accessAllowed = await WiFiAdapter.RequestAccessAsync(); if (accessAllowed == WiFiAccessStatus.Allowed) { var adapterList = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); var wifiAdapter = await WiFiAdapter.FromIdAsync(adapterList[0].Id); for (var i = 0; i < 5; i++) { cancel.ThrowIfCancellationRequested(); await wifiAdapter.ScanAsync(); await Task.Delay(100); if (await wifiAdapter.NetworkAdapter.GetConnectedProfileAsync() != null) { break; } } } })); }
public async Task <ResultCommandAvailableNetworks> GetAvailableNetworkListHandler() { try { var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync(); List <AvailableNetwork> networks = new List <AvailableNetwork>(); foreach (var adapter in wifiAdapterList) { try { var availableNetworks = await PortalApiHelper.GetAvailableNetworks(adapter.NetworkAdapter.NetworkAdapterId); if (availableNetworks != null && availableNetworks.AvailableNetworks != null) { networks.AddRange(availableNetworks.AvailableNetworks); } } catch (Exception) { } } var sortedNetworks = networks.OrderBy(x => x.SSID).Distinct().ToList(); return(new ResultCommandAvailableNetworks() { Networks = sortedNetworks, IsSuccess = true }); } catch (Exception e) { DebugHelper.LogError($"Error GetAvailableNetworkListHandler: {e.Message}."); return(ResultCommand.CreateFailedCommand <ResultCommandAvailableNetworks>($"Error GetAvailableNetworkListHandler: {e.Message}.")); } }
public async Task extract_access_point_names() { /* * // Credits: https://stackoverflow.com/questions/40645146/how-can-i-get-the-currently-connected-wifi-ssid-and-signal-strength-in-dotnet-co * // WARNING: Not cross-platform. Only avaliable on Windows. Old (2014). * var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All); * foreach (var network in networks) * { * var sConnected = ((network.IsConnected == true) ? " (connected)" : " (disconnected)"); * Console.WriteLine("Network : " + network.Name + " - Category : " + network.Category.ToString() + sConnected); * access_point_names.Add(network.Name); * } */ // Credits: https://stackoverflow.com/questions/496568/how-do-i-get-the-available-wifi-aps-and-their-signal-strength-in-net?rq=1 var adapters = await WiFiAdapter.FindAllAdaptersAsync(); foreach (var adapter in adapters) { foreach (var network in adapter.NetworkReport.AvailableNetworks) { Console.WriteLine($"ssid: {network.Ssid}" + " | " + $"signal strength: {network.SignalBars}"); access_point_names.Add(network.Ssid); } } }
public byte WiFiAdapterStatusAsync() { var t_Task = Task.Run(async delegate { vReturn = 0x40; ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile(); bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess; if (internet) { vReturn = 0x04; } // internet available else { // no internet -> check for adapter var result = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (!(result.Count >= 1)) { vReturn = 0x01; } // No WiFi Adapter available else { vReturn = 0x02; } } }); t_Task.Wait(); return(vReturn); }
private async Task InitializeFirstAdapter() { var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { throw new Exception("WiFiAccessStatus not allowed"); } else { var wifiAdapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (wifiAdapterResults.Count >= 1) { this.WiFiAdapter = await WiFiAdapter.FromIdAsync(wifiAdapterResults[0].Id); } else { throw new Exception("WiFi Adapter not found."); } } if (this.WiFiAdapter != null) { await this.WiFiAdapter.ScanAsync(); } }
public static void SetupAndConnectNetwork() { wifi = WiFiAdapter.FindAllAdapters()[0]; WiFiConnectionResult wiFiConnectionResult = wifi.Connect(c_SSID, WiFiReconnectionKind.Automatic, c_AP_PASSWORD); NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); if (nis.Length > 0) { NetworkInterface ni = nis[0]; ni.EnableAutomaticDns(); ni.EnableDhcp(); CheckIP(); if (!NetworkHelpers.IpAddressAvailable.WaitOne(5000, false)) { throw new NotSupportedException("ERROR: IP address is not assigned to the network interface."); } } else { throw new NotSupportedException("ERROR: there is no network interface configured.\r\nOpen the 'Edit Network Configuration' in Device Explorer and configure one."); } }
/// <summary> /// WiFiスキャンが完了したときのイベント /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void Wifi_AvailableNetworksChanged(WiFiAdapter sender, object e) { Debug.WriteLine("Wifi_AvailableNetworksChanged - get report"); // スキャンされたすべてのWiFiネットワークのレポートを取得 WiFiNetworkReport report = sender.NetworkReport; // ネットワークを探して列挙する foreach (WiFiAvailableNetwork net in report.AvailableNetworks) { // 見つかったすべてのネットワークを表示 Debug.WriteLine($"Net SSID :{net.Ssid}, BSSID : {net.Bsid}, rssi : {net.NetworkRssiInDecibelMilliwatts.ToString()}, signal : {net.SignalBars.ToString()}"); // 自分のネットワークの場合、接続する if (net.Ssid == MYSSID) { // すでに接続されている場合は切断します sender.Disconnect(); // ネットワークに接続する WiFiConnectionResult result = sender.Connect(net, WiFiReconnectionKind.Automatic, MYPASSWORD); // ステータス表示 if (result.ConnectionStatus == WiFiConnectionStatus.Success) { Debug.WriteLine("Connected to Wifi network"); } else { Debug.WriteLine($"Error {result.ConnectionStatus} connecting o Wifi network"); } } } }
private void DisplayNetworkReport(WiFiNetworkReport report, WiFiAdapter adapter) { rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage); ResultCollection.Clear(); foreach (var network in report.AvailableNetworks) { ResultCollection.Add(new WiFiNetworkDisplay(network, adapter)); } }
public async Task<bool> Initialise() { var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); } else return false; return true; }
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); } } }
private async void DisplayNetworkReport(WiFiNetworkReport report, WiFiAdapter adapter) { await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage); ResultCollection.Clear(); foreach (var network in report.AvailableNetworks) { ResultCollection.Add(new WiFiNetworkDisplay(network, adapter)); } }); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { ResultCollection = new ObservableCollection<WiFiNetworkDisplay>(); rootPage = MainPage.Current; // RequestAccessAsync must have been called at least once by the app before using the API // Calling it multiple times is fine but not necessary // RequestAccessAsync must be called from the UI thread var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage); } else { DataContext = this; var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); var scanButton = new Button(); scanButton.Content = string.Format("Scan"); scanButton.Click += ScanButton_Click; Buttons.Children.Add(scanButton); var disconnectButton = new Button(); disconnectButton.Content = string.Format("Disconnect"); disconnectButton.Click += DisconnectButton_Click; ; Buttons.Children.Add(disconnectButton); // Monitor network status changes await UpdateConnectivityStatusAsync(); NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; } else { rootPage.NotifyUser("No WiFi Adapters detected on this machine", NotifyType.ErrorMessage); } } }
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; } }
private async void ScanForWifi() { var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { System.Diagnostics.Debug.WriteLine("Access denied"); return; } DataContext = this; var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count > 0) { Adapter = await WiFiAdapter.FromIdAsync(result[0].Id); var connected = await Adapter.NetworkAdapter.GetConnectedProfileAsync(); } else { System.Diagnostics.Debug.WriteLine("No WiFiAdapters detected"); return; } await Adapter.ScanAsync(); FillWifiCollection(Adapter.NetworkReport); }
private async void HandleAdapterAdded(DeviceWatcher sender, DeviceInformation information) { if (_wlanAdapterId == null) { _wlanAdapterId = information.Id; _wlanAdapter = await WiFiAdapter.FromIdAsync(_wlanAdapterId); lock (_stateLock) { if (_state != OnboardingState.ConfiguredValidated) { _softAccessPoint.Start(); } } _onboardingProducer.Start(); _iconProducer.Start(); } }
private void HandleAdapterRemoved(DeviceWatcher sender, DeviceInformationUpdate information) { if (_wlanAdapterId != null && _wlanAdapterId == information.Id) { _softAccessPoint.Stop(); _wlanAdapter = null; _wlanAdapterId = null; _onboardingProducer.Stop(); _iconProducer.Stop(); } }
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; } } } } }
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 }
public WiFiAdapterEvents(WiFiAdapter This) { this.This = This; }
public WifiDataModel(WiFiAvailableNetwork avNetwork, WiFiAdapter adapter) { AvailableNetwork = avNetwork; this.adapter = adapter; }
public WiFiNetworkDisplay(WiFiAvailableNetwork availableNetwork, WiFiAdapter adapter) { AvailableNetwork = availableNetwork; this.adapter = adapter; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { ResultCollection = new ObservableCollection<WiFiNetworkDisplay>(); var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); } foreach (var network in firstAdapter.NetworkReport.AvailableNetworks) { var networkDisplay = new WiFiNetworkDisplay(network, firstAdapter); await networkDisplay.UpdateConnectivityLevel(); ResultCollection.Add(networkDisplay); } // sfdgNetList.DataContext = WiFiScan.WiFiNetworkDisplay; sfdgNetList.AllowSorting = true; sfdgNetList.AllowFiltering = true; sfdgNetList.RowHeight = 13; sfdgNetList.HeaderRowHeight = 30; sfdgNetList.AutoGenerateColumns = false; sfdgNetList.ItemsSource = ResultCollection; sfdgNetList.ColumnSizer = Syncfusion.UI.Xaml.Grid.GridLengthUnitType.Auto; sfdgNetList.Columns.Add(new GridTextColumn() { HeaderText = "SSID", MappingName = "Ssid" }); sfdgNetList.Columns.Add(new GridTextColumn() { HeaderText = "BSSID", MappingName = "Bssid" }); sfdgNetList.Columns.Add(new GridTextColumn() { HeaderText = "Channel", MappingName = "Channel" }); sfdgNetList.Columns.Add(new GridTextColumn() { HeaderText = "RSSI", MappingName = "Rssi" }); sfdgNetList.Columns.Add(new GridTextColumn() { HeaderText = "Security", MappingName = "SecuritySettings" }); //Chart Stuff sfChartNetView24.Header = "Wi-Fi Networks"; NumericalAxis primaryAxis = new Syncfusion.UI.Xaml.Charts.NumericalAxis(); primaryAxis.Minimum = 0; primaryAxis.Maximum = 14; primaryAxis.Interval = 1; primaryAxis.Header = "Channels"; sfChartNetView24.PrimaryAxis = primaryAxis; NumericalAxis SecondaryNumericalAxis = new Syncfusion.UI.Xaml.Charts.NumericalAxis(); SecondaryNumericalAxis.Header = "Signal Strength"; SecondaryNumericalAxis.Minimum = -100; SecondaryNumericalAxis.Maximum = -15; SecondaryNumericalAxis.Interval = 10; sfChartNetView24.SecondaryAxis = SecondaryNumericalAxis; ChartSeriesInput = new ObservableCollection<ChartHelperBssidNodeSeries>(); ChartSeriesInput = HelperFunctions.ChartHelper(ResultCollection); foreach (ChartHelperBssidNodeSeries c in ChartSeriesInput) { SplineSeries mySeries = new SplineSeries(); mySeries.ItemsSource = c.Series; mySeries.Label = "Home"; mySeries.XBindingPath = "Channel"; mySeries.YBindingPath = "Rssi"; mySeries.StrokeThickness = 2; //mySeries.EnableAnimation = true; //mySeries.AnimationDuration = System.TimeSpan.FromSeconds(.2); sfChartNetView24.Series.Add(mySeries); } //Chart Stuff sfChartNetView52.Header = "Wi-Fi Networks"; NumericalAxis primaryAxis52 = new Syncfusion.UI.Xaml.Charts.NumericalAxis(); primaryAxis52.Minimum = 36; primaryAxis52.Maximum = 165; primaryAxis52.Interval = 2; primaryAxis52.IsTextScaleFactorEnabled = true; primaryAxis52.LabelsIntersectAction = AxisLabelsIntersectAction.Hide; primaryAxis.Header = "Channels"; sfChartNetView52.PrimaryAxis = primaryAxis52; NumericalAxis SecondaryNumericalAxis52 = new Syncfusion.UI.Xaml.Charts.NumericalAxis(); SecondaryNumericalAxis52.Header = "Signal Strength"; SecondaryNumericalAxis52.Minimum = -100; SecondaryNumericalAxis52.Maximum = -15; SecondaryNumericalAxis52.Interval = 10; sfChartNetView24.SecondaryAxis = SecondaryNumericalAxis52; ChartSeriesInput = new ObservableCollection<ChartHelperBssidNodeSeries>(); ChartSeriesInput = HelperFunctions.ChartHelper(ResultCollection); foreach (ChartHelperBssidNodeSeries c in ChartSeriesInput) { SplineSeries mySeries = new SplineSeries(); mySeries.ItemsSource = c.Series; mySeries.Label = "Home"; mySeries.XBindingPath = "Channel"; mySeries.YBindingPath = "Rssi"; mySeries.StrokeThickness = 2; //mySeries.EnableAnimation = true; //mySeries.AnimationDuration = System.TimeSpan.FromSeconds(.2); sfChartNetView52.Series.Add(mySeries); } }
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 void FirstAdapter_AvailableNetworksChanged(WiFiAdapter sender, object args) { DisplayNetworkReport(sender.NetworkReport, sender); }
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 Task<bool> ScanNetworks() { ShowProgress = Visibility.Visible; var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { return false; } var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count > 0) { _adapter = await WiFiAdapter.FromIdAsync(result[0].Id); } await _adapter.ScanAsync(); foreach (var network in _adapter.NetworkReport.AvailableNetworks) { Networks.Add(network); } Networks = new ObservableCollection<WiFiAvailableNetwork>(Networks.OrderByDescending(a => a.SignalBars)); var storedNetworks = _setting.GetSetting<WifiNetworkSelectionItem>(SETTINGS.NETWORKS); if (storedNetworks != null) { SelectedNetworks = storedNetworks.Networks; } ShowProgress = Visibility.Collapsed; return true; }