public async Task <WiFiInfo> ConnectPreferredWifi() { WiFiInfo w = null; var wifiMgr = (WifiManager)context.GetSystemService(Context.WifiService); var formattedSsid = $"\"{preferredWifi}\""; var formattedPassword = $"\"{prefferedWifiPassword}\""; bool wifiEnabled = await SetWifiOn(); if (wifiEnabled) { w = await GetConnectedWifi(true); if (w == null || w.SSID != formattedSsid) { //no wifi is connected or other wifi is connected if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Q) { //Android 10 and later //string bssid = await GetBestBSSID(); string status = await SuggestNetwork(); w = await GetConnectedWifi(true); } else { //Android 9 and earlier var wifiConfig = new WifiConfiguration { Ssid = formattedSsid, PreSharedKey = formattedPassword }; var addNetwork = wifiMgr.AddNetwork(wifiConfig); var network = wifiMgr.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == formattedSsid); if (network == null) { w = null; } else { if (w.SSID != formattedSsid && w.SSID != "<unknown ssid>") { wifiMgr.Disconnect(); } var enableNetwork = wifiMgr.EnableNetwork(network.NetworkId, true); wifiMgr.Reconnect(); } } throw new NoPreferredConnectionException(); } } else { throw new WifiTurnedOffException(); } return(w); }
public override void OnReceive(Context context, Intent intent) { if (intent.Action.Equals(WifiManager.ActionWifiNetworkSuggestionPostConnection)) { //wifi suggestion finished var toast = Toast.MakeText(Application.Context, "Sugestia sieci zakońoczna", ToastLength.Long); toast.Show(); } else { //wifi scan finished IList <ScanResult> scanwifinetworks = wifi.ScanResults; foreach (ScanResult wifinetwork in scanwifinetworks) { bool isConnected = false; if (wifinetwork.Bssid == connectedSSID) { isConnected = true; } WiFiInfo nWF = new WiFiInfo { SSID = wifinetwork.Ssid, BSSID = wifinetwork.Bssid, Signal = wifinetwork.Level, IsConnected = isConnected }; wiFiInfos.Add(nWF); //wifiNetworks.Add(wifinetwork.Ssid); } } receiverARE.Set(); }
public async Task <WiFiInfo> GetConnectedWifi(bool?GetSignalStrength = false) { PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync <LocationPermission>(); if (status != PermissionStatus.Granted) { status = await CrossPermissions.Current.RequestPermissionAsync <LocationPermission>(); } if (status == PermissionStatus.Granted) { WifiManager wifiManager = (WifiManager)(Application.Context.GetSystemService(Context.WifiService)); if (wifiManager != null) { WiFiInfo currentWifi = new WiFiInfo(); currentWifi.SSID = wifiManager.ConnectionInfo.SSID; currentWifi.BSSID = wifiManager.ConnectionInfo.BSSID; currentWifi.NetworkId = wifiManager.ConnectionInfo.NetworkId; if ((bool)GetSignalStrength) { currentWifi.Signal = wifiManager.ConnectionInfo.Rssi; } currentWifi.IsConnected = true; return(currentWifi); } else { return(null); } } else { return(null); } }
public MainPage() { InitializeComponent(); logger = new TextBoxLogger(svLog, TbLog); wiFiInfo = new WiFiInfo(logger); controlPoint = new ControlPoint(logger) { Target = "spatium" }; controlPoint.DeviceDiscovered += DiscoveredCallback; controlPoint.DeviceGone += GoneCallback; rootDevice = new RootDevice(logger) { Target = "spatium", Name = "Spatium device", USN = "123-321", Port = 12345 }; eventTimer = new EventTimer(logger); eventTimer.Tick += async(s, t) => { logger.WriteLine(t.ToString()); IsAvailable.Text = (await wiFiInfo.IsAvailable()).ToString(); IsEnabled.Text = (await wiFiInfo.IsEnabled()).ToString(); IsConnected.Text = (await wiFiInfo.IsConnected()).ToString(); }; Loaded += async(s, e) => { try { HostName localIp = GetLocalIp(); LocalIp.Text = (localIp != null) ? localIp.CanonicalName : "Unknown"; } catch (Exception ex) { LocalIp.Text = "Error"; logger.WriteLine(ex.ToString()); } IsAvailable.Text = (await wiFiInfo.IsAvailable()) ? "Available" : "Unavailable"; IsEnabled.Text = (await wiFiInfo.IsEnabled()) ? "Enabled" : "Disabled"; IsConnected.Text = (await wiFiInfo.IsConnected()) ? "Connected" : "Disconnected"; wiFiInfo.AvailabilityChanged += (s2, a) => IsAvailable.Text = a.Available ? "Available" : "Unavailable"; wiFiInfo.AdapterStatusChanged += (s2, a) => IsEnabled.Text = a.Enabled ? "Enabled" : "Disabled"; wiFiInfo.ConnectionChanged += (s2, a) => IsConnected.Text = a.Connected ? "Connected" : "Disconnected"; }; }
private async void BtnWifiStatus_Clicked(object sender, EventArgs e) { //WiFiInfo wi = await DependencyService.Get<IWifiHandler>().GetConnectedWifi(true); var apiPing = await DependencyService.Get <IWifiHandler>().PingHost(); string pingStatus = $"{Static.Secrets.ServerIp} : "; if (apiPing) { pingStatus += "Dostępny"; } else { pingStatus += "Niedostępny"; } List <WiFiInfo> wis = await DependencyService.Get <IWifiHandler>().GetAvailableWifis(true); if (wis == null) { await DisplayAlert("Odmowa", "Aby sprawdzić nazwę sieci i moc sygnału, potrzebne jest uprawnienie do lokalizacji. Użytkownik odmówił tego uprawnienia. Spróbuj jeszcze raz i przyznaj odpowiednie uprawnienie", "OK"); } else { string status = ""; foreach (WiFiInfo w in wis.OrderByDescending(i => i.Signal)) { string con = ""; if (w.IsConnected) { con = "(P)"; } status += w.SSID + $" [{w.BSSID}] ({w.Signal}){con}, \n"; } WiFiInfo wi = await DependencyService.Get <IWifiHandler>().GetConnectedWifi(); await DisplayAlert("Connection status", $"Podłączona sieć: {wi.SSID} [{wi.BSSID}].\nDostępne sieci: {status}.\nPing: {pingStatus}", "OK"); } }
public static async Task CreateError(Exception ex, string text, string methodName, string className, string additionalInfo = null) { string UserName = string.Empty; string InternetConnectionStatus = ""; string ActiveConnections = ""; if (Connectivity.ConnectionProfiles.Contains(ConnectionProfile.Cellular)) { ActiveConnections += "GSM "; } if (Connectivity.ConnectionProfiles.Contains(ConnectionProfile.WiFi)) { ActiveConnections += "WiFi "; } if (Connectivity.NetworkAccess == NetworkAccess.Internet) { InternetConnectionStatus = "Pełen internet"; } else if (Connectivity.NetworkAccess == NetworkAccess.ConstrainedInternet) { InternetConnectionStatus = "Ograniczone"; } else if (Connectivity.NetworkAccess == NetworkAccess.Local) { InternetConnectionStatus = "Lokalne"; } else if (Connectivity.NetworkAccess == NetworkAccess.None) { InternetConnectionStatus = "Brak"; } else if (Connectivity.NetworkAccess == NetworkAccess.Unknown) { InternetConnectionStatus = "Nieznane"; } else { InternetConnectionStatus = "Tego przypadku powinno nie być... Prawdopodobnie przybyło opcji w Connectivity.NetworkAcces.. Sprawdź Error.cs"; } if (RuntimeSettings.CurrentUser != null) { UserName = RuntimeSettings.CurrentUser.FullName; } string macAddress = await DependencyService.Get <IWifiHandler>().GetWifiMacAddress(); var ApiPing = await DependencyService.Get <IWifiHandler>().PingHost(); string pingStatus = $"{Static.Secrets.ServerIp} : "; if (ApiPing) { pingStatus += "Dostępny"; } else { pingStatus += "Niedostępny"; } WiFiInfo wi = await DependencyService.Get <IWifiHandler>().GetConnectedWifi(); string _additionalInfo = "Brak"; if (additionalInfo != null) { _additionalInfo = additionalInfo; } var properties = new Dictionary <string, string> { { "Type", text }, { "Method", methodName }, { "Class", className }, { "User", UserName }, { "Połączenie internetowe", InternetConnectionStatus }, { "Aktywne połączenia", ActiveConnections }, { "SSID (BSSID) aktywnej sieci", wi.SSID + $"({wi.BSSID})" }, { "Adres MAC", macAddress }, { "Status pingu", pingStatus }, { "Dodatkowe info", _additionalInfo } }; List <WiFiInfo> wis = await DependencyService.Get <IWifiHandler>().GetAvailableWifis(true); if (wis != null) { string[] status = new string[] { "" }; foreach (WiFiInfo w in wis.OrderByDescending(i => i.Signal)) { string con = ""; string bssid = ""; if (w.IsConnected) { con = "(P)"; bssid = $" [{w.BSSID}]"; } if (status[status.Length - 1].Length + bssid.Length + w.SSID.Length + con.Length + 5 > 125) { //create new array's item Array.Resize(ref status, status.Length + 1); } status[status.Length - 1] += w.SSID + $"{bssid} ({w.Signal}){con}, "; } for (int i = 0; i < status.Length; i++) { properties.Add($"Status Wifi {i}", status[i]); } } Crashes.TrackError(ex, properties); }
public static async Task <HttpResponseMessage> GetPostRetryAsync(Func <Task <HttpResponseMessage> > action, TimeSpan sleepPeriod, int tryCount = 3) { int attempted = 0; bool pingable = false; CancellationTokenSource PingCts; CancellationTokenSource actionCts; HttpResponseMessage res = new HttpResponseMessage(); Exception exc; if (tryCount <= 0) { throw new ArgumentOutOfRangeException(nameof(tryCount)); } WiFiInfo w = null; try { w = await DependencyService.Get <IWifiHandler>().ConnectPreferredWifi(); }catch (WifiTurnedOffException ex) { //wifi is off await Application.Current.MainPage.DisplayAlert("Wyłączone WiFi", "Sieć Wifi jest wyłączona. Uruchom Wifi i spróbuj jeszcze raz.", "OK"); throw new WifiTurnedOffException("Sieć Wifi jest wyłączona"); } catch (Exception ex) { } while (true) { try { attempted++; if (attempted > 1) { DependencyService.Get <IToaster>().LongAlert($"Próba {attempted}"); } if (RuntimeSettings.IsVpnConnection) { tryCount = 1; } else { var formattedSsid = $"\"{Static.Secrets.PreferredWifi}\""; if (w != null) { if (w.SSID == formattedSsid) { //tryCount = 1; } } } PingCts = new CancellationTokenSource(); var ping = Task.Run(() => DependencyService.Get <IWifiHandler>().PingHost(), PingCts.Token); actionCts = new CancellationTokenSource(); var resTask = Task.Run(() => action(), actionCts.Token); Task firstFinieshed = await Task.WhenAny(ping, resTask); if (ping.Status == TaskStatus.RanToCompletion) { pingable = await ping; if (!pingable) { actionCts.Cancel(); exc = new ServerUnreachableException(); throw exc; } else { res = await resTask; } } else { PingCts.Cancel(); res = await resTask; } return(res); // success! } catch (Exception ex) { --tryCount; // --tryCount; if (tryCount <= 0) { throw; } await Task.Delay(sleepPeriod); } } }
/// <summary> /// Initializes strings from SystemFunctionTestClass resources /// </summary> /// <param name="APList">WiFi AP list will need to be researched and signal strength SPEC. /// If users configure the WiFi AP list and signal strength SPEC on SFTConfig.xml, this test will be auto-judge pass/fail.</param> public void WifiInformation(string[] APList, int iIfConnection) { string WiFiInfo; string ConnectAPSSID; bool bFlag = false; int APCheckCount = 0; CoreComponent component = null; try { component = new CoreComponent(); if (APList == null) { ConnectAPSSID = null; } else { ConnectAPSSID = APList[0]; } Log.LogComment(DllLog.Log.LogLevel.Info, "The SSID for wifi connection:" + ConnectAPSSID); WiFiInfo = component.TestWiFi(ConnectAPSSID, iIfConnection); if (WiFiInfo.IndexOf("WiFi_Connect_Fail", StringComparison.Ordinal) >= 0) { APCheckCount = 999; Log.LogComment(DllLog.Log.LogLevel.Error, "The SSID for wifi connection status : Fail"); } } finally { if (component != null) { component.Dispose(); component = null; } } char[] tok = new Char[] { '\n', ',' }; string[] split = WiFiInfo.Split(tok, StringSplitOptions.RemoveEmptyEntries); // Query WiFi informarion from Dll. // Parser the scaned AP and signal into array for (int i = 0; i < split.Length; i++) { APScan[iWiFiCount] = split[i]; i++; WifiListSignal[iWiFiCount] = Int32.Parse(split[i].ToString(), CultureInfo.InvariantCulture); iWiFiCount++; } // Add wifi signal amd SSID into dataview object for (int i = 0; i < iWiFiCount; i++) { DataGridViewRowCollection rows = WifiInfoGrid.Rows; rows.Add(new Object[] { WifiListSignal[i], APScan[i] }); Log.LogComment(DllLog.Log.LogLevel.Info, "Signal = " + WifiListSignal[i] + " , SSID = " + APScan[i]); } if (APList != null) { for (int k = 0; k < APList.Length; k++) { for (int i = 0; i < iWiFiCount; i++) { if (APScan[i].IndexOf(APList[k], StringComparison.Ordinal) >= 0 && WifiListSignal[i] > iSignalSpec) { APCheckCount++; bFlag = true; break; } } } if (bFlag && APCheckCount == APList.Length) // All listed AP need to be searched. { Program.ExitApplication(0); } else { Program.ExitApplication(255); } } }
public override object Execute(object arg, IAsyncTaskProgress progress) { SimpleDataSource ds = null; try { var pi = PluginInfo as DataParsePluginInfo; ds = new SimpleDataSource(); ds.Type = typeof(WiFiInfo); ds.Items = new DataItems <WiFiInfo>(pi.SaveDbPath); string file = ""; if (FileHelper.IsValid(pi.SourcePath[0].Local)) { file = pi.SourcePath[0].Local; } else if (FileHelper.IsValid(pi.SourcePath[1].Local)) { file = pi.SourcePath[1].Local; } else if (FileHelper.IsValid(pi.SourcePath[2].Local)) { file = pi.SourcePath[2].Local; } else if (FileHelper.IsValid(pi.SourcePath[3].Local)) { file = pi.SourcePath[3].Local; } string content = FileHelper.FileToUTF8String(file); if (content.IsValid()) { List <WiFiInfo> items = new List <WiFiInfo>(); var groups = content.Split(new string[] { "network" }, StringSplitOptions.RemoveEmptyEntries); int len = groups.Length; if (len <= 1) { return(null); } var ssid = new Regex(@"(?<=\bssid="").*(?=\b"")"); var psk = new Regex(@"(?<=\bpsk="").*(?=\b"")"); var key = new Regex(@"(?<=\bkey_mgmt=)\b.*"); var pri = new Regex(@"(?<=\bpriority=)\d*"); for (int i = 1; i < len; i++) { var id = ssid.Match(groups[i]).Value; if (id.IsValid()) { WiFiInfo item = new WiFiInfo(); item.Name = id; item.Pwd = psk.Match(groups[i]).Value; item.Type = key.Match(groups[i]).Value; item.Priority = pri.Match(groups[i]).Value.ToSafeInt(); items.Add(item); } } ds.Items.AddRange(items); } } catch (System.Exception ex) { Framework.Log4NetService.LoggerManagerSingle.Instance.Error("提取安卓设备WIFI信息数据出错!", ex); } finally { ds?.BuildParent(); } return(ds); }
private async void ConfirmButton_Click(object sender, RoutedEventArgs e) { string Pass = WiFiList[WiFiControl.SelectedIndex].Password; if (Pass != "" && Pass.Length >= 8) { WiFiList[WiFiControl.SelectedIndex].HideMessage(); (WiFiControl.ContainerFromItem(WiFiControl.SelectedItem) as ListViewItem).ContentTemplate = WiFiConnectingState; WiFiInfo Info = WiFiList[WiFiControl.SelectedIndex]; PasswordCredential Credential = new PasswordCredential { Password = Info.Password }; var ConnectResult = await WiFi.ConnectAsync(Info.GetWiFiAvailableNetwork(), Info.AutoConnect?WiFiReconnectionKind.Automatic : WiFiReconnectionKind.Manual, Credential); if (ConnectResult.ConnectionStatus == WiFiConnectionStatus.Success) { foreach (var WiFiInfo in from WiFiInfo in WiFiList where WiFiInfo.IsConnected == true select WiFiInfo) { WiFiInfo.ChangeConnectionStateAsync(false); } Info.HideMessage(); Info.ChangeConnectionStateAsync(true, true); (WiFiControl.ContainerFromItem(WiFiControl.SelectedItem) as ListViewItem).ContentTemplate = WiFiConnectedState; bool IsExist = false; foreach (var WiFiInfo in from WiFiInfo in StoragedWiFiInfoCollection where WiFiInfo.SSID == Info.Name select WiFiInfo) { if (WiFiInfo.Password != Info.Password) { await SQLite.GetInstance().UpdateWiFiDataAsync(Info.Name, Info.Password); } else if (WiFiInfo.Password == Info.Password) { IsExist = true; } if (WiFiInfo.AutoConnect != Info.AutoConnect) { await SQLite.GetInstance().UpdateWiFiDataAsync(Info.Name, Info.AutoConnect); } break; } if (!IsExist) { IsExist = false; StoragedWiFiInfoCollection.Add(new WiFiInDataBase(Info.Name, Info.Password, Info.AutoConnect ? "True" : "False")); await SQLite.GetInstance().SetWiFiDataAsync(Info.Name, Info.Password, Info.AutoConnect); } } else { WiFi.Disconnect(); (WiFiControl.ContainerFromItem(WiFiControl.SelectedItem) as ListViewItem).ContentTemplate = WiFiErrorState; Info.ShowMessage("连接失败"); } //连接完成后重新开始搜索 WiFiScanTimer.Tick += WiFiScanTimer_Tick; WiFiScanTimer.Start(); } else { WiFiList[WiFiControl.SelectedIndex].ShowMessage("密码必须非空且大于8位"); } }