blob: 1ea4183fc32677a8a176aff736285575e08c9257 [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
Jason Monk6980d122015-06-15 10:07:55 -040019import android.app.AppGlobals;
Jason Monkd52356a2015-01-28 10:40:41 -050020import android.content.Context;
Jason Monk6980d122015-06-15 10:07:55 -040021import android.content.pm.ApplicationInfo;
22import android.content.pm.IPackageManager;
23import android.content.pm.PackageManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070024import android.net.ConnectivityManager;
Sundeep Ghuman699deaf2017-02-13 15:32:13 -080025import android.net.NetworkBadging;
Sanket Padawe7094d222015-05-01 16:55:00 -070026import android.net.NetworkCapabilities;
Jason Monkd52356a2015-01-28 10:40:41 -050027import android.net.NetworkInfo;
28import android.net.NetworkInfo.DetailedState;
29import android.net.NetworkInfo.State;
Stephen Chen36dd5cf12017-03-20 13:27:51 -070030import android.net.NetworkScoreManager;
31import android.net.NetworkScorerAppData;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080032import android.net.ScoredNetwork;
Sanket Padawe7094d222015-05-01 16:55:00 -070033import android.net.wifi.IWifiManager;
Jason Monkd52356a2015-01-28 10:40:41 -050034import android.net.wifi.ScanResult;
35import android.net.wifi.WifiConfiguration;
36import android.net.wifi.WifiConfiguration.KeyMgmt;
37import android.net.wifi.WifiInfo;
38import android.net.wifi.WifiManager;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080039import android.net.wifi.WifiNetworkScoreCache;
Peter Qiuced37db2017-03-14 15:51:22 -070040import android.net.wifi.hotspot2.PasspointConfiguration;
Jason Monkd52356a2015-01-28 10:40:41 -050041import android.os.Bundle;
Sanket Padawe7094d222015-05-01 16:55:00 -070042import android.os.RemoteException;
43import android.os.ServiceManager;
Mitchell Wills18af4932016-08-10 13:49:21 -070044import android.os.SystemClock;
Jason Monk6980d122015-06-15 10:07:55 -040045import android.os.UserHandle;
Tony Mantlera0e03dd2016-01-27 15:57:03 -080046import android.support.annotation.NonNull;
Jason Monk6980d122015-06-15 10:07:55 -040047import android.text.Spannable;
48import android.text.SpannableString;
49import android.text.TextUtils;
50import android.text.style.TtsSpan;
Jason Monkd52356a2015-01-28 10:40:41 -050051import android.util.Log;
Jason Monkd52356a2015-01-28 10:40:41 -050052
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -080053import com.android.internal.annotations.VisibleForTesting;
Jason Monkd52356a2015-01-28 10:40:41 -050054import com.android.settingslib.R;
55
Vinit Deshpandefcd46122015-06-11 18:22:23 -070056import java.util.ArrayList;
Mitchell Wills18af4932016-08-10 13:49:21 -070057import java.util.Iterator;
Mitchell Wills18af4932016-08-10 13:49:21 -070058import java.util.concurrent.ConcurrentHashMap;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -070059import java.util.concurrent.atomic.AtomicInteger;
Jason Monkd52356a2015-01-28 10:40:41 -050060
61
62public class AccessPoint implements Comparable<AccessPoint> {
63 static final String TAG = "SettingsLib.AccessPoint";
64
65 /**
66 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
67 */
68 public static final int LOWER_FREQ_24GHZ = 2400;
69
70 /**
71 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
72 */
73 public static final int HIGHER_FREQ_24GHZ = 2500;
74
75 /**
76 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
77 */
78 public static final int LOWER_FREQ_5GHZ = 4900;
79
80 /**
81 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
82 */
83 public static final int HIGHER_FREQ_5GHZ = 5900;
84
85
86 /**
87 * Experimental: we should be able to show the user the list of BSSIDs and bands
88 * for that SSID.
89 * For now this data is used only with Verbose Logging so as to show the band and number
90 * of BSSIDs on which that network is seen.
91 */
Mitchell Wills18af4932016-08-10 13:49:21 -070092 private final ConcurrentHashMap<String, ScanResult> mScanResultCache =
93 new ConcurrentHashMap<String, ScanResult>(32);
94 private static final long MAX_SCAN_RESULT_AGE_MS = 15000;
Vinit Deshpandefcd46122015-06-11 18:22:23 -070095
Dave Schaefer98537432017-02-08 11:26:08 -080096 static final String KEY_NETWORKINFO = "key_networkinfo";
97 static final String KEY_WIFIINFO = "key_wifiinfo";
98 static final String KEY_SCANRESULT = "key_scanresult";
99 static final String KEY_SSID = "key_ssid";
100 static final String KEY_SECURITY = "key_security";
101 static final String KEY_PSKTYPE = "key_psktype";
102 static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
103 static final String KEY_CONFIG = "key_config";
Peter Qiuced37db2017-03-14 15:51:22 -0700104 static final String KEY_FQDN = "key_fqdn";
105 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
Dave Schaefer98537432017-02-08 11:26:08 -0800106 static final AtomicInteger sLastId = new AtomicInteger(0);
Jason Monkd52356a2015-01-28 10:40:41 -0500107
108 /**
109 * These values are matched in string arrays -- changes must be kept in sync
110 */
111 public static final int SECURITY_NONE = 0;
112 public static final int SECURITY_WEP = 1;
113 public static final int SECURITY_PSK = 2;
114 public static final int SECURITY_EAP = 3;
115
116 private static final int PSK_UNKNOWN = 0;
117 private static final int PSK_WPA = 1;
118 private static final int PSK_WPA2 = 2;
119 private static final int PSK_WPA_WPA2 = 3;
120
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700121 /**
122 * The number of distinct wifi levels.
123 *
124 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
125 */
126 public static final int SIGNAL_LEVELS = 5;
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800127
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700128 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
Dave Schaefer98537432017-02-08 11:26:08 -0800129
Jason Monkd52356a2015-01-28 10:40:41 -0500130 private final Context mContext;
131
132 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500133 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500134 private int security;
135 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
136
137 private int pskType = PSK_UNKNOWN;
138
139 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500140
Dave Schaefer98537432017-02-08 11:26:08 -0800141 private int mRssi = UNREACHABLE_RSSI;
Jason Monkd52356a2015-01-28 10:40:41 -0500142 private long mSeen = 0;
143
144 private WifiInfo mInfo;
145 private NetworkInfo mNetworkInfo;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700146 AccessPointListener mAccessPointListener;
Jason Monkd52356a2015-01-28 10:40:41 -0500147
148 private Object mTag;
149
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800150 private int mRankingScore = Integer.MIN_VALUE;
Sundeep Ghuman699deaf2017-02-13 15:32:13 -0800151 private int mBadge = NetworkBadging.BADGING_NONE;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800152
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700153 // used to co-relate internal vs returned accesspoint.
154 int mId;
155
Peter Qiuced37db2017-03-14 15:51:22 -0700156 /**
157 * Information associated with the {@link PasspointConfiguration}. Only maintaining
158 * the relevant info to preserve spaces.
159 */
160 private String mFqdn;
161 private String mProviderFriendlyName;
162
Jason Monkd52356a2015-01-28 10:40:41 -0500163 public AccessPoint(Context context, Bundle savedState) {
164 mContext = context;
165 mConfig = savedState.getParcelable(KEY_CONFIG);
166 if (mConfig != null) {
167 loadConfig(mConfig);
168 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700169 if (savedState.containsKey(KEY_SSID)) {
170 ssid = savedState.getString(KEY_SSID);
171 }
172 if (savedState.containsKey(KEY_SECURITY)) {
173 security = savedState.getInt(KEY_SECURITY);
174 }
175 if (savedState.containsKey(KEY_PSKTYPE)) {
176 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500177 }
178 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
179 if (savedState.containsKey(KEY_NETWORKINFO)) {
180 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
181 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700182 if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
183 ArrayList<ScanResult> scanResultArrayList =
184 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
Mitchell Wills18af4932016-08-10 13:49:21 -0700185 mScanResultCache.clear();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700186 for (ScanResult result : scanResultArrayList) {
187 mScanResultCache.put(result.BSSID, result);
188 }
189 }
Peter Qiuced37db2017-03-14 15:51:22 -0700190 if (savedState.containsKey(KEY_FQDN)) {
191 mFqdn = savedState.getString(KEY_FQDN);
192 }
193 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
194 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
195 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700196 update(mConfig, mInfo, mNetworkInfo);
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800197 updateRssi();
198 updateSeen();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700199 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500200 }
201
Peter Qiuced37db2017-03-14 15:51:22 -0700202 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500203 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700204 loadConfig(config);
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700205 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500206 }
207
Peter Qiuced37db2017-03-14 15:51:22 -0700208 /**
209 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
210 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
211 */
212 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500213 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700214 mFqdn = config.getHomeSp().getFqdn();
215 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700216 mId = sLastId.incrementAndGet();
217 }
218
219 AccessPoint(Context context, AccessPoint other) {
220 mContext = context;
221 copyFrom(other);
222 }
223
Peter Qiuced37db2017-03-14 15:51:22 -0700224 AccessPoint(Context context, ScanResult result) {
225 mContext = context;
226 initWithScanResult(result);
227 mId = sLastId.incrementAndGet();
228 }
229
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700230 /**
231 * Copy accesspoint information. NOTE: We do not copy tag information because that is never
232 * set on the internal copy.
233 * @param that
234 */
235 void copyFrom(AccessPoint that) {
236 that.evictOldScanResults();
237 this.ssid = that.ssid;
238 this.bssid = that.bssid;
239 this.security = that.security;
240 this.networkId = that.networkId;
241 this.pskType = that.pskType;
242 this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated.
243 this.mRssi = that.mRssi;
244 this.mSeen = that.mSeen;
245 this.mInfo = that.mInfo;
246 this.mNetworkInfo = that.mNetworkInfo;
247 this.mScanResultCache.clear();
248 this.mScanResultCache.putAll(that.mScanResultCache);
249 this.mId = that.mId;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800250 this.mBadge = that.mBadge;
251 this.mRankingScore = that.mRankingScore;
Jason Monkd52356a2015-01-28 10:40:41 -0500252 }
253
Dave Schaefer98537432017-02-08 11:26:08 -0800254 /**
255 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
256 * equal to, or greater than the other AccessPoint.
257 *
258 * Sort order rules for AccessPoints:
259 * 1. Active before inactive
260 * 2. Reachable before unreachable
261 * 3. Saved before unsaved
262 * 4. (Internal only) Network ranking score
263 * 5. Stronger signal before weaker signal
264 * 6. SSID alphabetically
265 *
266 * Note that AccessPoints with a signal are usually also Reachable,
267 * and will thus appear before unreachable saved AccessPoints.
268 */
Jason Monkd52356a2015-01-28 10:40:41 -0500269 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800270 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500271 // Active one goes first.
272 if (isActive() && !other.isActive()) return -1;
273 if (!isActive() && other.isActive()) return 1;
274
275 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800276 if (isReachable() && !other.isReachable()) return -1;
277 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500278
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800279 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800280 if (isSaved() && !other.isSaved()) return -1;
281 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500282
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800283 // Higher scores go before lower scores
Dave Schaefer98537432017-02-08 11:26:08 -0800284 if (getRankingScore() != other.getRankingScore()) {
285 return (getRankingScore() > other.getRankingScore()) ? -1 : 1;
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800286 }
287
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800288 // Sort by signal strength, bucketed by level
289 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
290 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500291 if (difference != 0) {
292 return difference;
293 }
294 // Sort by ssid.
Dave Schaefer98537432017-02-08 11:26:08 -0800295 return getSsidStr().compareToIgnoreCase(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500296 }
297
298 @Override
299 public boolean equals(Object other) {
300 if (!(other instanceof AccessPoint)) return false;
301 return (this.compareTo((AccessPoint) other) == 0);
302 }
303
304 @Override
305 public int hashCode() {
306 int result = 0;
307 if (mInfo != null) result += 13 * mInfo.hashCode();
308 result += 19 * mRssi;
309 result += 23 * networkId;
310 result += 29 * ssid.hashCode();
311 return result;
312 }
313
314 @Override
315 public String toString() {
316 StringBuilder builder = new StringBuilder().append("AccessPoint(")
317 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800318 if (bssid != null) {
319 builder.append(":").append(bssid);
320 }
Jason Monkd52356a2015-01-28 10:40:41 -0500321 if (isSaved()) {
322 builder.append(',').append("saved");
323 }
324 if (isActive()) {
325 builder.append(',').append("active");
326 }
327 if (isEphemeral()) {
328 builder.append(',').append("ephemeral");
329 }
330 if (isConnectable()) {
331 builder.append(',').append("connectable");
332 }
333 if (security != SECURITY_NONE) {
334 builder.append(',').append(securityToString(security, pskType));
335 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800336 builder.append(",level=").append(getLevel());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800337 builder.append(",rankingScore=").append(mRankingScore);
338 builder.append(",badge=").append(mBadge);
339
Jason Monkd52356a2015-01-28 10:40:41 -0500340 return builder.append(')').toString();
341 }
342
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800343 /**
344 * Updates the AccessPoint rankingScore and badge, returning true if the data has changed.
345 *
346 * @param scoreCache The score cache to use to retrieve scores.
347 */
348 boolean updateScores(WifiNetworkScoreCache scoreCache) {
349 int oldBadge = mBadge;
350 int oldRankingScore = mRankingScore;
Sundeep Ghuman699deaf2017-02-13 15:32:13 -0800351 mBadge = NetworkBadging.BADGING_NONE;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800352 mRankingScore = Integer.MIN_VALUE;
353
354 for (ScanResult result : mScanResultCache.values()) {
355 ScoredNetwork score = scoreCache.getScoredNetwork(result);
356 if (score == null) {
357 continue;
358 }
359
360 if (score.hasRankingScore()) {
361 mRankingScore = Math.max(mRankingScore, score.calculateRankingScore(result.level));
362 }
363 mBadge = Math.max(mBadge, score.calculateBadge(result.level));
364 }
365
366 return (oldBadge != mBadge || oldRankingScore != mRankingScore);
367 }
368
Mitchell Wills18af4932016-08-10 13:49:21 -0700369 private void evictOldScanResults() {
370 long nowMs = SystemClock.elapsedRealtime();
371 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
372 ScanResult result = iter.next();
373 // result timestamp is in microseconds
374 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) {
375 iter.remove();
376 }
377 }
378 }
379
Jason Monkd52356a2015-01-28 10:40:41 -0500380 public boolean matches(ScanResult result) {
381 return ssid.equals(result.SSID) && security == getSecurity(result);
382 }
383
384 public boolean matches(WifiConfiguration config) {
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100385 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
Shinji Sogof29e1222015-12-09 17:21:38 +0900386 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100387 } else {
388 return ssid.equals(removeDoubleQuotes(config.SSID))
389 && security == getSecurity(config)
390 && (mConfig == null || mConfig.shared == config.shared);
391 }
Jason Monkd52356a2015-01-28 10:40:41 -0500392 }
393
394 public WifiConfiguration getConfig() {
395 return mConfig;
396 }
397
Peter Qiuced37db2017-03-14 15:51:22 -0700398 public String getPasspointFqdn() {
399 return mFqdn;
400 }
401
Jason Monkd52356a2015-01-28 10:40:41 -0500402 public void clearConfig() {
403 mConfig = null;
404 networkId = WifiConfiguration.INVALID_NETWORK_ID;
405 }
406
407 public WifiInfo getInfo() {
408 return mInfo;
409 }
410
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700411 /**
412 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
413 *
414 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
415 * always return at least 0.
416 */
Jason Monkd52356a2015-01-28 10:40:41 -0500417 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800418 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500419 }
420
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700421 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800422 return mRssi;
423 }
424
425 /**
426 * Updates {@link #mRssi}.
427 *
428 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
429 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700430 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
431 * value. If the access point is not connected and there are no scan results, the rssi will be
432 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800433 *
434 * <p>Old scan results will be evicted from the cache when this method is invoked.
435 */
436 private void updateRssi() {
Mitchell Wills18af4932016-08-10 13:49:21 -0700437 evictOldScanResults();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800438
439 if (this.isActive()) {
440 return;
441 }
442
443 int rssi = UNREACHABLE_RSSI;
Mitchell Wills18af4932016-08-10 13:49:21 -0700444 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700445 if (result.level > rssi) {
446 rssi = result.level;
447 }
448 }
449
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700450 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
451 mRssi = (mRssi + rssi) / 2; // half-life previous value
452 } else {
453 mRssi = rssi;
454 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700455 }
456
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800457 /**
458 * Updates {@link #mSeen} based on the scan result cache.
459 *
460 * <p>Old scan results will be evicted from the cache when this method is invoked.
461 */
462 private void updateSeen() {
Mitchell Wills18af4932016-08-10 13:49:21 -0700463 evictOldScanResults();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800464
465 // TODO(sghuman): Set to now if connected
466
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700467 long seen = 0;
Mitchell Wills18af4932016-08-10 13:49:21 -0700468 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700469 if (result.timestamp > seen) {
470 seen = result.timestamp;
471 }
472 }
473
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800474 mSeen = seen;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700475 }
476
Jason Monkd52356a2015-01-28 10:40:41 -0500477 public NetworkInfo getNetworkInfo() {
478 return mNetworkInfo;
479 }
480
481 public int getSecurity() {
482 return security;
483 }
484
485 public String getSecurityString(boolean concise) {
486 Context context = mContext;
Sanket Padawed1878802015-05-12 10:27:19 -0700487 if (mConfig != null && mConfig.isPasspoint()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700488 return concise ? context.getString(R.string.wifi_security_short_eap) :
489 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700490 }
Jason Monkd52356a2015-01-28 10:40:41 -0500491 switch(security) {
492 case SECURITY_EAP:
493 return concise ? context.getString(R.string.wifi_security_short_eap) :
494 context.getString(R.string.wifi_security_eap);
495 case SECURITY_PSK:
496 switch (pskType) {
497 case PSK_WPA:
498 return concise ? context.getString(R.string.wifi_security_short_wpa) :
499 context.getString(R.string.wifi_security_wpa);
500 case PSK_WPA2:
501 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
502 context.getString(R.string.wifi_security_wpa2);
503 case PSK_WPA_WPA2:
504 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
505 context.getString(R.string.wifi_security_wpa_wpa2);
506 case PSK_UNKNOWN:
507 default:
508 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
509 : context.getString(R.string.wifi_security_psk_generic);
510 }
511 case SECURITY_WEP:
512 return concise ? context.getString(R.string.wifi_security_short_wep) :
513 context.getString(R.string.wifi_security_wep);
514 case SECURITY_NONE:
515 default:
516 return concise ? "" : context.getString(R.string.wifi_security_none);
517 }
518 }
519
Jason Monk6980d122015-06-15 10:07:55 -0400520 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500521 return ssid;
522 }
523
Jason Monk60a82ff2016-02-25 13:55:03 -0500524 public String getBssid() {
525 return bssid;
526 }
527
Jason Monk6980d122015-06-15 10:07:55 -0400528 public CharSequence getSsid() {
Fan Zhangeb83a0d2016-09-21 11:34:08 -0700529 final SpannableString str = new SpannableString(ssid);
530 str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
Jason Monk6980d122015-06-15 10:07:55 -0400531 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
532 return str;
533 }
534
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700535 public String getConfigName() {
536 if (mConfig != null && mConfig.isPasspoint()) {
537 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700538 } else if (mFqdn != null) {
539 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700540 } else {
541 return ssid;
542 }
543 }
544
Jason Monkd52356a2015-01-28 10:40:41 -0500545 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700546 if (mNetworkInfo != null) {
547 return mNetworkInfo.getDetailedState();
548 }
549 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
550 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500551 }
552
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700553 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700554 WifiConfiguration config = mConfig;
555 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700556 PackageManager pm = mContext.getPackageManager();
557 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700558 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700559 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700560 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700561 appInfo = mContext.getApplicationInfo();
562 } else {
563 try {
564 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700565 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700566 } catch (RemoteException rex) {
567 }
568 }
569 if (appInfo != null &&
570 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
571 !appInfo.packageName.equals(
572 mContext.getString(R.string.certinstaller_package))) {
573 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
574 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700575 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700576 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700577 }
578
Jason Monkd52356a2015-01-28 10:40:41 -0500579 public String getSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700580 return getSettingsSummary(mConfig);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700581 }
582
583 public String getSettingsSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700584 return getSettingsSummary(mConfig);
585 }
586
587 private String getSettingsSummary(WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500588 // Update to new summary
589 StringBuilder summary = new StringBuilder();
590
Fan Zhang51365c32016-09-20 12:22:18 -0700591 if (isActive() && config != null && config.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700592 // This is the active connection on passpoint
Jason Monkd52356a2015-01-28 10:40:41 -0500593 summary.append(getSummary(mContext, getDetailedState(),
Fan Zhang51365c32016-09-20 12:22:18 -0700594 false, config.providerFriendlyName));
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700595 } else if (isActive()) {
596 // This is the active connection on non-passpoint network
597 summary.append(getSummary(mContext, getDetailedState(),
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700598 mInfo != null && mInfo.isEphemeral()));
Yuxin Chang6b750862017-01-11 14:59:17 +0900599 } else if (config != null && config.isPasspoint()
600 && config.getNetworkSelectionStatus().isNetworkEnabled()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700601 String format = mContext.getString(R.string.available_via_passpoint);
Fan Zhang51365c32016-09-20 12:22:18 -0700602 summary.append(String.format(format, config.providerFriendlyName));
603 } else if (config != null && config.hasNoInternetAccess()) {
Salvador Martinez5d937fc2016-09-23 08:54:20 -0700604 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
605 ? R.string.wifi_no_internet_no_reconnect
606 : R.string.wifi_no_internet;
607 summary.append(mContext.getString(messageID));
Fan Zhang51365c32016-09-20 12:22:18 -0700608 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
xinhef7705c32015-12-01 14:44:37 -0800609 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700610 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800611 switch (networkStatus.getNetworkSelectionDisableReason()) {
612 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
Jason Monkd52356a2015-01-28 10:40:41 -0500613 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
xinhef7705c32015-12-01 14:44:37 -0800614 break;
615 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
616 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
617 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
618 break;
619 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
620 summary.append(mContext.getString(R.string.wifi_disabled_generic));
621 break;
Jason Monkd52356a2015-01-28 10:40:41 -0500622 }
Amin Shaikh98773d42017-02-02 17:50:12 -0800623 } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
624 summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
Dave Schaefer98537432017-02-08 11:26:08 -0800625 } else if (!isReachable()) { // Wifi out of range
Jason Monkd52356a2015-01-28 10:40:41 -0500626 summary.append(mContext.getString(R.string.wifi_not_in_range));
627 } else { // In range, not disabled.
Fan Zhang51365c32016-09-20 12:22:18 -0700628 if (config != null) { // Is saved network
Jason Monkd52356a2015-01-28 10:40:41 -0500629 summary.append(mContext.getString(R.string.wifi_remembered));
630 }
631 }
632
633 if (WifiTracker.sVerboseLogging > 0) {
634 // Add RSSI/band information for this config, what was seen up to 6 seconds ago
635 // verbose WiFi Logging is only turned on thru developers settings
636 if (mInfo != null && mNetworkInfo != null) { // This is the active connection
637 summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
638 }
639 summary.append(" " + getVisibilityStatus());
Fan Zhang51365c32016-09-20 12:22:18 -0700640 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
641 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
642 if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
Jason Monkd52356a2015-01-28 10:40:41 -0500643 long now = System.currentTimeMillis();
Fan Zhang51365c32016-09-20 12:22:18 -0700644 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
Jason Monkd52356a2015-01-28 10:40:41 -0500645 long sec = diff%60; //seconds
646 long min = (diff/60)%60; //minutes
647 long hour = (min/60)%60; //hours
648 summary.append(", ");
649 if (hour > 0) summary.append(Long.toString(hour) + "h ");
650 summary.append( Long.toString(min) + "m ");
651 summary.append( Long.toString(sec) + "s ");
652 }
653 summary.append(")");
654 }
xinhef7705c32015-12-01 14:44:37 -0800655
Fan Zhang51365c32016-09-20 12:22:18 -0700656 if (config != null) {
xinhef7705c32015-12-01 14:44:37 -0800657 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700658 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800659 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
660 index < WifiConfiguration.NetworkSelectionStatus
661 .NETWORK_SELECTION_DISABLED_MAX; index++) {
662 if (networkStatus.getDisableReasonCounter(index) != 0) {
663 summary.append(" " + WifiConfiguration.NetworkSelectionStatus
664 .getNetworkDisableReasonString(index) + "="
665 + networkStatus.getDisableReasonCounter(index));
666 }
667 }
Jason Monkd52356a2015-01-28 10:40:41 -0500668 }
669 }
670 return summary.toString();
671 }
672
673 /**
674 * Returns the visibility status of the WifiConfiguration.
675 *
676 * @return autojoin debugging information
677 * TODO: use a string formatter
678 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
679 * For instance [-40,5/-30,2]
680 */
681 private String getVisibilityStatus() {
682 StringBuilder visibility = new StringBuilder();
683 StringBuilder scans24GHz = null;
684 StringBuilder scans5GHz = null;
685 String bssid = null;
686
687 long now = System.currentTimeMillis();
688
689 if (mInfo != null) {
690 bssid = mInfo.getBSSID();
691 if (bssid != null) {
692 visibility.append(" ").append(bssid);
693 }
694 visibility.append(" rssi=").append(mInfo.getRssi());
695 visibility.append(" ");
696 visibility.append(" score=").append(mInfo.score);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800697 visibility.append(" rankingScore=").append(getRankingScore());
698 visibility.append(" badge=").append(getBadge());
Jason Monkd52356a2015-01-28 10:40:41 -0500699 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
700 visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
701 visibility.append(String.format("%.1f ", mInfo.txBadRate));
702 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
703 }
704
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700705 int rssi5 = WifiConfiguration.INVALID_RSSI;
706 int rssi24 = WifiConfiguration.INVALID_RSSI;
707 int num5 = 0;
708 int num24 = 0;
709 int numBlackListed = 0;
710 int n24 = 0; // Number scan results we included in the string
711 int n5 = 0; // Number scan results we included in the string
Mitchell Wills18af4932016-08-10 13:49:21 -0700712 evictOldScanResults();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700713 // TODO: sort list by RSSI or age
Mitchell Wills18af4932016-08-10 13:49:21 -0700714 for (ScanResult result : mScanResultCache.values()) {
Jason Monkd52356a2015-01-28 10:40:41 -0500715
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700716 if (result.frequency >= LOWER_FREQ_5GHZ
717 && result.frequency <= HIGHER_FREQ_5GHZ) {
718 // Strictly speaking: [4915, 5825]
719 // number of known BSSID on 5GHz band
720 num5 = num5 + 1;
721 } else if (result.frequency >= LOWER_FREQ_24GHZ
722 && result.frequency <= HIGHER_FREQ_24GHZ) {
723 // Strictly speaking: [2412, 2482]
724 // number of known BSSID on 2.4Ghz band
725 num24 = num24 + 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500726 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700727
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700728
729 if (result.frequency >= LOWER_FREQ_5GHZ
730 && result.frequency <= HIGHER_FREQ_5GHZ) {
731 if (result.level > rssi5) {
732 rssi5 = result.level;
Jason Monkd52356a2015-01-28 10:40:41 -0500733 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700734 if (n5 < 4) {
735 if (scans5GHz == null) scans5GHz = new StringBuilder();
736 scans5GHz.append(" \n{").append(result.BSSID);
737 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
738 scans5GHz.append("=").append(result.frequency);
739 scans5GHz.append(",").append(result.level);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700740 scans5GHz.append("}");
741 n5++;
Jason Monkd52356a2015-01-28 10:40:41 -0500742 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700743 } else if (result.frequency >= LOWER_FREQ_24GHZ
744 && result.frequency <= HIGHER_FREQ_24GHZ) {
745 if (result.level > rssi24) {
746 rssi24 = result.level;
747 }
748 if (n24 < 4) {
749 if (scans24GHz == null) scans24GHz = new StringBuilder();
750 scans24GHz.append(" \n{").append(result.BSSID);
751 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
752 scans24GHz.append("=").append(result.frequency);
753 scans24GHz.append(",").append(result.level);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700754 scans24GHz.append("}");
755 n24++;
Jason Monkd52356a2015-01-28 10:40:41 -0500756 }
757 }
758 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700759 visibility.append(" [");
760 if (num24 > 0) {
761 visibility.append("(").append(num24).append(")");
762 if (n24 <= 4) {
763 if (scans24GHz != null) {
764 visibility.append(scans24GHz.toString());
765 }
766 } else {
767 visibility.append("max=").append(rssi24);
768 if (scans24GHz != null) {
769 visibility.append(",").append(scans24GHz.toString());
770 }
771 }
772 }
773 visibility.append(";");
774 if (num5 > 0) {
775 visibility.append("(").append(num5).append(")");
776 if (n5 <= 4) {
777 if (scans5GHz != null) {
778 visibility.append(scans5GHz.toString());
779 }
780 } else {
781 visibility.append("max=").append(rssi5);
782 if (scans5GHz != null) {
783 visibility.append(",").append(scans5GHz.toString());
784 }
785 }
786 }
787 if (numBlackListed > 0)
788 visibility.append("!").append(numBlackListed);
789 visibility.append("]");
Jason Monkd52356a2015-01-28 10:40:41 -0500790
791 return visibility.toString();
792 }
793
794 /**
795 * Return whether this is the active connection.
796 * For ephemeral connections (networkId is invalid), this returns false if the network is
797 * disconnected.
798 */
799 public boolean isActive() {
800 return mNetworkInfo != null &&
801 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
802 mNetworkInfo.getState() != State.DISCONNECTED);
803 }
804
805 public boolean isConnectable() {
806 return getLevel() != -1 && getDetailedState() == null;
807 }
808
809 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700810 return mInfo != null && mInfo.isEphemeral() &&
811 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -0500812 }
813
Peter Qiuced37db2017-03-14 15:51:22 -0700814 /**
815 * Return true if this AccessPoint represents a Passpoint AP.
816 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -0700817 public boolean isPasspoint() {
818 return mConfig != null && mConfig.isPasspoint();
819 }
820
Mitchell Wills5a42db22015-08-03 09:46:08 -0700821 /**
Peter Qiuced37db2017-03-14 15:51:22 -0700822 * Return true if this AccessPoint represents a Passpoint provider configuration.
823 */
824 public boolean isPasspointConfig() {
825 return mFqdn != null;
826 }
827
828 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -0700829 * Return whether the given {@link WifiInfo} is for this access point.
830 * If the current AP does not have a network Id then the config is used to
831 * match based on SSID and security.
832 */
833 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Vinit Deshpande5b7352c2015-07-09 16:53:12 -0700834 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -0500835 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -0700836 } else if (config != null) {
837 return matches(config);
838 }
839 else {
Jason Monkd52356a2015-01-28 10:40:41 -0500840 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
841 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
842 // TODO: Handle hex string SSIDs.
843 return ssid.equals(removeDoubleQuotes(info.getSSID()));
844 }
845 }
846
847 public boolean isSaved() {
848 return networkId != WifiConfiguration.INVALID_NETWORK_ID;
849 }
850
851 public Object getTag() {
852 return mTag;
853 }
854
855 public void setTag(Object tag) {
856 mTag = tag;
857 }
858
859 /**
860 * Generate and save a default wifiConfiguration with common values.
861 * Can only be called for unsecured networks.
862 */
863 public void generateOpenNetworkConfig() {
864 if (security != SECURITY_NONE)
865 throw new IllegalStateException();
866 if (mConfig != null)
867 return;
868 mConfig = new WifiConfiguration();
869 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
870 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
871 }
872
873 void loadConfig(WifiConfiguration config) {
Peter Qiu2c3b5ee22017-02-01 11:49:15 -0800874 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
Jason Monk60a82ff2016-02-25 13:55:03 -0500875 bssid = config.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -0500876 security = getSecurity(config);
877 networkId = config.networkId;
878 mConfig = config;
879 }
880
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700881 private void initWithScanResult(ScanResult result) {
Jason Monkd52356a2015-01-28 10:40:41 -0500882 ssid = result.SSID;
Jason Monk60a82ff2016-02-25 13:55:03 -0500883 bssid = result.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -0500884 security = getSecurity(result);
885 if (security == SECURITY_PSK)
886 pskType = getPskType(result);
887 mRssi = result.level;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700888 mSeen = result.timestamp;
Jason Monkd52356a2015-01-28 10:40:41 -0500889 }
890
891 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700892 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
893 savedState.putInt(KEY_SECURITY, security);
894 savedState.putInt(KEY_PSKTYPE, pskType);
895 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -0500896 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Mitchell Wills18af4932016-08-10 13:49:21 -0700897 evictOldScanResults();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700898 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
Mitchell Wills18af4932016-08-10 13:49:21 -0700899 new ArrayList<ScanResult>(mScanResultCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -0500900 if (mNetworkInfo != null) {
901 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
902 }
Peter Qiuced37db2017-03-14 15:51:22 -0700903 if (mFqdn != null) {
904 savedState.putString(KEY_FQDN, mFqdn);
905 }
906 if (mProviderFriendlyName != null) {
907 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
908 }
Jason Monkd52356a2015-01-28 10:40:41 -0500909 }
910
911 public void setListener(AccessPointListener listener) {
912 mAccessPointListener = listener;
913 }
914
915 boolean update(ScanResult result) {
Mitchell Wills5a42db22015-08-03 09:46:08 -0700916 if (matches(result)) {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800917 int oldLevel = getLevel();
918
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700919 /* Add or update the scan result for the BSSID */
920 mScanResultCache.put(result.BSSID, result);
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800921 updateSeen();
922 updateRssi();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700923 int newLevel = getLevel();
924
925 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
926 mAccessPointListener.onLevelChanged(this);
Jason Monkd52356a2015-01-28 10:40:41 -0500927 }
928 // This flag only comes from scans, is not easily saved in config
929 if (security == SECURITY_PSK) {
930 pskType = getPskType(result);
931 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700932
Jason Monkd52356a2015-01-28 10:40:41 -0500933 if (mAccessPointListener != null) {
934 mAccessPointListener.onAccessPointChanged(this);
935 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700936
Jason Monkd52356a2015-01-28 10:40:41 -0500937 return true;
938 }
939 return false;
940 }
941
Sundeep Ghumandc6cf4b2017-03-08 16:18:29 -0800942 public boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Jason Monkd52356a2015-01-28 10:40:41 -0500943 boolean reorder = false;
Mitchell Wills5a42db22015-08-03 09:46:08 -0700944 if (info != null && isInfoForThisAccessPoint(config, info)) {
Jason Monkd52356a2015-01-28 10:40:41 -0500945 reorder = (mInfo == null);
946 mRssi = info.getRssi();
947 mInfo = info;
948 mNetworkInfo = networkInfo;
949 if (mAccessPointListener != null) {
950 mAccessPointListener.onAccessPointChanged(this);
951 }
952 } else if (mInfo != null) {
953 reorder = true;
954 mInfo = null;
955 mNetworkInfo = null;
956 if (mAccessPointListener != null) {
957 mAccessPointListener.onAccessPointChanged(this);
958 }
959 }
960 return reorder;
961 }
962
Vinit Deshpandefc406002015-04-15 18:10:55 -0700963 void update(WifiConfiguration config) {
964 mConfig = config;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700965 networkId = config.networkId;
966 if (mAccessPointListener != null) {
967 mAccessPointListener.onAccessPointChanged(this);
968 }
Vinit Deshpandefc406002015-04-15 18:10:55 -0700969 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700970
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800971 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -0700972 void setRssi(int rssi) {
973 mRssi = rssi;
974 }
975
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800976 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
977 void setUnreachable() {
978 setRssi(AccessPoint.UNREACHABLE_RSSI);
979 }
980
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800981 int getRankingScore() {
982 return mRankingScore;
983 }
984
985 int getBadge() {
986 return mBadge;
987 }
988
Dave Schaefer98537432017-02-08 11:26:08 -0800989 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700990 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -0800991 return mRssi != UNREACHABLE_RSSI;
992 }
993
Jason Monkd52356a2015-01-28 10:40:41 -0500994 public static String getSummary(Context context, String ssid, DetailedState state,
Vinit Deshpandefc406002015-04-15 18:10:55 -0700995 boolean isEphemeral, String passpointProvider) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700996 if (state == DetailedState.CONNECTED && ssid == null) {
Vinit Deshpandefc406002015-04-15 18:10:55 -0700997 if (TextUtils.isEmpty(passpointProvider) == false) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700998 // Special case for connected + passpoint networks.
Vinit Deshpandefc406002015-04-15 18:10:55 -0700999 String format = context.getString(R.string.connected_via_passpoint);
1000 return String.format(format, passpointProvider);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001001 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001002 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001003 final NetworkScoreManager networkScoreManager = context.getSystemService(
1004 NetworkScoreManager.class);
1005 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1006 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1007 String format = context.getString(R.string.connected_via_network_scorer);
1008 return String.format(format, scorer.getRecommendationServiceLabel());
1009 } else {
1010 return context.getString(R.string.connected_via_network_scorer_default);
1011 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001012 }
Jason Monkd52356a2015-01-28 10:40:41 -05001013 }
1014
Sanket Padawe7094d222015-05-01 16:55:00 -07001015 // Case when there is wifi connected without internet connectivity.
1016 final ConnectivityManager cm = (ConnectivityManager)
1017 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1018 if (state == DetailedState.CONNECTED) {
1019 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1020 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001021 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001022
1023 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001024 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1025 } catch (RemoteException e) {}
1026
1027 if (nc != null) {
1028 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1029 return context.getString(
1030 com.android.internal.R.string.network_available_sign_in);
1031 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1032 return context.getString(R.string.wifi_connected_no_internet);
1033 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001034 }
1035 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001036 if (state == null) {
1037 Log.w(TAG, "state is null, returning empty summary");
1038 return "";
1039 }
Jason Monkd52356a2015-01-28 10:40:41 -05001040 String[] formats = context.getResources().getStringArray((ssid == null)
1041 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1042 int index = state.ordinal();
1043
1044 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001045 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001046 }
1047 return String.format(formats[index], ssid);
1048 }
1049
1050 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001051 return getSummary(context, null, state, isEphemeral, null);
1052 }
1053
1054 public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1055 String passpointProvider) {
1056 return getSummary(context, null, state, isEphemeral, passpointProvider);
Jason Monkd52356a2015-01-28 10:40:41 -05001057 }
1058
1059 public static String convertToQuotedString(String string) {
1060 return "\"" + string + "\"";
1061 }
1062
1063 private static int getPskType(ScanResult result) {
1064 boolean wpa = result.capabilities.contains("WPA-PSK");
1065 boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1066 if (wpa2 && wpa) {
1067 return PSK_WPA_WPA2;
1068 } else if (wpa2) {
1069 return PSK_WPA2;
1070 } else if (wpa) {
1071 return PSK_WPA;
1072 } else {
1073 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1074 return PSK_UNKNOWN;
1075 }
1076 }
1077
1078 private static int getSecurity(ScanResult result) {
1079 if (result.capabilities.contains("WEP")) {
1080 return SECURITY_WEP;
1081 } else if (result.capabilities.contains("PSK")) {
1082 return SECURITY_PSK;
1083 } else if (result.capabilities.contains("EAP")) {
1084 return SECURITY_EAP;
1085 }
1086 return SECURITY_NONE;
1087 }
1088
1089 static int getSecurity(WifiConfiguration config) {
1090 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1091 return SECURITY_PSK;
1092 }
1093 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1094 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1095 return SECURITY_EAP;
1096 }
1097 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1098 }
1099
1100 public static String securityToString(int security, int pskType) {
1101 if (security == SECURITY_WEP) {
1102 return "WEP";
1103 } else if (security == SECURITY_PSK) {
1104 if (pskType == PSK_WPA) {
1105 return "WPA";
1106 } else if (pskType == PSK_WPA2) {
1107 return "WPA2";
1108 } else if (pskType == PSK_WPA_WPA2) {
1109 return "WPA_WPA2";
1110 }
1111 return "PSK";
1112 } else if (security == SECURITY_EAP) {
1113 return "EAP";
1114 }
1115 return "NONE";
1116 }
1117
1118 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001119 if (TextUtils.isEmpty(string)) {
1120 return "";
1121 }
Jason Monkd52356a2015-01-28 10:40:41 -05001122 int length = string.length();
1123 if ((length > 1) && (string.charAt(0) == '"')
1124 && (string.charAt(length - 1) == '"')) {
1125 return string.substring(1, length - 1);
1126 }
1127 return string;
1128 }
1129
1130 public interface AccessPointListener {
1131 void onAccessPointChanged(AccessPoint accessPoint);
1132 void onLevelChanged(AccessPoint accessPoint);
1133 }
1134}