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); }
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); }
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; } } } })); }
private async void btnConnect_Click(object sender, RoutedEventArgs e) { var access = await WiFiAdapter.RequestAccessAsync(); var wifiAdapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); WiFiAdapter wa = await WiFiAdapter.FromIdAsync(wifiAdapterResults[0].Id); WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic; WiFiConnectionResult result; foreach (var availableNetwork in _report.AvailableNetworks) { if (availableNetwork.Ssid == _selectedSSID) { if (txtPassword.Text.Length > 1) { var credential = new PasswordCredential(); credential.Password = txtPassword.Text; result = await wa.ConnectAsync(availableNetwork, reconnectionKind, credential); } else { result = await wa.ConnectAsync(availableNetwork, reconnectionKind); } } } }
private async void MainPage_Loaded(object sender, RoutedEventArgs e) { Loaded -= MainPage_Loaded; Displays.Clear(); var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { Allowed = false; Toast.ShowError("不允许连接wifi,请确认已开启wifi"); } else { var result = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await UpdateConnectivityStatusAsync(); NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; OnRefreshRequested(null, null); } Allowed = true; } }
public NetworkPresenter() { WiFiAdaptersWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); WiFiAdaptersWatcher.EnumerationCompleted += AdaptersEnumCompleted; WiFiAdaptersWatcher.Added += AdaptersAdded; WiFiAdaptersWatcher.Removed += AdaptersRemoved; WiFiAdaptersWatcher.Start(); }
public WiFiInfo(ILogger logger) { this.logger = logger; dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; deviceWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); initialize(); }
private WiFiNetworks() { _wifiAdapterWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); _wifiAdapterWatcher.EnumerationCompleted += AdaptersEnumCompleted; _wifiAdapterWatcher.Added += AdaptersAdded; _wifiAdapterWatcher.Removed += AdaptersRemoved; _wifiAdapterWatcher.Start(); }
/// <summary> /// Gather Network adaptater infos /// </summary> /// <param name="returnedInfo">returned Dictionnary filled with new info</param> /// <returns>Dictionnary<String-String> : network informations</returns> public async override Task <Dictionary <string, string> > GetInfos(Dictionary <String, String> returnedInfo) { returnedInfo = await base.GetInfos(returnedInfo); returnedInfo.Add("------- " + LABEL + " -------", "----------------"); incrementEthernet = 0; incrementUnknow = 0; incrementWifi = 0; increm = 'a'; #if WINDOWS_UWP //Ask permission var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { returnedInfo.Add("Error", "Wifi Acces denied"); } else { //Get the list of Wifi Adaptaters var DeviceswifiAdaptaters = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); WifiAdaptaters = new Dictionary <Guid, WiFiAdapter>(); //Transfer list in a more convenient Dictionnary foreach (WiFiAdapter item in await WiFiAdapter.FindAllAdaptersAsync()) { WifiAdaptaters.Add(item.NetworkAdapter.NetworkAdapterId, item); } //Get the list of network connection var connectedProfiles = NetworkInformation.GetConnectionProfiles().ToList(); //Switch is irrelevant now but can be useful if more specific treatment is needed foreach (var item in NetworkInformation.GetHostNames()) { switch (item.Type) { case HostNameType.DomainName: if (!item.DisplayName.Contains(".local")) { returnedInfo.Add("Machine Name", item.DisplayName); } break; case HostNameType.Ipv4: case HostNameType.Ipv6: case HostNameType.Bluetooth: returnedInfo = await getAdaptaterType(item, returnedInfo); returnedInfo.Add(increm + "- Adress : ", item.DisplayName); returnedInfo.Add(increm + "- Network Type : ", getNetworkType(item)); increment++; increm++; break; } } } #endif return(returnedInfo); }
public async void Start() { try { _iconFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///IoTOnboardingService/icon72x72.png")); var connectionProfiles = NetworkInformation.GetConnectionProfiles(); foreach (var profile in connectionProfiles) { if (profile.IsWlanConnectionProfile) { lock (_stateLock) { _state = OnboardingState.ConfiguredValidated; } break; } } if (_softAccessPoint == null) { _softAccessPoint = new OnboardingAccessPoint(string.Format(_resourceLoader.GetString("SoftApSsidTemplate"), _onboardingInstanceId), _resourceLoader.GetString("SoftApPassword")); } if (_busAttachment == null) { _busAttachment = new AllJoynBusAttachment(); _busAttachment.AboutData.DefaultDescription = string.Format(_resourceLoader.GetString("DefaultDescriptionTemplate"), _onboardingInstanceId); _busAttachment.AboutData.DefaultManufacturer = _resourceLoader.GetString("DefaultManufacturer"); _busAttachment.AboutData.ModelNumber = _resourceLoader.GetString("ModelNumber"); _onboardingProducer = new OnboardingProducer(_busAttachment); _onboardingProducer.Service = this; _iconProducer = new IconProducer(_busAttachment); _iconProducer.Service = this; } if (_deviceWatcher == null) { var accessStatus = await WiFiAdapter.RequestAccessAsync(); if (accessStatus == WiFiAccessStatus.Allowed) { _deviceWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); _deviceWatcher.Added += this.HandleAdapterAdded; _deviceWatcher.Removed += this.HandleAdapterRemoved; _deviceWatcher.Start(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private async Task <WiFiAdapter> GetWifiAdapter() { if (_wifiAdapter != null) { return(_wifiAdapter); } //var accessStatus = await WiFiAdapter.RequestAccessAsync(); var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); _wifiAdapter = await WiFiAdapter.FromIdAsync(devices[0].Id); return(_wifiAdapter); }
/// <summary> /// 异步初始化WiFi适配器 /// </summary> /// <returns>成功与否</returns> private async Task <bool> InitializeWiFiAdapterAsync() { var WiFiAdapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (WiFiAdapterResults.Count >= 1) { WiFi = await WiFiAdapter.FromIdAsync(WiFiAdapterResults.FirstOrDefault().Id); WiFi.AvailableNetworksChanged += WiFi_AvailableNetworksChanged; } else { return(false); } return(true); }
public NetworkPresenter() { // WiFiAdapter.GetDeviceSelector and DeviceInformation.CreateWatcher can throw an exception if the user doesn't grant permission to access the WiFi adapter. try { _wiFiAdaptersWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); _wiFiAdaptersWatcher.EnumerationCompleted += AdaptersEnumCompleted; _wiFiAdaptersWatcher.Added += AdaptersAdded; _wiFiAdaptersWatcher.Removed += AdaptersRemoved; _wiFiAdaptersWatcher.Start(); } catch (Exception ex) { App.LogService.WriteException(ex); } }
public NetworkPresenter() { Log.Enter(); Task.Run(() => { if (TestAccess().Result) { WiFiAdaptersWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); WiFiAdaptersWatcher.EnumerationCompleted += AdaptersEnumCompleted; WiFiAdaptersWatcher.Added += AdaptersAdded; WiFiAdaptersWatcher.Removed += AdaptersRemoved; WiFiAdaptersWatcher.Start(); } }); Log.Leave(); }
private static async Task <WiFiAdapter> FetchWiFiAdapter() { WiFiAdapter wifiAdapter = null; var result = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { try { wifiAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); } catch { } } return(wifiAdapter); }
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."); } } }
// Access private async Task <List <string> > Access() { List <string> devices = new List <string>(); // Request wifi access from the device var access = await WiFiAdapter.RequestAccessAsync(); // Check if access status is allowed if (access == WiFiAccessStatus.Allowed) { // Find all wifi adapters on the equipment var adapters = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (adapters.Count > 0) { foreach (var item in adapters) { devices.Add(item.Id); } } } return(devices); }
private async Task <WiFiAdapter> InitializeFirstAdapter(CancellationToken token) { var access = await WiFiAdapter.RequestAccessAsync().AsTask(token).ConfigureAwait(false); if (access != WiFiAccessStatus.Allowed) { throw new Exception("WiFi Access Status not allowed. Did you add" + "'<DeviceCapability Name=\"wifiControl\" />' to your manifest?"); } var wifiAdapterResults = await DeviceInformation.FindAllAsync( WiFiAdapter.GetDeviceSelector()).AsTask(token).ConfigureAwait(false); if (wifiAdapterResults.Count >= 1) { var deviceId = wifiAdapterResults.FirstOrDefault(r => r.IsDefault || r.IsEnabled); if (deviceId != null) { return(await WiFiAdapter.FromIdAsync(deviceId.Id).AsTask(token).ConfigureAwait(false)); } } throw new Exception("WiFi Adapter not found."); }
public async void InitializeAsync() { Status = WiFiSettingsStatus.Initializing; WiFiNetworks = new ObservableCollection <WiFiNetworkViewModel>(); var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) // Manifest aanpassen! { Status = WiFiSettingsStatus.AccessDenied; OnError?.Invoke(this, new UnauthorizedAccessException("WiFi access not permitted")); return; } var result = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count <= 0)// Werkt alleen met RPI >= 3 { Status = WiFiSettingsStatus.Unavailable; OnError?.Invoke(this, new NotSupportedException("No WiFi adapters detected on this device")); return; } _wifiAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); OnReady?.Invoke(this, EventArgs.Empty); }
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 OnActivated(IActivatedEventArgs args) { Messages parameters = new Messages(); Frame rootFrame = Window.Current.Content as Frame; WiFiAdapter firstAdapter; WiFiConnectionResult result1; ObservableCollection <WiFiNetworkDisplay> ResultCollection = new ObservableCollection <WiFiNetworkDisplay>(); // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(WiFiConfigPage)); } // Ensure the current window is active Window.Current.Activate(); if (args.Kind == ActivationKind.Protocol) { ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs; // Handle URI activation // The received URI is eventArgs.Uri.AbsoluteUri Uri myUri1 = new Uri(eventArgs.Uri.AbsoluteUri); WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(myUri1.Query); String token = decoder.GetFirstValueByName("token"); String identifier = decoder.GetFirstValueByName("identifier"); String Ssid; String password; int numVal = Int32.Parse(identifier); WiFiProfile z = new WiFiProfile(); try { z = await OnboardingService.getInstance().getWiFiProfileAsync(token, identifier); } catch { parameters.Clear(); parameters.Notification = "Cannot get network profile "; parameters.Result = "Net or system error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } Ssid = z.getUser_policies().getSsid(); parameters.Notification = "Start connecting to " + z.getUser_policies().getEap_type() + " network."; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5)); WiFiConfiguration wc = z.getWifiConfiguration(); Window.Current.Activate(); await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync( z.getUser_policies().getPublic_ca(), "", ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "Test"); var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { parameters.Clear(); parameters.Notification = "No WiFi Adapter. Or access is denied!"; parameters.Result = "System error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } else { switch (numVal) { case 2: { //////////////////////////////////////////////////////////////////// //EAP-TTLS var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await firstAdapter.ScanAsync(); var report = firstAdapter.NetworkReport; // var message = string.Format("Network Report Timestamp: { 0}", report.Timestamp); var message = "Find "; ResultCollection.Clear(); foreach (var network in report.AvailableNetworks) { //Format the network information message += string.Format("NetworkName: {0}\n ", network.Ssid); ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter)); } var q = ResultCollection.Where(X => X.Ssid == "ALCATEL1").FirstOrDefault(); if (q == null) { parameters.Clear(); parameters.Notification = "Cannot find network with ssid: " + Ssid; parameters.Result = "Net error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } WiFiNetworkDisplay selectedNetwork = q; WiFiConnectionResult result0; WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211) { result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { var credential = new PasswordCredential(); String Password = z.getUser_policies().getPassword(); String Username = z.getUser_policies().getUsername(); credential.Password = "******"; // Password; credential.UserName = Username; parameters.Clear(); parameters.Notification = message; parameters.Result = string.Format("!!Connecting to {0} ", Ssid); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5)); result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result0.ConnectionStatus == WiFiConnectionStatus.Success) { parameters.Clear(); parameters.Notification = string.Format("Successfully connected to {0}.", selectedNetwork.Ssid); parameters.Result = "Success!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); // refresh the webpage // webViewGrid.Visibility = Visibility.Visible; // toggleBrowserButton.Content = "Hide Browser Control"; // refreshBrowserButton.Visibility = Visibility.Visible; } else { parameters.Clear(); parameters.Result = "Error!"; parameters.Notification = string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result0.ConnectionStatus); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); } } else { parameters.Clear(); parameters.Notification = "No WiFi Adapter. Or access is denied!"; parameters.Result = "System error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } break; } /////////////////////////// case 1: { parameters.Clear(); parameters.Notification = "Not implemented yet"; parameters.Result = "System warning!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); break; } case 3: { parameters.Clear(); parameters.Notification = "Not implemented yet"; parameters.Result = "System waninbg!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); break; } case 4: { //////////////////////////////////////////////////////////////////// //EAP-PEAP var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await firstAdapter.ScanAsync(); var report = firstAdapter.NetworkReport; // var message = string.Format("Network Report Timestamp: { 0}", report.Timestamp); var message = "Find "; ResultCollection.Clear(); foreach (var network in report.AvailableNetworks) { //Format the network information message += string.Format("NetworkName: {0}\n ", network.Ssid); ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter)); } var q = ResultCollection.Where(X => X.Ssid == Ssid).FirstOrDefault(); if (q == null) { parameters.Clear(); parameters.Notification = "Cannot find network with ssid: " + Ssid; parameters.Result = "Net error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } WiFiNetworkDisplay selectedNetwork = q; WiFiConnectionResult result0; WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211) { result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { var credential = new PasswordCredential(); String Password = z.getUser_policies().getPassword(); String Username = z.getUser_policies().getUsername(); credential.Password = Password; credential.UserName = Username; parameters.Clear(); parameters.Notification = message; parameters.Result = string.Format("Connecting to {0} ", Ssid); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5)); result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result0.ConnectionStatus == WiFiConnectionStatus.Success) { parameters.Clear(); parameters.Notification = string.Format("Successfully connected to {0}.", selectedNetwork.Ssid); parameters.Result = "Success!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); // refresh the webpage // webViewGrid.Visibility = Visibility.Visible; // toggleBrowserButton.Content = "Hide Browser Control"; // refreshBrowserButton.Visibility = Visibility.Visible; } else { parameters.Clear(); parameters.Result = "Error!"; parameters.Notification = string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result0.ConnectionStatus); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); } } else { parameters.Clear(); parameters.Notification = "No WiFi Adapter. Or access is denied!"; parameters.Result = "System error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } break; } /////////////////////////// default: { break; } }//switch end } } }
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); } } }
private async Task <bool> _getWifiAdapter() { WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { throw new Exception("WiFiAccessStatus not allowed."); } else { DeviceInformationCollection adapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (adapterResults.Count() >= 1) { _WiFiAdapter = await WiFiAdapter.FromIdAsync(adapterResults[0].Id); } else { throw new Exception("WiFi adapter not found."); } } return(true); }
public async Task <AdaptersStatus> GetWifiAdaptors() { try { if (wiFiaccess == WiFiAccessStatus.Allowed) { var wifiAdaptersColletion = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (wifiAdaptersColletion.Count >= 1) { wifiAdapter = await WiFiAdapter.FromIdAsync(wifiAdaptersColletion[0].Id); return(AdaptersStatus.hasAdapters); } } return(AdaptersStatus.noAdapters); } catch (Exception ex) { Debug.WriteLine("RequestWifiAccess() Exception: " + ex.Message); //return AdaptersStatus.hasAdapters; throw; } }
//Here savedProfileName will have network ssid its connected. //Also connectedProfile.IsWlanConnectionProfile will be true if connected over wifi //connectedProfile.IsWwanConnectionProfile will be true if connected over cellular private async Task GetNet() { var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); if (firstAdapter.NetworkAdapter.GetConnectedProfileAsync() != null) { connectedProfile = await firstAdapter.NetworkAdapter.GetConnectedProfileAsync(); if (connectedProfile != null) //&& !connectedProfile.ProfileName.Equals(savedProfileName) { savedProfileName = connectedProfile.ProfileName; if (connectedProfile.IsWlanConnectionProfile) { nettype = $"Wifi \"{savedProfileName}\""; } if (connectedProfile.IsWwanConnectionProfile) { nettype = "cellular"; } Logger.LogInformation($"Connected to internet: {nettype}. Battery: {GetBattery()}%"); } else { Logger.LogInformation($"No connectedProfile"); } } else { Logger.LogInformation($"No network-profil"); } } else { Logger.LogInformation($"No network-devices"); } }
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); }
public async void Start() { try { _iconFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///IoTOnboardingService/icon72x72.png")); var connectionProfiles = NetworkInformation.GetConnectionProfiles(); foreach (var profile in connectionProfiles) { if (profile.IsWlanConnectionProfile) { lock (_stateLock) { _state = OnboardingState.ConfiguredValidated; } break; } } // read configuration var configResult = await ReadConfig(); if (!configResult.Item1) { // for some reason config file doesn't seem to be OK // => reset config and try another time await ResetConfig(); configResult = await ReadConfig(); if (!configResult.Item1) { throw new System.IO.InvalidDataException("Invalid configuration"); } } _ajOnboardingConfig = configResult.Item2; _softAPConfig = configResult.Item3; bool monitorOk = await MonitorConfigFile(); if (!monitorOk) { throw new System.Exception("Unable to monitor configuration file for changes. Unexpected."); } // If everything is disabled, then there's nothing to do. if ((_softAPConfig.enabled == false) && (_ajOnboardingConfig.enabled == false)) { return; } // create softAP if (_softAccessPoint == null && (_softAPConfig.enabled || _ajOnboardingConfig.enabled)) { // The following builds up an Access Point SSID from information available to the IotOnboarding Task // If AllJoyn is enabled, then we must add AJ_ to the start of the SSID // If a Soft AP SSID value is specified in the configuration settings, then we will add that next // Finally we add the Soft AP's MAC Address to the end. Note that if a device does not have a WiFi adapter, // this _mac value will be a forced to the onboardingDevice ID GUID created the first time this app runs // // Examples: AllJoyn enabled, Wifi: AJ_SoftAPSsid_<MACADDRESS> // AllJoyn disabled, Wifi: SoftAPSsid_<MACADDRESS> // AllJoyn disabled, No Wifi: SoftAPSsid_<8Chars_of_Onboarding_GUID> // // string prefix = ""; string suffix = "_" + _mac; string ssid = ""; if (_ajOnboardingConfig.enabled) { prefix = SOFTAP_SSID_AJONBOARDING_PREFIX; } // SSID examples: AJ_SoftAPSsid_AABBCCDDEEFF ssid = prefix + _softAPConfig.ssid + suffix; _softAccessPoint = new OnboardingAccessPoint(ssid, _softAPConfig.password, _onboardingDeviceId); } // create AllJoyn related things if (_busAttachment == null && _ajOnboardingConfig.enabled) { _busAttachment = new AllJoynBusAttachment(); _busAttachment.AboutData.DefaultDescription = _ajOnboardingConfig.defaultDescription + " MAC: " + _mac; _busAttachment.AboutData.DefaultManufacturer = _ajOnboardingConfig.defaultManufacturer; _busAttachment.AboutData.ModelNumber = _ajOnboardingConfig.modelNumber; _onboardingProducer = new OnboardingProducer(_busAttachment); _onboardingProducer.Service = this; _busAttachment.AuthenticationMechanisms.Clear(); if (_ajOnboardingConfig.presharedKey.Length == 0) { _busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdheNull); } else { _busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdhePsk); } _busAttachment.CredentialsRequested += CredentialsRequested; _busAttachment.CredentialsVerificationRequested += CredentialsVerificationRequested; _busAttachment.AuthenticationComplete += AuthenticationComplete; _iconProducer = new IconProducer(_busAttachment); _iconProducer.Service = this; } if (_deviceWatcher == null) { var accessStatus = await WiFiAdapter.RequestAccessAsync(); if (accessStatus == WiFiAccessStatus.Allowed) { _deviceWatcher = DeviceInformation.CreateWatcher(WiFiAdapter.GetDeviceSelector()); _deviceWatcher.Added += this.HandleAdapterAdded; _deviceWatcher.Removed += this.HandleAdapterRemoved; _deviceWatcher.Start(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
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(); } }
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; } }
/// <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; } }