blob: d1e4fdf472c004210f361b19ba0cf39458b043be [file] [log] [blame]
Jason Monkd52356a2015-01-28 10:40:41 -05001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settingslib.wifi;
18
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070019import android.annotation.IntDef;
Sundeep Ghumanbb399912018-01-29 18:31:15 -080020import android.annotation.MainThread;
Sundeep Ghuman271e5de2017-05-30 14:11:39 -070021import android.annotation.Nullable;
Jason Monk6980d122015-06-15 10:07:55 -040022import android.app.AppGlobals;
Jason Monkd52356a2015-01-28 10:40:41 -050023import android.content.Context;
Jason Monk6980d122015-06-15 10:07:55 -040024import android.content.pm.ApplicationInfo;
25import android.content.pm.IPackageManager;
26import android.content.pm.PackageManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070027import android.net.ConnectivityManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070028import android.net.NetworkCapabilities;
Jason Monkd52356a2015-01-28 10:40:41 -050029import android.net.NetworkInfo;
30import android.net.NetworkInfo.DetailedState;
31import android.net.NetworkInfo.State;
Sundeep Ghumana28050a2017-07-12 22:09:25 -070032import android.net.NetworkKey;
Stephen Chen36dd5cf12017-03-20 13:27:51 -070033import android.net.NetworkScoreManager;
34import android.net.NetworkScorerAppData;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080035import android.net.ScoredNetwork;
Sanket Padawe7094d222015-05-01 16:55:00 -070036import android.net.wifi.IWifiManager;
Jason Monkd52356a2015-01-28 10:40:41 -050037import android.net.wifi.ScanResult;
38import android.net.wifi.WifiConfiguration;
39import android.net.wifi.WifiConfiguration.KeyMgmt;
Peter Qiu280581b2017-07-24 14:18:56 -070040import android.net.wifi.WifiEnterpriseConfig;
Jason Monkd52356a2015-01-28 10:40:41 -050041import android.net.wifi.WifiInfo;
42import android.net.wifi.WifiManager;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080043import android.net.wifi.WifiNetworkScoreCache;
Quang Luong9051dfd2018-12-12 12:49:24 -080044import android.net.wifi.hotspot2.OsuProvider;
Peter Qiuced37db2017-03-14 15:51:22 -070045import android.net.wifi.hotspot2.PasspointConfiguration;
Quang Luong4d194842018-12-18 16:59:49 -080046import android.net.wifi.hotspot2.ProvisioningCallback;
Jason Monkd52356a2015-01-28 10:40:41 -050047import android.os.Bundle;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080048import android.os.Parcelable;
Sanket Padawe7094d222015-05-01 16:55:00 -070049import android.os.RemoteException;
50import android.os.ServiceManager;
Mitchell Wills18af4932016-08-10 13:49:21 -070051import android.os.SystemClock;
Jason Monk6980d122015-06-15 10:07:55 -040052import android.os.UserHandle;
Jason Monk6980d122015-06-15 10:07:55 -040053import android.text.TextUtils;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080054import android.util.ArraySet;
Jason Monkd52356a2015-01-28 10:40:41 -050055import android.util.Log;
Quang Luong7cfa5272019-03-08 12:37:15 -080056import android.util.Pair;
Jason Monkd52356a2015-01-28 10:40:41 -050057
Fan Zhangf7802ea2018-08-28 15:15:19 -070058import androidx.annotation.NonNull;
59
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -080060import com.android.internal.annotations.VisibleForTesting;
Quang Luong8123f772019-02-08 16:30:12 -080061import com.android.internal.util.CollectionUtils;
Jason Monkd52356a2015-01-28 10:40:41 -050062import com.android.settingslib.R;
Sundeep Ghumanbb399912018-01-29 18:31:15 -080063import com.android.settingslib.utils.ThreadUtils;
Jason Monkd52356a2015-01-28 10:40:41 -050064
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070065import java.lang.annotation.Retention;
66import java.lang.annotation.RetentionPolicy;
Vinit Deshpandefcd46122015-06-11 18:22:23 -070067import java.util.ArrayList;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080068import java.util.Collection;
Quang Luong7cfa5272019-03-08 12:37:15 -080069import java.util.Collections;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070070import java.util.HashMap;
Mitchell Wills18af4932016-08-10 13:49:21 -070071import java.util.Iterator;
Quang Luong7cfa5272019-03-08 12:37:15 -080072import java.util.List;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070073import java.util.Map;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080074import java.util.Set;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -070075import java.util.concurrent.atomic.AtomicInteger;
Jason Monkd52356a2015-01-28 10:40:41 -050076
Sundeep Ghumanbb399912018-01-29 18:31:15 -080077/**
78 * Represents a selectable Wifi Network for use in various wifi selection menus backed by
79 * {@link WifiTracker}.
80 *
81 * <p>An AccessPoint, which would be more fittingly named "WifiNetwork", is an aggregation of
82 * {@link ScanResult ScanResults} along with pertinent metadata (e.g. current connection info,
83 * network scores) required to successfully render the network to the user.
84 */
Jason Monkd52356a2015-01-28 10:40:41 -050085public class AccessPoint implements Comparable<AccessPoint> {
86 static final String TAG = "SettingsLib.AccessPoint";
87
88 /**
89 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
90 */
91 public static final int LOWER_FREQ_24GHZ = 2400;
92
93 /**
94 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
95 */
96 public static final int HIGHER_FREQ_24GHZ = 2500;
97
98 /**
99 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
100 */
101 public static final int LOWER_FREQ_5GHZ = 4900;
102
103 /**
104 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
105 */
106 public static final int HIGHER_FREQ_5GHZ = 5900;
107
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800108 /** The key which identifies this AccessPoint grouping. */
109 private String mKey;
110
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700111 @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST})
112 @Retention(RetentionPolicy.SOURCE)
113 public @interface Speed {
114 /**
115 * Constant value representing an unlabeled / unscored network.
116 */
117 int NONE = 0;
118 /**
119 * Constant value representing a slow speed network connection.
120 */
121 int SLOW = 5;
122 /**
123 * Constant value representing a medium speed network connection.
124 */
125 int MODERATE = 10;
126 /**
127 * Constant value representing a fast speed network connection.
128 */
129 int FAST = 20;
130 /**
131 * Constant value representing a very fast speed network connection.
132 */
133 int VERY_FAST = 30;
134 }
Jason Monkd52356a2015-01-28 10:40:41 -0500135
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800136 /** The underlying set of scan results comprising this AccessPoint. */
137 private final ArraySet<ScanResult> mScanResults = new ArraySet<>();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700138
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700139 /**
Quang Luong8123f772019-02-08 16:30:12 -0800140 * Extra set of unused scan results corresponding to this AccessPoint for verbose logging
141 * purposes, such as a set of Passpoint roaming scan results when home scans are available.
142 */
143 private final ArraySet<ScanResult> mExtraScanResults = new ArraySet<>();
144
145 /**
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700146 * Map of BSSIDs to scored networks for individual bssids.
147 *
148 * <p>This cache should not be evicted with scan results, as the values here are used to
149 * generate a fallback in the absence of scores for the visible APs.
150 */
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700151 private final Map<String, TimestampedScoredNetwork> mScoredNetworkCache = new HashMap<>();
152
Dave Schaefer98537432017-02-08 11:26:08 -0800153 static final String KEY_NETWORKINFO = "key_networkinfo";
154 static final String KEY_WIFIINFO = "key_wifiinfo";
Dave Schaefer98537432017-02-08 11:26:08 -0800155 static final String KEY_SSID = "key_ssid";
156 static final String KEY_SECURITY = "key_security";
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700157 static final String KEY_SPEED = "key_speed";
Dave Schaefer98537432017-02-08 11:26:08 -0800158 static final String KEY_PSKTYPE = "key_psktype";
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800159 static final String KEY_SCANRESULTS = "key_scanresults";
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700160 static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
Dave Schaefer98537432017-02-08 11:26:08 -0800161 static final String KEY_CONFIG = "key_config";
Peter Qiuced37db2017-03-14 15:51:22 -0700162 static final String KEY_FQDN = "key_fqdn";
163 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
Peter Qiu280581b2017-07-24 14:18:56 -0700164 static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
165 static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
166 static final String KEY_CARRIER_NAME = "key_carrier_name";
Dave Schaefer98537432017-02-08 11:26:08 -0800167 static final AtomicInteger sLastId = new AtomicInteger(0);
Jason Monkd52356a2015-01-28 10:40:41 -0500168
Maurice Lam7cdbe192018-11-13 13:52:50 -0800169 /*
170 * NOTE: These constants for security and PSK types are saved to the bundle in saveWifiState,
171 * and sent across IPC. The numeric values should remain stable, otherwise the changes will need
172 * to be synced with other unbundled users of this library.
Jason Monkd52356a2015-01-28 10:40:41 -0500173 */
174 public static final int SECURITY_NONE = 0;
Hai Shalom9effa642018-11-12 11:43:52 -0800175 public static final int SECURITY_WEP = 1;
176 public static final int SECURITY_PSK = 2;
177 public static final int SECURITY_EAP = 3;
178 public static final int SECURITY_OWE = 4;
179 public static final int SECURITY_SAE = 5;
Hai Shalomaa6f9202018-10-16 14:30:02 -0700180 public static final int SECURITY_EAP_SUITE_B = 6;
Hai Shalom828b13c2018-11-13 16:43:14 -0800181 public static final int SECURITY_MAX_VAL = 7; // Has to be the last
Jason Monkd52356a2015-01-28 10:40:41 -0500182
183 private static final int PSK_UNKNOWN = 0;
184 private static final int PSK_WPA = 1;
185 private static final int PSK_WPA2 = 2;
186 private static final int PSK_WPA_WPA2 = 3;
Hai Shalomc03fc882019-04-08 15:08:19 -0700187 private static final int PSK_SAE = 4;
Jason Monkd52356a2015-01-28 10:40:41 -0500188
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700189 /**
190 * The number of distinct wifi levels.
191 *
192 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
193 */
194 public static final int SIGNAL_LEVELS = 5;
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800195
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700196 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
Dave Schaefer98537432017-02-08 11:26:08 -0800197
Quang Luong9051dfd2018-12-12 12:49:24 -0800198 public static final String KEY_PREFIX_AP = "AP:";
199 public static final String KEY_PREFIX_FQDN = "FQDN:";
200 public static final String KEY_PREFIX_OSU = "OSU:";
201
Jason Monkd52356a2015-01-28 10:40:41 -0500202 private final Context mContext;
203
Quang Luong7cfa5272019-03-08 12:37:15 -0800204 private WifiManager mWifiManager;
205 private WifiManager.ActionListener mConnectListener;
206
Jason Monkd52356a2015-01-28 10:40:41 -0500207 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500208 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500209 private int security;
210 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
211
212 private int pskType = PSK_UNKNOWN;
213
214 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500215
Dave Schaefer98537432017-02-08 11:26:08 -0800216 private int mRssi = UNREACHABLE_RSSI;
Jason Monkd52356a2015-01-28 10:40:41 -0500217
218 private WifiInfo mInfo;
219 private NetworkInfo mNetworkInfo;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700220 AccessPointListener mAccessPointListener;
Jason Monkd52356a2015-01-28 10:40:41 -0500221
222 private Object mTag;
223
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700224 @Speed private int mSpeed = Speed.NONE;
Stephen Chen21f68682017-04-04 13:23:31 -0700225 private boolean mIsScoredNetworkMetered = false;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800226
Peter Qiuced37db2017-03-14 15:51:22 -0700227 /**
228 * Information associated with the {@link PasspointConfiguration}. Only maintaining
229 * the relevant info to preserve spaces.
230 */
231 private String mFqdn;
232 private String mProviderFriendlyName;
Quang Luong8123f772019-02-08 16:30:12 -0800233 private boolean mIsRoaming = false;
Peter Qiuced37db2017-03-14 15:51:22 -0700234
Peter Qiu280581b2017-07-24 14:18:56 -0700235 private boolean mIsCarrierAp = false;
Quang Luong9051dfd2018-12-12 12:49:24 -0800236
237 private OsuProvider mOsuProvider;
Quang Luong8d40a8e2019-01-02 16:25:38 -0800238
239 private String mOsuStatus;
240 private String mOsuFailure;
241 private boolean mOsuProvisioningComplete = false;
242
Peter Qiu280581b2017-07-24 14:18:56 -0700243 /**
244 * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
245 */
246 private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
247 private String mCarrierName = null;
248
Jason Monkd52356a2015-01-28 10:40:41 -0500249 public AccessPoint(Context context, Bundle savedState) {
250 mContext = context;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800251
252 if (savedState.containsKey(KEY_CONFIG)) {
253 mConfig = savedState.getParcelable(KEY_CONFIG);
254 }
Jason Monkd52356a2015-01-28 10:40:41 -0500255 if (mConfig != null) {
256 loadConfig(mConfig);
257 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700258 if (savedState.containsKey(KEY_SSID)) {
259 ssid = savedState.getString(KEY_SSID);
260 }
261 if (savedState.containsKey(KEY_SECURITY)) {
262 security = savedState.getInt(KEY_SECURITY);
263 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700264 if (savedState.containsKey(KEY_SPEED)) {
265 mSpeed = savedState.getInt(KEY_SPEED);
266 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700267 if (savedState.containsKey(KEY_PSKTYPE)) {
268 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500269 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700270 mInfo = savedState.getParcelable(KEY_WIFIINFO);
Jason Monkd52356a2015-01-28 10:40:41 -0500271 if (savedState.containsKey(KEY_NETWORKINFO)) {
272 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
273 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800274 if (savedState.containsKey(KEY_SCANRESULTS)) {
275 Parcelable[] scanResults = savedState.getParcelableArray(KEY_SCANRESULTS);
276 mScanResults.clear();
277 for (Parcelable result : scanResults) {
278 mScanResults.add((ScanResult) result);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700279 }
280 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700281 if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700282 ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700283 savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700284 for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
285 mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700286 }
287 }
Peter Qiuced37db2017-03-14 15:51:22 -0700288 if (savedState.containsKey(KEY_FQDN)) {
289 mFqdn = savedState.getString(KEY_FQDN);
290 }
291 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
292 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
293 }
Peter Qiu280581b2017-07-24 14:18:56 -0700294 if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
295 mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
296 }
297 if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
298 mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
299 }
300 if (savedState.containsKey(KEY_CARRIER_NAME)) {
301 mCarrierName = savedState.getString(KEY_CARRIER_NAME);
302 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700303 update(mConfig, mInfo, mNetworkInfo);
Sundeep Ghumand1e44922017-08-07 11:21:38 -0700304
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800305 // Calculate required fields
306 updateKey();
Quang Luong8123f772019-02-08 16:30:12 -0800307 updateBestRssiInfo();
Jason Monkd52356a2015-01-28 10:40:41 -0500308 }
309
Quang Luong9051dfd2018-12-12 12:49:24 -0800310 /**
311 * Creates an AccessPoint with only a WifiConfiguration. This is used for the saved networks
312 * page.
Quang Luong9051dfd2018-12-12 12:49:24 -0800313 */
Peter Qiuced37db2017-03-14 15:51:22 -0700314 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500315 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700316 loadConfig(config);
Quang Luong6e711c82019-03-07 14:52:55 -0800317 updateKey();
Jason Monkd52356a2015-01-28 10:40:41 -0500318 }
319
Peter Qiuced37db2017-03-14 15:51:22 -0700320 /**
321 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
322 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
323 */
324 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500325 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700326 mFqdn = config.getHomeSp().getFqdn();
327 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Quang Luong6e711c82019-03-07 14:52:55 -0800328 updateKey();
Quang Luong9051dfd2018-12-12 12:49:24 -0800329 }
330
331 /**
Quang Luong8123f772019-02-08 16:30:12 -0800332 * Initialize an AccessPoint object for a Passpoint network.
Quang Luong9051dfd2018-12-12 12:49:24 -0800333 */
Quang Luong8123f772019-02-08 16:30:12 -0800334 public AccessPoint(@NonNull Context context, @NonNull WifiConfiguration config,
335 @Nullable Collection<ScanResult> homeScans,
336 @Nullable Collection<ScanResult> roamingScans) {
337 mContext = context;
338 networkId = config.networkId;
339 mConfig = config;
Quang Luongeafca1b2019-04-15 14:15:25 -0700340 mFqdn = config.FQDN;
Quang Luong8123f772019-02-08 16:30:12 -0800341 setScanResultsPasspoint(homeScans, roamingScans);
342 updateKey();
343 }
344
345 /**
346 * Initialize an AccessPoint object for a Passpoint OSU Provider.
347 */
348 public AccessPoint(@NonNull Context context, @NonNull OsuProvider provider,
349 @NonNull Collection<ScanResult> results) {
Quang Luong9051dfd2018-12-12 12:49:24 -0800350 mContext = context;
351 mOsuProvider = provider;
Quang Luong8123f772019-02-08 16:30:12 -0800352 setScanResults(results);
Quang Luong9051dfd2018-12-12 12:49:24 -0800353 updateKey();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700354 }
355
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800356 AccessPoint(Context context, Collection<ScanResult> results) {
Peter Qiuced37db2017-03-14 15:51:22 -0700357 mContext = context;
Quang Luong8123f772019-02-08 16:30:12 -0800358 setScanResults(results);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800359 updateKey();
Peter Qiuced37db2017-03-14 15:51:22 -0700360 }
361
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800362 @VisibleForTesting void loadConfig(WifiConfiguration config) {
363 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
364 bssid = config.BSSID;
365 security = getSecurity(config);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800366 networkId = config.networkId;
367 mConfig = config;
368 }
369
370 /** Updates {@link #mKey} and should only called upon object creation/initialization. */
371 private void updateKey() {
372 // TODO(sghuman): Consolidate Key logic on ScanResultMatchInfo
Quang Luong7054e922018-12-07 16:44:18 -0800373 if (isPasspoint()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800374 mKey = getKey(mConfig);
Quang Luong6e711c82019-03-07 14:52:55 -0800375 } else if (isPasspointConfig()) {
376 mKey = getKey(mFqdn);
Quang Luong9051dfd2018-12-12 12:49:24 -0800377 } else if (isOsuProvider()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800378 mKey = getKey(mOsuProvider);
Quang Luong9051dfd2018-12-12 12:49:24 -0800379 } else { // Non-Passpoint AP
Quang Luongac1026e2019-01-02 17:37:01 -0800380 mKey = getKey(getSsidStr(), getBssid(), getSecurity());
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800381 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800382 }
383
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700384 /**
Dave Schaefer98537432017-02-08 11:26:08 -0800385 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
386 * equal to, or greater than the other AccessPoint.
387 *
388 * Sort order rules for AccessPoints:
389 * 1. Active before inactive
390 * 2. Reachable before unreachable
391 * 3. Saved before unsaved
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700392 * 4. Network speed value
Dave Schaefer98537432017-02-08 11:26:08 -0800393 * 5. Stronger signal before weaker signal
394 * 6. SSID alphabetically
395 *
396 * Note that AccessPoints with a signal are usually also Reachable,
397 * and will thus appear before unreachable saved AccessPoints.
398 */
Jason Monkd52356a2015-01-28 10:40:41 -0500399 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800400 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500401 // Active one goes first.
402 if (isActive() && !other.isActive()) return -1;
403 if (!isActive() && other.isActive()) return 1;
404
405 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800406 if (isReachable() && !other.isReachable()) return -1;
407 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500408
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800409 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800410 if (isSaved() && !other.isSaved()) return -1;
411 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500412
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700413 // Faster speeds go before slower speeds - but only if visible change in speed label
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700414 if (getSpeed() != other.getSpeed()) {
415 return other.getSpeed() - getSpeed();
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800416 }
417
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800418 // Sort by signal strength, bucketed by level
419 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
420 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500421 if (difference != 0) {
422 return difference;
423 }
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700424
Quang Luong9051dfd2018-12-12 12:49:24 -0800425 // Sort by title.
426 difference = getTitle().compareToIgnoreCase(other.getTitle());
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700427 if (difference != 0) {
428 return difference;
429 }
430
431 // Do a case sensitive comparison to distinguish SSIDs that differ in case only
432 return getSsidStr().compareTo(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500433 }
434
435 @Override
436 public boolean equals(Object other) {
437 if (!(other instanceof AccessPoint)) return false;
438 return (this.compareTo((AccessPoint) other) == 0);
439 }
440
441 @Override
442 public int hashCode() {
443 int result = 0;
444 if (mInfo != null) result += 13 * mInfo.hashCode();
445 result += 19 * mRssi;
446 result += 23 * networkId;
447 result += 29 * ssid.hashCode();
448 return result;
449 }
450
451 @Override
452 public String toString() {
453 StringBuilder builder = new StringBuilder().append("AccessPoint(")
454 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800455 if (bssid != null) {
456 builder.append(":").append(bssid);
457 }
Jason Monkd52356a2015-01-28 10:40:41 -0500458 if (isSaved()) {
459 builder.append(',').append("saved");
460 }
461 if (isActive()) {
462 builder.append(',').append("active");
463 }
464 if (isEphemeral()) {
465 builder.append(',').append("ephemeral");
466 }
467 if (isConnectable()) {
468 builder.append(',').append("connectable");
469 }
Hai Shalomaa6f9202018-10-16 14:30:02 -0700470 if ((security != SECURITY_NONE) && (security != SECURITY_OWE)) {
Jason Monkd52356a2015-01-28 10:40:41 -0500471 builder.append(',').append(securityToString(security, pskType));
472 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800473 builder.append(",level=").append(getLevel());
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700474 if (mSpeed != Speed.NONE) {
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700475 builder.append(",speed=").append(mSpeed);
Sundeep Ghuman8920e9c2017-04-27 16:16:41 -0700476 }
Stephen Chen21f68682017-04-04 13:23:31 -0700477 builder.append(",metered=").append(isMetered());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800478
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800479 if (isVerboseLoggingEnabled()) {
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -0700480 builder.append(",rssi=").append(mRssi);
Quang Luong8123f772019-02-08 16:30:12 -0800481 builder.append(",scan cache size=").append(mScanResults.size()
482 + mExtraScanResults.size());
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -0700483 }
484
Jason Monkd52356a2015-01-28 10:40:41 -0500485 return builder.append(')').toString();
486 }
487
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800488 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700489 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
Stephen Chen21f68682017-04-04 13:23:31 -0700490 * changed.
491 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700492 * @param scoreCache The score cache to use to retrieve scores
493 * @param scoringUiEnabled Whether to show scoring and badging UI
494 * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
495 * generating speed labels
Stephen Chen21f68682017-04-04 13:23:31 -0700496 */
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700497 boolean update(
498 WifiNetworkScoreCache scoreCache,
499 boolean scoringUiEnabled,
500 long maxScoreCacheAgeMillis) {
Stephen Chen21f68682017-04-04 13:23:31 -0700501 boolean scoreChanged = false;
502 if (scoringUiEnabled) {
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700503 scoreChanged = updateScores(scoreCache, maxScoreCacheAgeMillis);
Stephen Chen21f68682017-04-04 13:23:31 -0700504 }
505 return updateMetered(scoreCache) || scoreChanged;
506 }
507
508 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700509 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800510 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700511 * <p>Any cached {@link TimestampedScoredNetwork} objects older than the given max age in millis
512 * will be removed when this method is invoked.
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700513 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700514 * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
515 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700516 * @param scoreCache The score cache to use to retrieve scores
517 * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
518 * generating speed labels
519 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700520 * @return true if the set speed has changed
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800521 */
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700522 private boolean updateScores(WifiNetworkScoreCache scoreCache, long maxScoreCacheAgeMillis) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700523 long nowMillis = SystemClock.elapsedRealtime();
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800524 for (ScanResult result : mScanResults) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700525 ScoredNetwork score = scoreCache.getScoredNetwork(result);
526 if (score == null) {
527 continue;
528 }
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700529 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
530 if (timedScore == null) {
531 mScoredNetworkCache.put(
532 result.BSSID, new TimestampedScoredNetwork(score, nowMillis));
533 } else {
534 // Update data since the has been seen in the score cache
535 timedScore.update(score, nowMillis);
536 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700537 }
538
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700539 // Remove old cached networks
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700540 long evictionCutoff = nowMillis - maxScoreCacheAgeMillis;
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700541 Iterator<TimestampedScoredNetwork> iterator = mScoredNetworkCache.values().iterator();
542 iterator.forEachRemaining(timestampedScoredNetwork -> {
543 if (timestampedScoredNetwork.getUpdatedTimestampMillis() < evictionCutoff) {
544 iterator.remove();
545 }
546 });
547
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700548 return updateSpeed();
549 }
550
551 /**
552 * Updates the internal speed, returning true if the update resulted in a speed label change.
553 */
554 private boolean updateSpeed() {
555 int oldSpeed = mSpeed;
556 mSpeed = generateAverageSpeedForSsid();
557
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700558 boolean changed = oldSpeed != mSpeed;
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800559 if(isVerboseLoggingEnabled() && changed) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700560 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800561 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700562 return changed;
563 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800564
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700565 /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
566 @Speed private int generateAverageSpeedForSsid() {
567 if (mScoredNetworkCache.isEmpty()) {
568 return Speed.NONE;
569 }
570
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700571 if (Log.isLoggable(TAG, Log.DEBUG)) {
572 Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
573 getSsidStr(), mScoredNetworkCache));
574 }
575
Sundeep Ghumana7825692017-08-23 15:53:00 -0700576 // TODO(b/63073866): If flickering issues persist, consider mapping using getLevel rather
577 // than specific rssi value so score doesn't change without a visible wifi bar change. This
578 // issue is likely to be more evident for the active AP whose RSSI value is not half-lifed.
579
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700580 int count = 0;
581 int totalSpeed = 0;
582 for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
583 int speed = timedScore.getScore().calculateBadge(mRssi);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700584 if (speed != Speed.NONE) {
585 count++;
586 totalSpeed += speed;
587 }
588 }
589 int speed = count == 0 ? Speed.NONE : totalSpeed / count;
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800590 if (isVerboseLoggingEnabled()) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700591 Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
592 }
593 return roundToClosestSpeedEnum(speed);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800594 }
595
Stephen Chen21f68682017-04-04 13:23:31 -0700596 /**
597 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
598 * true if the metering changed.
599 */
600 private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
601 boolean oldMetering = mIsScoredNetworkMetered;
602 mIsScoredNetworkMetered = false;
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700603
604 if (isActive() && mInfo != null) {
Eric Schwarzenbach733ea262017-08-08 10:28:21 -0700605 NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700606 ScoredNetwork score = scoreCache.getScoredNetwork(key);
607 if (score != null) {
608 mIsScoredNetworkMetered |= score.meteredHint;
Stephen Chen21f68682017-04-04 13:23:31 -0700609 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700610 } else {
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800611 for (ScanResult result : mScanResults) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700612 ScoredNetwork score = scoreCache.getScoredNetwork(result);
613 if (score == null) {
614 continue;
615 }
616 mIsScoredNetworkMetered |= score.meteredHint;
617 }
Stephen Chen21f68682017-04-04 13:23:31 -0700618 }
619 return oldMetering == mIsScoredNetworkMetered;
620 }
621
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800622 public static String getKey(ScanResult result) {
Quang Luongac1026e2019-01-02 17:37:01 -0800623 return getKey(result.SSID, result.BSSID, getSecurity(result));
Mitchell Wills18af4932016-08-10 13:49:21 -0700624 }
625
Quang Luongac1026e2019-01-02 17:37:01 -0800626 /**
627 * Returns the AccessPoint key for a WifiConfiguration.
628 * This will return a special Passpoint key if the config is for Passpoint.
629 */
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800630 public static String getKey(WifiConfiguration config) {
Quang Luong7054e922018-12-07 16:44:18 -0800631 if (config.isPasspoint()) {
Quang Luong6e711c82019-03-07 14:52:55 -0800632 return getKey(config.FQDN);
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800633 } else {
Quang Luongc2c947c2019-01-18 12:51:35 -0800634 return getKey(removeDoubleQuotes(config.SSID), config.BSSID, getSecurity(config));
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800635 }
Quang Luongac1026e2019-01-02 17:37:01 -0800636 }
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800637
Quang Luongac1026e2019-01-02 17:37:01 -0800638 /**
Quang Luong6e711c82019-03-07 14:52:55 -0800639 * Returns the AccessPoint key corresponding to a Passpoint network by its FQDN.
640 */
641 public static String getKey(String fqdn) {
642 return new StringBuilder()
643 .append(KEY_PREFIX_FQDN)
644 .append(fqdn).toString();
645 }
646
647 /**
Quang Luongac1026e2019-01-02 17:37:01 -0800648 * Returns the AccessPoint key corresponding to the OsuProvider.
649 */
650 public static String getKey(OsuProvider provider) {
651 return new StringBuilder()
652 .append(KEY_PREFIX_OSU)
Quang Luong1a8fece2019-01-11 14:58:14 -0800653 .append(provider.getFriendlyName())
Quang Luongac1026e2019-01-02 17:37:01 -0800654 .append(',')
655 .append(provider.getServerUri()).toString();
656 }
657
658 /**
659 * Returns the AccessPoint key for a normal non-Passpoint network by ssid/bssid and security.
660 */
661 private static String getKey(String ssid, String bssid, int security) {
662 StringBuilder builder = new StringBuilder();
663 builder.append(KEY_PREFIX_AP);
664 if (TextUtils.isEmpty(ssid)) {
665 builder.append(bssid);
666 } else {
667 builder.append(ssid);
668 }
669 builder.append(',').append(security);
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800670 return builder.toString();
671 }
672
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800673 public String getKey() {
674 return mKey;
Jason Monkd52356a2015-01-28 10:40:41 -0500675 }
676
Quang Luongeafca1b2019-04-15 14:15:25 -0700677 /**
678 * Determines if the other AccessPoint represents the same network as this AccessPoint
679 */
680 public boolean matches(AccessPoint other) {
681 return getKey().equals(other.getKey());
682 }
683
Jason Monkd52356a2015-01-28 10:40:41 -0500684 public boolean matches(WifiConfiguration config) {
Quang Luong7054e922018-12-07 16:44:18 -0800685 if (config.isPasspoint()) {
686 return (isPasspoint() && config.FQDN.equals(mConfig.FQDN));
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100687 } else {
Quang Luong7054e922018-12-07 16:44:18 -0800688 // Normal non-Passpoint network
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100689 return ssid.equals(removeDoubleQuotes(config.SSID))
690 && security == getSecurity(config)
691 && (mConfig == null || mConfig.shared == config.shared);
692 }
Jason Monkd52356a2015-01-28 10:40:41 -0500693 }
694
695 public WifiConfiguration getConfig() {
696 return mConfig;
697 }
698
Peter Qiuced37db2017-03-14 15:51:22 -0700699 public String getPasspointFqdn() {
700 return mFqdn;
701 }
702
Jason Monkd52356a2015-01-28 10:40:41 -0500703 public void clearConfig() {
704 mConfig = null;
705 networkId = WifiConfiguration.INVALID_NETWORK_ID;
706 }
707
708 public WifiInfo getInfo() {
709 return mInfo;
710 }
711
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700712 /**
713 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
714 *
715 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
716 * always return at least 0.
717 */
Jason Monkd52356a2015-01-28 10:40:41 -0500718 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800719 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500720 }
721
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700722 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800723 return mRssi;
724 }
725
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800726 /**
727 * Returns the underlying scan result set.
728 *
729 * <p>Callers should not modify this set.
730 */
Quang Luong8123f772019-02-08 16:30:12 -0800731 public Set<ScanResult> getScanResults() {
732 Set<ScanResult> allScans = new ArraySet<>();
733 allScans.addAll(mScanResults);
734 allScans.addAll(mExtraScanResults);
735 return allScans;
736 }
jackqdyulei9ee9b392017-12-22 11:31:49 -0800737
738 public Map<String, TimestampedScoredNetwork> getScoredNetworkCache() {
739 return mScoredNetworkCache;
740 }
741
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800742 /**
Quang Luong8123f772019-02-08 16:30:12 -0800743 * Updates {@link #mRssi} and sets scan result information to that of the best RSSI scan result.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800744 *
745 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
746 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700747 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
748 * value. If the access point is not connected and there are no scan results, the rssi will be
749 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800750 */
Quang Luong8123f772019-02-08 16:30:12 -0800751 private void updateBestRssiInfo() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800752 if (this.isActive()) {
753 return;
754 }
755
Quang Luong8123f772019-02-08 16:30:12 -0800756 ScanResult bestResult = null;
757 int bestRssi = UNREACHABLE_RSSI;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800758 for (ScanResult result : mScanResults) {
Quang Luong8123f772019-02-08 16:30:12 -0800759 if (result.level > bestRssi) {
760 bestRssi = result.level;
761 bestResult = result;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700762 }
763 }
764
Quang Luong8123f772019-02-08 16:30:12 -0800765 // Set the rssi to the average of the current rssi and the previous rssi.
766 if (bestRssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
767 mRssi = (mRssi + bestRssi) / 2;
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700768 } else {
Quang Luong8123f772019-02-08 16:30:12 -0800769 mRssi = bestRssi;
770 }
771
772 if (bestResult != null) {
773 ssid = bestResult.SSID;
774 bssid = bestResult.BSSID;
775 security = getSecurity(bestResult);
Hai Shalomc03fc882019-04-08 15:08:19 -0700776 if (security == SECURITY_PSK || security == SECURITY_SAE) {
Quang Luong8123f772019-02-08 16:30:12 -0800777 pskType = getPskType(bestResult);
778 }
779 mIsCarrierAp = bestResult.isCarrierAp;
780 mCarrierApEapType = bestResult.carrierApEapType;
781 mCarrierName = bestResult.carrierName;
782 }
783 // Update the config SSID of a Passpoint network to that of the best RSSI
784 if (isPasspoint()) {
785 mConfig.SSID = convertToQuotedString(ssid);
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700786 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700787 }
788
Stephen Chen21f68682017-04-04 13:23:31 -0700789 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600790 * Returns if the network should be considered metered.
Stephen Chen21f68682017-04-04 13:23:31 -0700791 */
792 public boolean isMetered() {
793 return mIsScoredNetworkMetered
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600794 || WifiConfiguration.isMetered(mConfig, mInfo);
Stephen Chen21f68682017-04-04 13:23:31 -0700795 }
796
Jason Monkd52356a2015-01-28 10:40:41 -0500797 public NetworkInfo getNetworkInfo() {
798 return mNetworkInfo;
799 }
800
801 public int getSecurity() {
802 return security;
803 }
804
805 public String getSecurityString(boolean concise) {
806 Context context = mContext;
Tomoharu Hatano2bde6e72017-05-30 18:38:56 +0900807 if (isPasspoint() || isPasspointConfig()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700808 return concise ? context.getString(R.string.wifi_security_short_eap) :
809 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700810 }
Jason Monkd52356a2015-01-28 10:40:41 -0500811 switch(security) {
812 case SECURITY_EAP:
813 return concise ? context.getString(R.string.wifi_security_short_eap) :
814 context.getString(R.string.wifi_security_eap);
Hai Shalomaa6f9202018-10-16 14:30:02 -0700815 case SECURITY_EAP_SUITE_B:
816 return concise ? context.getString(R.string.wifi_security_short_eap_suiteb) :
817 context.getString(R.string.wifi_security_eap_suiteb);
Jason Monkd52356a2015-01-28 10:40:41 -0500818 case SECURITY_PSK:
819 switch (pskType) {
820 case PSK_WPA:
821 return concise ? context.getString(R.string.wifi_security_short_wpa) :
822 context.getString(R.string.wifi_security_wpa);
823 case PSK_WPA2:
824 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
825 context.getString(R.string.wifi_security_wpa2);
826 case PSK_WPA_WPA2:
827 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
828 context.getString(R.string.wifi_security_wpa_wpa2);
829 case PSK_UNKNOWN:
830 default:
831 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
832 : context.getString(R.string.wifi_security_psk_generic);
833 }
834 case SECURITY_WEP:
835 return concise ? context.getString(R.string.wifi_security_short_wep) :
836 context.getString(R.string.wifi_security_wep);
Hai Shalomaa6f9202018-10-16 14:30:02 -0700837 case SECURITY_SAE:
Hai Shalomc03fc882019-04-08 15:08:19 -0700838 if (pskType == PSK_SAE) {
839 return concise ? context.getString(R.string.wifi_security_short_psk_sae) :
840 context.getString(R.string.wifi_security_psk_sae);
841 } else {
842 return concise ? context.getString(R.string.wifi_security_short_sae) :
843 context.getString(R.string.wifi_security_sae);
844 }
Hai Shalomaa6f9202018-10-16 14:30:02 -0700845 case SECURITY_OWE:
846 return concise ? context.getString(R.string.wifi_security_short_owe) :
847 context.getString(R.string.wifi_security_owe);
Jason Monkd52356a2015-01-28 10:40:41 -0500848 case SECURITY_NONE:
849 default:
850 return concise ? "" : context.getString(R.string.wifi_security_none);
851 }
852 }
853
Jason Monk6980d122015-06-15 10:07:55 -0400854 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500855 return ssid;
856 }
857
Jason Monk60a82ff2016-02-25 13:55:03 -0500858 public String getBssid() {
859 return bssid;
860 }
861
Jason Monk6980d122015-06-15 10:07:55 -0400862 public CharSequence getSsid() {
pastychanga2998fc2018-06-26 13:37:34 +0800863 return ssid;
Jason Monk6980d122015-06-15 10:07:55 -0400864 }
865
Quang Luong19429e42019-02-20 17:10:51 -0800866 /**
867 * Returns the name associated with the stored config.
868 * @deprecated Please use {@link #getTitle()} instead to get the display name of an AccessPoint.
869 */
870 @Deprecated
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700871 public String getConfigName() {
872 if (mConfig != null && mConfig.isPasspoint()) {
873 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700874 } else if (mFqdn != null) {
875 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700876 } else {
877 return ssid;
878 }
879 }
880
Jason Monkd52356a2015-01-28 10:40:41 -0500881 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700882 if (mNetworkInfo != null) {
883 return mNetworkInfo.getDetailedState();
884 }
885 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
886 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500887 }
888
Peter Qiu280581b2017-07-24 14:18:56 -0700889 public boolean isCarrierAp() {
890 return mIsCarrierAp;
891 }
892
893 public int getCarrierApEapType() {
894 return mCarrierApEapType;
895 }
896
897 public String getCarrierName() {
898 return mCarrierName;
899 }
900
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700901 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700902 WifiConfiguration config = mConfig;
903 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700904 PackageManager pm = mContext.getPackageManager();
905 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700906 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700907 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700908 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700909 appInfo = mContext.getApplicationInfo();
910 } else {
911 try {
912 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700913 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700914 } catch (RemoteException rex) {
915 }
916 }
917 if (appInfo != null &&
918 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
919 !appInfo.packageName.equals(
920 mContext.getString(R.string.certinstaller_package))) {
921 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
922 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700923 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700924 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700925 }
926
Quang Luong7054e922018-12-07 16:44:18 -0800927 /**
928 * Returns the display title for the AccessPoint, such as for an AccessPointPreference's title.
929 */
930 public String getTitle() {
931 if (isPasspoint()) {
932 return mConfig.providerFriendlyName;
Quang Luong19429e42019-02-20 17:10:51 -0800933 } else if (isPasspointConfig()) {
934 return mProviderFriendlyName;
Quang Luong9051dfd2018-12-12 12:49:24 -0800935 } else if (isOsuProvider()) {
936 return mOsuProvider.getFriendlyName();
Quang Luong7054e922018-12-07 16:44:18 -0800937 } else {
938 return getSsidStr();
939 }
940 }
941
Jason Monkd52356a2015-01-28 10:40:41 -0500942 public String getSummary() {
Quang Luong19bae88c2018-12-14 16:05:05 -0800943 return getSettingsSummary();
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700944 }
945
946 public String getSettingsSummary() {
Jason Monkd52356a2015-01-28 10:40:41 -0500947 // Update to new summary
948 StringBuilder summary = new StringBuilder();
949
Quang Luong919d4642019-01-03 14:46:06 -0800950 if (isOsuProvider()) {
951 if (mOsuProvisioningComplete) {
Quang Luongf005c882019-01-29 16:32:03 -0800952 summary.append(mContext.getString(R.string.osu_sign_up_complete));
Quang Luong919d4642019-01-03 14:46:06 -0800953 } else if (mOsuFailure != null) {
954 summary.append(mOsuFailure);
955 } else if (mOsuStatus != null) {
956 summary.append(mOsuStatus);
957 } else {
Quang Luongf005c882019-01-29 16:32:03 -0800958 summary.append(mContext.getString(R.string.tap_to_sign_up));
Quang Luong919d4642019-01-03 14:46:06 -0800959 }
960 } else if (isActive()) {
Quang Luong8123f772019-02-08 16:30:12 -0800961 if (mConfig != null && getDetailedState() == DetailedState.CONNECTED
Quang Luong19bae88c2018-12-14 16:05:05 -0800962 && mIsCarrierAp) {
963 // This is the active connection on a carrier AP
964 summary.append(String.format(mContext.getString(R.string.connected_via_carrier),
965 mCarrierName));
966 } else {
Quang Luong98d06bd2019-01-30 13:42:26 -0800967 summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
Roshan Piuse9b8e502019-01-23 15:42:44 -0800968 mInfo != null && mInfo.isEphemeral(),
969 mInfo != null ? mInfo.getNetworkSuggestionOrSpecifierPackageName() : null));
Jason Monkd52356a2015-01-28 10:40:41 -0500970 }
Quang Luong19bae88c2018-12-14 16:05:05 -0800971 } else { // not active
972 if (mConfig != null && mConfig.hasNoInternetAccess()) {
973 int messageID = mConfig.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
974 ? R.string.wifi_no_internet_no_reconnect
975 : R.string.wifi_no_internet;
976 summary.append(mContext.getString(messageID));
977 } else if (mConfig != null && !mConfig.getNetworkSelectionStatus().isNetworkEnabled()) {
978 WifiConfiguration.NetworkSelectionStatus networkStatus =
979 mConfig.getNetworkSelectionStatus();
980 switch (networkStatus.getNetworkSelectionDisableReason()) {
981 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
982 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
Glen Kuhne446afac2017-06-22 16:02:33 -0700983 break;
Quang Luong19bae88c2018-12-14 16:05:05 -0800984 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
985 summary.append(mContext.getString(R.string.wifi_check_password_try_again));
Glen Kuhne446afac2017-06-22 16:02:33 -0700986 break;
Quang Luong19bae88c2018-12-14 16:05:05 -0800987 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
988 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
989 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
990 break;
991 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
992 summary.append(mContext.getString(R.string.wifi_disabled_generic));
993 break;
994 }
995 } else if (mConfig != null && mConfig.getNetworkSelectionStatus().isNotRecommended()) {
996 summary.append(mContext.getString(
997 R.string.wifi_disabled_by_recommendation_provider));
998 } else if (mIsCarrierAp) {
999 summary.append(String.format(mContext.getString(
1000 R.string.available_via_carrier), mCarrierName));
1001 } else if (!isReachable()) { // Wifi out of range
1002 summary.append(mContext.getString(R.string.wifi_not_in_range));
1003 } else { // In range, not disabled.
1004 if (mConfig != null) { // Is saved network
1005 // Last attempt to connect to this failed. Show reason why
1006 switch (mConfig.recentFailure.getAssociationStatus()) {
1007 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
1008 summary.append(mContext.getString(
1009 R.string.wifi_ap_unable_to_handle_new_sta));
1010 break;
1011 default:
1012 // "Saved"
1013 summary.append(mContext.getString(R.string.wifi_remembered));
1014 break;
1015 }
Glen Kuhne446afac2017-06-22 16:02:33 -07001016 }
Jason Monkd52356a2015-01-28 10:40:41 -05001017 }
1018 }
1019
Quang Luong19bae88c2018-12-14 16:05:05 -08001020
1021
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -08001022 if (isVerboseLoggingEnabled()) {
Quang Luong19bae88c2018-12-14 16:05:05 -08001023 summary.append(WifiUtils.buildLoggingSummary(this, mConfig));
Jason Monkd52356a2015-01-28 10:40:41 -05001024 }
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001025
Quang Luong19bae88c2018-12-14 16:05:05 -08001026 if (mConfig != null && (WifiUtils.isMeteredOverridden(mConfig) || mConfig.meteredHint)) {
Salvador Martinez6f6fe752018-03-21 16:33:53 -07001027 return mContext.getResources().getString(
1028 R.string.preference_summary_default_combination,
Quang Luong19bae88c2018-12-14 16:05:05 -08001029 WifiUtils.getMeteredLabel(mContext, mConfig),
Salvador Martinez6f6fe752018-03-21 16:33:53 -07001030 summary.toString());
1031 }
1032
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -07001033 // If Speed label and summary are both present, use the preference combination to combine
1034 // the two, else return the non-null one.
1035 if (getSpeedLabel() != null && summary.length() != 0) {
Sundeep Ghumand3171ca2017-07-12 23:02:24 -07001036 return mContext.getResources().getString(
1037 R.string.preference_summary_default_combination,
1038 getSpeedLabel(),
1039 summary.toString());
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -07001040 } else if (getSpeedLabel() != null) {
1041 return getSpeedLabel();
Sundeep Ghumand3171ca2017-07-12 23:02:24 -07001042 } else {
1043 return summary.toString();
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001044 }
Jason Monkd52356a2015-01-28 10:40:41 -05001045 }
1046
1047 /**
Jason Monkd52356a2015-01-28 10:40:41 -05001048 * Return whether this is the active connection.
1049 * For ephemeral connections (networkId is invalid), this returns false if the network is
1050 * disconnected.
1051 */
1052 public boolean isActive() {
1053 return mNetworkInfo != null &&
1054 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1055 mNetworkInfo.getState() != State.DISCONNECTED);
1056 }
1057
1058 public boolean isConnectable() {
1059 return getLevel() != -1 && getDetailedState() == null;
1060 }
1061
1062 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001063 return mInfo != null && mInfo.isEphemeral() &&
1064 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -05001065 }
1066
Peter Qiuced37db2017-03-14 15:51:22 -07001067 /**
1068 * Return true if this AccessPoint represents a Passpoint AP.
1069 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001070 public boolean isPasspoint() {
1071 return mConfig != null && mConfig.isPasspoint();
1072 }
1073
Mitchell Wills5a42db22015-08-03 09:46:08 -07001074 /**
Peter Qiuced37db2017-03-14 15:51:22 -07001075 * Return true if this AccessPoint represents a Passpoint provider configuration.
1076 */
1077 public boolean isPasspointConfig() {
1078 return mFqdn != null;
1079 }
1080
1081 /**
Quang Luong9051dfd2018-12-12 12:49:24 -08001082 * Return true if this AccessPoint represents an OSU Provider.
1083 */
1084 public boolean isOsuProvider() {
1085 return mOsuProvider != null;
1086 }
1087
1088 /**
Quang Luong4d194842018-12-18 16:59:49 -08001089 * Starts the OSU Provisioning flow.
1090 */
Quang Luong7cfa5272019-03-08 12:37:15 -08001091 public void startOsuProvisioning(@Nullable WifiManager.ActionListener connectListener) {
1092 mConnectListener = connectListener;
1093
1094 getWifiManager().startSubscriptionProvisioning(
Quang Luong4d194842018-12-18 16:59:49 -08001095 mOsuProvider,
Ecco Parke67533e2019-03-01 15:09:35 -08001096 mContext.getMainExecutor(),
1097 new AccessPointProvisioningCallback()
Quang Luong4d194842018-12-18 16:59:49 -08001098 );
1099 }
1100
1101 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -07001102 * Return whether the given {@link WifiInfo} is for this access point.
1103 * If the current AP does not have a network Id then the config is used to
1104 * match based on SSID and security.
1105 */
1106 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Quang Luong1f1207b2019-02-19 17:35:50 -08001107 if (info.isOsuAp() || mOsuStatus != null) {
1108 return (info.isOsuAp() && mOsuStatus != null);
1109 } else if (info.isPasspointAp() || isPasspoint()) {
1110 return (info.isPasspointAp() && isPasspoint()
Quang Luong2a6cdc52019-03-05 17:35:45 -08001111 && TextUtils.equals(info.getPasspointFqdn(), mConfig.FQDN));
Quang Luong919d4642019-01-03 14:46:06 -08001112 }
1113
Quang Luong1f1207b2019-02-19 17:35:50 -08001114 if (networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -05001115 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001116 } else if (config != null) {
Quang Luong1f1207b2019-02-19 17:35:50 -08001117 return TextUtils.equals(getKey(config), getKey());
1118 } else {
Jason Monkd52356a2015-01-28 10:40:41 -05001119 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1120 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1121 // TODO: Handle hex string SSIDs.
Quang Luong1f1207b2019-02-19 17:35:50 -08001122 return TextUtils.equals(removeDoubleQuotes(info.getSSID()), ssid);
Jason Monkd52356a2015-01-28 10:40:41 -05001123 }
1124 }
1125
1126 public boolean isSaved() {
Quang Luong48ad03a2019-02-14 11:51:01 -08001127 return mConfig != null;
Jason Monkd52356a2015-01-28 10:40:41 -05001128 }
1129
1130 public Object getTag() {
1131 return mTag;
1132 }
1133
1134 public void setTag(Object tag) {
1135 mTag = tag;
1136 }
1137
1138 /**
1139 * Generate and save a default wifiConfiguration with common values.
1140 * Can only be called for unsecured networks.
1141 */
1142 public void generateOpenNetworkConfig() {
Hai Shalomaa6f9202018-10-16 14:30:02 -07001143 if ((security != SECURITY_NONE) && (security != SECURITY_OWE)) {
Jason Monkd52356a2015-01-28 10:40:41 -05001144 throw new IllegalStateException();
Hai Shalomaa6f9202018-10-16 14:30:02 -07001145 }
Jason Monkd52356a2015-01-28 10:40:41 -05001146 if (mConfig != null)
1147 return;
1148 mConfig = new WifiConfiguration();
1149 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
Hai Shalomaa6f9202018-10-16 14:30:02 -07001150
1151 if (security == SECURITY_NONE) {
1152 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1153 } else {
1154 mConfig.allowedKeyManagement.set(KeyMgmt.OWE);
1155 mConfig.requirePMF = true;
1156 }
Jason Monkd52356a2015-01-28 10:40:41 -05001157 }
1158
Jason Monkd52356a2015-01-28 10:40:41 -05001159 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001160 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1161 savedState.putInt(KEY_SECURITY, security);
Sundeep Ghumana28050a2017-07-12 22:09:25 -07001162 savedState.putInt(KEY_SPEED, mSpeed);
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001163 savedState.putInt(KEY_PSKTYPE, pskType);
1164 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -05001165 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001166 savedState.putParcelableArray(KEY_SCANRESULTS,
Quang Luong8123f772019-02-08 16:30:12 -08001167 mScanResults.toArray(new Parcelable[mScanResults.size()
1168 + mExtraScanResults.size()]));
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001169 savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1170 new ArrayList<>(mScoredNetworkCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -05001171 if (mNetworkInfo != null) {
1172 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1173 }
Peter Qiuced37db2017-03-14 15:51:22 -07001174 if (mFqdn != null) {
1175 savedState.putString(KEY_FQDN, mFqdn);
1176 }
1177 if (mProviderFriendlyName != null) {
1178 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1179 }
Peter Qiu280581b2017-07-24 14:18:56 -07001180 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1181 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1182 savedState.putString(KEY_CARRIER_NAME, mCarrierName);
Jason Monkd52356a2015-01-28 10:40:41 -05001183 }
1184
1185 public void setListener(AccessPointListener listener) {
1186 mAccessPointListener = listener;
1187 }
1188
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001189 /**
Quang Luong8123f772019-02-08 16:30:12 -08001190 * Sets {@link #mScanResults} to the given collection and updates info based on the best RSSI
1191 * scan result.
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001192 *
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001193 * @param scanResults a collection of scan results to add to the internal set
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001194 */
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001195 void setScanResults(Collection<ScanResult> scanResults) {
Quang Luong8123f772019-02-08 16:30:12 -08001196 if (CollectionUtils.isEmpty(scanResults)) {
1197 Log.d(TAG, "Cannot set scan results to empty list");
1198 return;
1199 }
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001200
Quang Luong7054e922018-12-07 16:44:18 -08001201 // Validate scan results are for current AP only by matching SSID/BSSID
Quang Luong9051dfd2018-12-12 12:49:24 -08001202 // Passpoint networks are not bound to a specific SSID/BSSID, so skip this for passpoint.
Quang Luong8123f772019-02-08 16:30:12 -08001203 if (mKey != null && !isPasspoint() && !isOsuProvider()) {
Quang Luong7054e922018-12-07 16:44:18 -08001204 for (ScanResult result : scanResults) {
1205 String scanResultKey = AccessPoint.getKey(result);
Quang Luong8123f772019-02-08 16:30:12 -08001206 if (mKey != null && !mKey.equals(scanResultKey)) {
1207 Log.d(TAG, String.format(
Quang Luong7054e922018-12-07 16:44:18 -08001208 "ScanResult %s\nkey of %s did not match current AP key %s",
Quang Luong8123f772019-02-08 16:30:12 -08001209 result, scanResultKey, mKey));
1210 return;
Quang Luong7054e922018-12-07 16:44:18 -08001211 }
Jason Monkd52356a2015-01-28 10:40:41 -05001212 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001213 }
1214
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001215 int oldLevel = getLevel();
1216 mScanResults.clear();
1217 mScanResults.addAll(scanResults);
Quang Luong8123f772019-02-08 16:30:12 -08001218 updateBestRssiInfo();
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001219 int newLevel = getLevel();
1220
1221 // If newLevel is 0, there will be no displayed Preference since the AP is unreachable
1222 if (newLevel > 0 && newLevel != oldLevel) {
1223 // Only update labels on visible rssi changes
1224 updateSpeed();
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001225 ThreadUtils.postOnMainThread(() -> {
1226 if (mAccessPointListener != null) {
1227 mAccessPointListener.onLevelChanged(this);
1228 }
1229 });
1230
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001231 }
1232
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001233 ThreadUtils.postOnMainThread(() -> {
1234 if (mAccessPointListener != null) {
1235 mAccessPointListener.onAccessPointChanged(this);
1236 }
1237 });
Quang Luong8123f772019-02-08 16:30:12 -08001238 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001239
Quang Luong8123f772019-02-08 16:30:12 -08001240 /**
1241 * Sets the internal scan result cache to the list of home scans.
1242 * If there are no home scans, then the roaming scan list is used, and the AccessPoint is
1243 * marked as roaming.
1244 */
1245 void setScanResultsPasspoint(
1246 @Nullable Collection<ScanResult> homeScans,
1247 @Nullable Collection<ScanResult> roamingScans) {
1248 mExtraScanResults.clear();
1249 if (!CollectionUtils.isEmpty(homeScans)) {
1250 if (!CollectionUtils.isEmpty(roamingScans)) {
1251 mExtraScanResults.addAll(roamingScans);
Jason Monkd52356a2015-01-28 10:40:41 -05001252 }
Quang Luong8123f772019-02-08 16:30:12 -08001253 mIsRoaming = false;
1254 setScanResults(homeScans);
1255 } else if (!CollectionUtils.isEmpty(roamingScans)) {
1256 mIsRoaming = true;
1257 setScanResults(roamingScans);
Jason Monkd52356a2015-01-28 10:40:41 -05001258 }
Jason Monkd52356a2015-01-28 10:40:41 -05001259 }
1260
Quang Luong9051dfd2018-12-12 12:49:24 -08001261 /**
1262 * Attempt to update the AccessPoint with the current connection info.
1263 * This is used to set an AccessPoint to the active one if the connection info matches, or
1264 * conversely to set an AccessPoint to inactive if the connection info does not match. The RSSI
1265 * is also updated upon a match. Listeners will be notified if an update occurred.
1266 *
1267 * This is called in {@link WifiTracker#updateAccessPoints} as well as in callbacks for handling
1268 * NETWORK_STATE_CHANGED_ACTION, RSSI_CHANGED_ACTION, and onCapabilitiesChanged in WifiTracker.
1269 *
1270 * Returns true if an update occurred.
1271 */
Sundeep Ghumand911da32017-07-05 20:06:05 -07001272 public boolean update(
1273 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001274 boolean updated = false;
1275 final int oldLevel = getLevel();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001276 if (info != null && isInfoForThisAccessPoint(config, info)) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001277 updated = (mInfo == null);
Quang Luong1f1207b2019-02-19 17:35:50 -08001278 if (!isPasspoint() && mConfig != config) {
Sundeep Ghumanf4d33022017-06-05 19:47:36 -07001279 // We do not set updated = true as we do not want to increase the amount of sorting
1280 // and copying performed in WifiTracker at this time. If issues involving refresh
1281 // are still seen, we will investigate further.
1282 update(config); // Notifies the AccessPointListener of the change
1283 }
Glen Kuhned38708c2017-07-19 14:53:34 -07001284 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001285 mRssi = info.getRssi();
1286 updated = true;
Sundeep Ghuman5c5cd7a2017-05-03 12:45:44 -07001287 } else if (mNetworkInfo != null && networkInfo != null
1288 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
Sundeep Ghuman96a53572017-04-20 21:25:41 -07001289 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001290 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001291 mInfo = info;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001292 mNetworkInfo = networkInfo;
Jason Monkd52356a2015-01-28 10:40:41 -05001293 } else if (mInfo != null) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001294 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001295 mInfo = null;
1296 mNetworkInfo = null;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001297 }
1298 if (updated && mAccessPointListener != null) {
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001299 ThreadUtils.postOnMainThread(() -> {
1300 if (mAccessPointListener != null) {
1301 mAccessPointListener.onAccessPointChanged(this);
1302 }
1303 });
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001304
1305 if (oldLevel != getLevel() /* current level */) {
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001306 ThreadUtils.postOnMainThread(() -> {
1307 if (mAccessPointListener != null) {
1308 mAccessPointListener.onLevelChanged(this);
1309 }
1310 });
Jason Monkd52356a2015-01-28 10:40:41 -05001311 }
1312 }
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -07001313
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001314 return updated;
Jason Monkd52356a2015-01-28 10:40:41 -05001315 }
1316
Sundeep Ghumand911da32017-07-05 20:06:05 -07001317 void update(@Nullable WifiConfiguration config) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001318 mConfig = config;
Quang Luong7054e922018-12-07 16:44:18 -08001319 if (mConfig != null) {
1320 ssid = removeDoubleQuotes(mConfig.SSID);
1321 }
Sundeep Ghumand911da32017-07-05 20:06:05 -07001322 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001323 ThreadUtils.postOnMainThread(() -> {
1324 if (mAccessPointListener != null) {
1325 mAccessPointListener.onAccessPointChanged(this);
1326 }
1327 });
Vinit Deshpandefc406002015-04-15 18:10:55 -07001328 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001329
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001330 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -07001331 void setRssi(int rssi) {
1332 mRssi = rssi;
1333 }
1334
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001335 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1336 void setUnreachable() {
1337 setRssi(AccessPoint.UNREACHABLE_RSSI);
1338 }
1339
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001340 int getSpeed() { return mSpeed;}
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001341
1342 @Nullable
1343 String getSpeedLabel() {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001344 return getSpeedLabel(mSpeed);
1345 }
1346
1347 @Nullable
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001348 @Speed
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001349 private static int roundToClosestSpeedEnum(int speed) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001350 if (speed < Speed.SLOW) {
1351 return Speed.NONE;
1352 } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1353 return Speed.SLOW;
1354 } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1355 return Speed.MODERATE;
1356 } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1357 return Speed.FAST;
1358 } else {
1359 return Speed.VERY_FAST;
1360 }
1361 }
1362
1363 @Nullable
jackqdyulei9ee9b392017-12-22 11:31:49 -08001364 String getSpeedLabel(@Speed int speed) {
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001365 return getSpeedLabel(mContext, speed);
1366 }
1367
1368 private static String getSpeedLabel(Context context, int speed) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001369 switch (speed) {
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001370 case Speed.VERY_FAST:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001371 return context.getString(R.string.speed_label_very_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001372 case Speed.FAST:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001373 return context.getString(R.string.speed_label_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001374 case Speed.MODERATE:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001375 return context.getString(R.string.speed_label_okay);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001376 case Speed.SLOW:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001377 return context.getString(R.string.speed_label_slow);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001378 case Speed.NONE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001379 default:
1380 return null;
1381 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -08001382 }
1383
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001384 /** Return the speed label for a {@link ScoredNetwork} at the specified {@code rssi} level. */
1385 @Nullable
1386 public static String getSpeedLabel(Context context, ScoredNetwork scoredNetwork, int rssi) {
1387 return getSpeedLabel(context, roundToClosestSpeedEnum(scoredNetwork.calculateBadge(rssi)));
1388 }
1389
Dave Schaefer98537432017-02-08 11:26:08 -08001390 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -07001391 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -08001392 return mRssi != UNREACHABLE_RSSI;
1393 }
1394
Roshan Piuse9b8e502019-01-23 15:42:44 -08001395 private static CharSequence getAppLabel(String packageName, PackageManager packageManager) {
1396 CharSequence appLabel = "";
1397 ApplicationInfo appInfo = null;
1398 try {
1399 int userId = UserHandle.getUserId(UserHandle.USER_CURRENT);
1400 appInfo = packageManager.getApplicationInfoAsUser(packageName, 0 /* flags */, userId);
1401 } catch (PackageManager.NameNotFoundException e) {
1402 Log.e(TAG, "Failed to get app info", e);
1403 return appLabel;
1404 }
1405 if (appInfo != null) {
1406 appLabel = appInfo.loadLabel(packageManager);
1407 }
1408 return appLabel;
1409 }
1410
Jason Monkd52356a2015-01-28 10:40:41 -05001411 public static String getSummary(Context context, String ssid, DetailedState state,
Quang Luong98d06bd2019-01-30 13:42:26 -08001412 boolean isEphemeral, String suggestionOrSpecifierPackageName) {
Quang Luong0a3edf02018-12-17 14:50:58 -08001413 if (state == DetailedState.CONNECTED) {
Quang Luong98d06bd2019-01-30 13:42:26 -08001414 if (isEphemeral && !TextUtils.isEmpty(suggestionOrSpecifierPackageName)) {
Roshan Piuse9b8e502019-01-23 15:42:44 -08001415 CharSequence appLabel =
1416 getAppLabel(suggestionOrSpecifierPackageName, context.getPackageManager());
1417 return context.getString(R.string.connected_via_app, appLabel);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001418 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001419 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001420 final NetworkScoreManager networkScoreManager = context.getSystemService(
1421 NetworkScoreManager.class);
1422 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1423 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1424 String format = context.getString(R.string.connected_via_network_scorer);
1425 return String.format(format, scorer.getRecommendationServiceLabel());
1426 } else {
1427 return context.getString(R.string.connected_via_network_scorer_default);
1428 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001429 }
Jason Monkd52356a2015-01-28 10:40:41 -05001430 }
1431
Sanket Padawe7094d222015-05-01 16:55:00 -07001432 // Case when there is wifi connected without internet connectivity.
1433 final ConnectivityManager cm = (ConnectivityManager)
1434 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1435 if (state == DetailedState.CONNECTED) {
1436 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1437 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001438 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001439
1440 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001441 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1442 } catch (RemoteException e) {}
1443
1444 if (nc != null) {
1445 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
Maurice Lam7f6fc862017-07-12 16:43:49 -07001446 int id = context.getResources()
1447 .getIdentifier("network_available_sign_in", "string", "android");
1448 return context.getString(id);
lucaslinfc731ab2019-03-12 17:52:15 +08001449 } else if (nc.hasCapability(
1450 NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
1451 return context.getString(R.string.wifi_limited_connection);
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001452 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1453 return context.getString(R.string.wifi_connected_no_internet);
1454 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001455 }
1456 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001457 if (state == null) {
1458 Log.w(TAG, "state is null, returning empty summary");
1459 return "";
1460 }
Jason Monkd52356a2015-01-28 10:40:41 -05001461 String[] formats = context.getResources().getStringArray((ssid == null)
1462 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1463 int index = state.ordinal();
1464
1465 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001466 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001467 }
1468 return String.format(formats[index], ssid);
1469 }
1470
Jason Monkd52356a2015-01-28 10:40:41 -05001471 public static String convertToQuotedString(String string) {
1472 return "\"" + string + "\"";
1473 }
1474
1475 private static int getPskType(ScanResult result) {
1476 boolean wpa = result.capabilities.contains("WPA-PSK");
Hai Shalome6194252019-04-08 14:07:42 -07001477 boolean wpa2 = result.capabilities.contains("RSN-PSK");
Hai Shalomc03fc882019-04-08 15:08:19 -07001478 boolean wpa3TransitionMode = result.capabilities.contains("PSK+SAE");
1479 boolean wpa3 = result.capabilities.contains("RSN-SAE");
1480 if (wpa3TransitionMode) {
1481 return PSK_SAE;
1482 } else if (wpa2 && wpa) {
Jason Monkd52356a2015-01-28 10:40:41 -05001483 return PSK_WPA_WPA2;
1484 } else if (wpa2) {
1485 return PSK_WPA2;
1486 } else if (wpa) {
1487 return PSK_WPA;
1488 } else {
Hai Shalomc03fc882019-04-08 15:08:19 -07001489 if (!wpa3) {
1490 // Suppress warning for WPA3 only networks
1491 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1492 }
Jason Monkd52356a2015-01-28 10:40:41 -05001493 return PSK_UNKNOWN;
1494 }
1495 }
1496
1497 private static int getSecurity(ScanResult result) {
1498 if (result.capabilities.contains("WEP")) {
1499 return SECURITY_WEP;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001500 } else if (result.capabilities.contains("SAE")) {
1501 return SECURITY_SAE;
Jason Monkd52356a2015-01-28 10:40:41 -05001502 } else if (result.capabilities.contains("PSK")) {
1503 return SECURITY_PSK;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001504 } else if (result.capabilities.contains("EAP_SUITE_B_192")) {
1505 return SECURITY_EAP_SUITE_B;
Jason Monkd52356a2015-01-28 10:40:41 -05001506 } else if (result.capabilities.contains("EAP")) {
1507 return SECURITY_EAP;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001508 } else if (result.capabilities.contains("OWE")) {
1509 return SECURITY_OWE;
Jason Monkd52356a2015-01-28 10:40:41 -05001510 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001511
Jason Monkd52356a2015-01-28 10:40:41 -05001512 return SECURITY_NONE;
1513 }
1514
1515 static int getSecurity(WifiConfiguration config) {
Hai Shalomaa6f9202018-10-16 14:30:02 -07001516 if (config.allowedKeyManagement.get(KeyMgmt.SAE)) {
1517 return SECURITY_SAE;
1518 }
Jason Monkd52356a2015-01-28 10:40:41 -05001519 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1520 return SECURITY_PSK;
1521 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001522 if (config.allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
1523 return SECURITY_EAP_SUITE_B;
1524 }
Jason Monkd52356a2015-01-28 10:40:41 -05001525 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1526 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1527 return SECURITY_EAP;
1528 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001529 if (config.allowedKeyManagement.get(KeyMgmt.OWE)) {
1530 return SECURITY_OWE;
1531 }
Jason Monkd52356a2015-01-28 10:40:41 -05001532 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1533 }
1534
1535 public static String securityToString(int security, int pskType) {
1536 if (security == SECURITY_WEP) {
1537 return "WEP";
1538 } else if (security == SECURITY_PSK) {
1539 if (pskType == PSK_WPA) {
1540 return "WPA";
1541 } else if (pskType == PSK_WPA2) {
1542 return "WPA2";
1543 } else if (pskType == PSK_WPA_WPA2) {
1544 return "WPA_WPA2";
1545 }
1546 return "PSK";
1547 } else if (security == SECURITY_EAP) {
1548 return "EAP";
Hai Shalomaa6f9202018-10-16 14:30:02 -07001549 } else if (security == SECURITY_SAE) {
1550 return "SAE";
1551 } else if (security == SECURITY_EAP_SUITE_B) {
1552 return "SUITE_B";
1553 } else if (security == SECURITY_OWE) {
1554 return "OWE";
Jason Monkd52356a2015-01-28 10:40:41 -05001555 }
1556 return "NONE";
1557 }
1558
1559 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001560 if (TextUtils.isEmpty(string)) {
1561 return "";
1562 }
Jason Monkd52356a2015-01-28 10:40:41 -05001563 int length = string.length();
1564 if ((length > 1) && (string.charAt(0) == '"')
1565 && (string.charAt(length - 1) == '"')) {
1566 return string.substring(1, length - 1);
1567 }
1568 return string;
1569 }
1570
Quang Luong7cfa5272019-03-08 12:37:15 -08001571 private WifiManager getWifiManager() {
1572 if (mWifiManager == null) {
1573 mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
1574 }
1575 return mWifiManager;
1576 }
1577
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001578 /**
1579 * Callbacks relaying changes to the AccessPoint representation.
1580 *
1581 * <p>All methods are invoked on the Main Thread.
1582 */
Jason Monkd52356a2015-01-28 10:40:41 -05001583 public interface AccessPointListener {
Quang Luong7cfa5272019-03-08 12:37:15 -08001584
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001585 /**
1586 * Indicates a change to the externally visible state of the AccessPoint trigger by an
1587 * update of ScanResults, saved configuration state, connection state, or score
1588 * (labels/metered) state.
1589 *
1590 * <p>Clients should refresh their view of the AccessPoint to match the updated state when
1591 * this is invoked. Overall this method is extraneous if clients are listening to
1592 * {@link WifiTracker.WifiListener#onAccessPointsChanged()} callbacks.
1593 *
1594 * <p>Examples of changes include signal strength, connection state, speed label, and
1595 * generally anything that would impact the summary string.
1596 *
1597 * @param accessPoint The accessPoint object the listener was registered on which has
1598 * changed
1599 */
1600 @MainThread void onAccessPointChanged(AccessPoint accessPoint);
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001601 /**
1602 * Indicates the "wifi pie signal level" has changed, retrieved via calls to
1603 * {@link AccessPoint#getLevel()}.
1604 *
1605 * <p>This call is a subset of {@link #onAccessPointChanged(AccessPoint)} , hence is also
1606 * extraneous if the client is already reacting to that or the
1607 * {@link WifiTracker.WifiListener#onAccessPointsChanged()} callbacks.
1608 *
1609 * @param accessPoint The accessPoint object the listener was registered on whose level has
1610 * changed
1611 */
1612 @MainThread void onLevelChanged(AccessPoint accessPoint);
Jason Monkd52356a2015-01-28 10:40:41 -05001613 }
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -08001614
1615 private static boolean isVerboseLoggingEnabled() {
1616 return WifiTracker.sVerboseLogging || Log.isLoggable(TAG, Log.VERBOSE);
1617 }
Quang Luong4d194842018-12-18 16:59:49 -08001618
1619 /**
1620 * Callbacks relaying changes to the OSU provisioning status started in startOsuProvisioning().
1621 *
1622 * All methods are invoked on the Main Thread
1623 */
Quang Luong8123f772019-02-08 16:30:12 -08001624 @VisibleForTesting
1625 class AccessPointProvisioningCallback extends ProvisioningCallback {
Quang Luong4d194842018-12-18 16:59:49 -08001626 @Override
1627 @MainThread public void onProvisioningFailure(int status) {
Quang Luongf005c882019-01-29 16:32:03 -08001628 if (TextUtils.equals(mOsuStatus, mContext.getString(R.string.osu_completing_sign_up))) {
1629 mOsuFailure = mContext.getString(R.string.osu_sign_up_failed);
1630 } else {
1631 mOsuFailure = mContext.getString(R.string.osu_connect_failed);
Quang Luong8d40a8e2019-01-02 16:25:38 -08001632 }
1633 mOsuStatus = null;
1634 mOsuProvisioningComplete = false;
1635 ThreadUtils.postOnMainThread(() -> {
1636 if (mAccessPointListener != null) {
1637 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1638 }
1639 });
Quang Luong4d194842018-12-18 16:59:49 -08001640 }
1641
1642 @Override
1643 @MainThread public void onProvisioningStatus(int status) {
Quang Luongf005c882019-01-29 16:32:03 -08001644 String newStatus = null;
Quang Luong8d40a8e2019-01-02 16:25:38 -08001645 switch (status) {
1646 case OSU_STATUS_AP_CONNECTING:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001647 case OSU_STATUS_AP_CONNECTED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001648 case OSU_STATUS_SERVER_CONNECTING:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001649 case OSU_STATUS_SERVER_VALIDATED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001650 case OSU_STATUS_SERVER_CONNECTED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001651 case OSU_STATUS_INIT_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001652 case OSU_STATUS_WAITING_FOR_REDIRECT_RESPONSE:
Quang Luongf005c882019-01-29 16:32:03 -08001653 newStatus = String.format(mContext.getString(R.string.osu_opening_provider),
1654 mOsuProvider.getFriendlyName());
Quang Luong8d40a8e2019-01-02 16:25:38 -08001655 break;
1656 case OSU_STATUS_REDIRECT_RESPONSE_RECEIVED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001657 case OSU_STATUS_SECOND_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001658 case OSU_STATUS_THIRD_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001659 case OSU_STATUS_RETRIEVING_TRUST_ROOT_CERTS:
Quang Luongf005c882019-01-29 16:32:03 -08001660 newStatus = mContext.getString(
1661 R.string.osu_completing_sign_up);
Quang Luong8d40a8e2019-01-02 16:25:38 -08001662 break;
1663 }
Quang Luongf005c882019-01-29 16:32:03 -08001664 boolean updated = !TextUtils.equals(mOsuStatus, newStatus);
1665 mOsuStatus = newStatus;
Quang Luong8d40a8e2019-01-02 16:25:38 -08001666 mOsuFailure = null;
1667 mOsuProvisioningComplete = false;
Quang Luongf005c882019-01-29 16:32:03 -08001668 if (updated) {
1669 ThreadUtils.postOnMainThread(() -> {
1670 if (mAccessPointListener != null) {
1671 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1672 }
1673 });
1674 }
Quang Luong8d40a8e2019-01-02 16:25:38 -08001675 }
1676
1677 @Override
1678 @MainThread public void onProvisioningComplete() {
1679 mOsuProvisioningComplete = true;
1680 mOsuFailure = null;
1681 mOsuStatus = null;
Quang Luong7cfa5272019-03-08 12:37:15 -08001682
Quang Luong8d40a8e2019-01-02 16:25:38 -08001683 ThreadUtils.postOnMainThread(() -> {
1684 if (mAccessPointListener != null) {
1685 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1686 }
1687 });
Quang Luong7cfa5272019-03-08 12:37:15 -08001688
1689 // Connect to the freshly provisioned network.
1690 WifiManager wifiManager = getWifiManager();
1691
1692 PasspointConfiguration passpointConfig = wifiManager
1693 .getMatchingPasspointConfigsForOsuProviders(Collections.singleton(mOsuProvider))
1694 .get(mOsuProvider);
1695 if (passpointConfig == null) {
1696 Log.e(TAG, "Missing PasspointConfiguration for newly provisioned network!");
1697 if (mConnectListener != null) {
1698 mConnectListener.onFailure(0);
1699 }
1700 return;
1701 }
1702
1703 String fqdn = passpointConfig.getHomeSp().getFqdn();
1704 for (Pair<WifiConfiguration, Map<Integer, List<ScanResult>>> pairing :
1705 wifiManager.getAllMatchingWifiConfigs(wifiManager.getScanResults())) {
1706 WifiConfiguration config = pairing.first;
1707 if (TextUtils.equals(config.FQDN, fqdn)) {
1708 List<ScanResult> homeScans =
1709 pairing.second.get(WifiManager.PASSPOINT_HOME_NETWORK);
1710 List<ScanResult> roamingScans =
1711 pairing.second.get(WifiManager.PASSPOINT_ROAMING_NETWORK);
1712
1713 AccessPoint connectionAp =
1714 new AccessPoint(mContext, config, homeScans, roamingScans);
1715 wifiManager.connect(connectionAp.getConfig(), mConnectListener);
1716 return;
1717 }
1718 }
1719 if (mConnectListener != null) {
1720 mConnectListener.onFailure(0);
1721 }
Quang Luong4d194842018-12-18 16:59:49 -08001722 }
1723 }
Jason Monkd52356a2015-01-28 10:40:41 -05001724}