blob: 901848af43a0c8eadcd483391ba8a200883630bb [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;
Stephen Chen21f68682017-04-04 13:23:31 -0700152 private boolean mIsScoredNetworkMetered = false;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800153
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700154 // used to co-relate internal vs returned accesspoint.
155 int mId;
156
Peter Qiuced37db2017-03-14 15:51:22 -0700157 /**
158 * Information associated with the {@link PasspointConfiguration}. Only maintaining
159 * the relevant info to preserve spaces.
160 */
161 private String mFqdn;
162 private String mProviderFriendlyName;
163
Jason Monkd52356a2015-01-28 10:40:41 -0500164 public AccessPoint(Context context, Bundle savedState) {
165 mContext = context;
166 mConfig = savedState.getParcelable(KEY_CONFIG);
167 if (mConfig != null) {
168 loadConfig(mConfig);
169 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700170 if (savedState.containsKey(KEY_SSID)) {
171 ssid = savedState.getString(KEY_SSID);
172 }
173 if (savedState.containsKey(KEY_SECURITY)) {
174 security = savedState.getInt(KEY_SECURITY);
175 }
176 if (savedState.containsKey(KEY_PSKTYPE)) {
177 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500178 }
179 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
180 if (savedState.containsKey(KEY_NETWORKINFO)) {
181 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
182 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700183 if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
184 ArrayList<ScanResult> scanResultArrayList =
185 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
Mitchell Wills18af4932016-08-10 13:49:21 -0700186 mScanResultCache.clear();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700187 for (ScanResult result : scanResultArrayList) {
188 mScanResultCache.put(result.BSSID, result);
189 }
190 }
Peter Qiuced37db2017-03-14 15:51:22 -0700191 if (savedState.containsKey(KEY_FQDN)) {
192 mFqdn = savedState.getString(KEY_FQDN);
193 }
194 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
195 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
196 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700197 update(mConfig, mInfo, mNetworkInfo);
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800198 updateRssi();
199 updateSeen();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700200 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500201 }
202
Peter Qiuced37db2017-03-14 15:51:22 -0700203 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500204 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700205 loadConfig(config);
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700206 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500207 }
208
Peter Qiuced37db2017-03-14 15:51:22 -0700209 /**
210 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
211 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
212 */
213 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500214 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700215 mFqdn = config.getHomeSp().getFqdn();
216 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700217 mId = sLastId.incrementAndGet();
218 }
219
220 AccessPoint(Context context, AccessPoint other) {
221 mContext = context;
222 copyFrom(other);
223 }
224
Peter Qiuced37db2017-03-14 15:51:22 -0700225 AccessPoint(Context context, ScanResult result) {
226 mContext = context;
227 initWithScanResult(result);
228 mId = sLastId.incrementAndGet();
229 }
230
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700231 /**
232 * Copy accesspoint information. NOTE: We do not copy tag information because that is never
233 * set on the internal copy.
234 * @param that
235 */
236 void copyFrom(AccessPoint that) {
237 that.evictOldScanResults();
238 this.ssid = that.ssid;
239 this.bssid = that.bssid;
240 this.security = that.security;
241 this.networkId = that.networkId;
242 this.pskType = that.pskType;
243 this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated.
244 this.mRssi = that.mRssi;
245 this.mSeen = that.mSeen;
246 this.mInfo = that.mInfo;
247 this.mNetworkInfo = that.mNetworkInfo;
248 this.mScanResultCache.clear();
249 this.mScanResultCache.putAll(that.mScanResultCache);
250 this.mId = that.mId;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800251 this.mBadge = that.mBadge;
Stephen Chen21f68682017-04-04 13:23:31 -0700252 this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800253 this.mRankingScore = that.mRankingScore;
Jason Monkd52356a2015-01-28 10:40:41 -0500254 }
255
Dave Schaefer98537432017-02-08 11:26:08 -0800256 /**
257 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
258 * equal to, or greater than the other AccessPoint.
259 *
260 * Sort order rules for AccessPoints:
261 * 1. Active before inactive
262 * 2. Reachable before unreachable
263 * 3. Saved before unsaved
264 * 4. (Internal only) Network ranking score
265 * 5. Stronger signal before weaker signal
266 * 6. SSID alphabetically
267 *
268 * Note that AccessPoints with a signal are usually also Reachable,
269 * and will thus appear before unreachable saved AccessPoints.
270 */
Jason Monkd52356a2015-01-28 10:40:41 -0500271 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800272 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500273 // Active one goes first.
274 if (isActive() && !other.isActive()) return -1;
275 if (!isActive() && other.isActive()) return 1;
276
277 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800278 if (isReachable() && !other.isReachable()) return -1;
279 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500280
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800281 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800282 if (isSaved() && !other.isSaved()) return -1;
283 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500284
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800285 // Higher scores go before lower scores
Dave Schaefer98537432017-02-08 11:26:08 -0800286 if (getRankingScore() != other.getRankingScore()) {
287 return (getRankingScore() > other.getRankingScore()) ? -1 : 1;
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800288 }
289
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800290 // Sort by signal strength, bucketed by level
291 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
292 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500293 if (difference != 0) {
294 return difference;
295 }
296 // Sort by ssid.
Dave Schaefer98537432017-02-08 11:26:08 -0800297 return getSsidStr().compareToIgnoreCase(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500298 }
299
300 @Override
301 public boolean equals(Object other) {
302 if (!(other instanceof AccessPoint)) return false;
303 return (this.compareTo((AccessPoint) other) == 0);
304 }
305
306 @Override
307 public int hashCode() {
308 int result = 0;
309 if (mInfo != null) result += 13 * mInfo.hashCode();
310 result += 19 * mRssi;
311 result += 23 * networkId;
312 result += 29 * ssid.hashCode();
313 return result;
314 }
315
316 @Override
317 public String toString() {
318 StringBuilder builder = new StringBuilder().append("AccessPoint(")
319 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800320 if (bssid != null) {
321 builder.append(":").append(bssid);
322 }
Jason Monkd52356a2015-01-28 10:40:41 -0500323 if (isSaved()) {
324 builder.append(',').append("saved");
325 }
326 if (isActive()) {
327 builder.append(',').append("active");
328 }
329 if (isEphemeral()) {
330 builder.append(',').append("ephemeral");
331 }
332 if (isConnectable()) {
333 builder.append(',').append("connectable");
334 }
335 if (security != SECURITY_NONE) {
336 builder.append(',').append(securityToString(security, pskType));
337 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800338 builder.append(",level=").append(getLevel());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800339 builder.append(",rankingScore=").append(mRankingScore);
340 builder.append(",badge=").append(mBadge);
Stephen Chen21f68682017-04-04 13:23:31 -0700341 builder.append(",metered=").append(isMetered());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800342
Jason Monkd52356a2015-01-28 10:40:41 -0500343 return builder.append(')').toString();
344 }
345
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800346 /**
Stephen Chen21f68682017-04-04 13:23:31 -0700347 * Updates the AccessPoint rankingScore, metering, and badge, returning true if the data has
348 * changed.
349 *
350 * @param scoreCache The score cache to use to retrieve scores.
351 * @param scoringUiEnabled Whether to show scoring and badging UI.
352 */
353 boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) {
354 boolean scoreChanged = false;
355 if (scoringUiEnabled) {
356 scoreChanged = updateScores(scoreCache);
357 }
358 return updateMetered(scoreCache) || scoreChanged;
359 }
360
361 /**
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800362 * Updates the AccessPoint rankingScore and badge, returning true if the data has changed.
363 *
364 * @param scoreCache The score cache to use to retrieve scores.
365 */
Stephen Chen21f68682017-04-04 13:23:31 -0700366 private boolean updateScores(WifiNetworkScoreCache scoreCache) {
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800367 int oldBadge = mBadge;
368 int oldRankingScore = mRankingScore;
Sundeep Ghuman699deaf2017-02-13 15:32:13 -0800369 mBadge = NetworkBadging.BADGING_NONE;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800370 mRankingScore = Integer.MIN_VALUE;
371
372 for (ScanResult result : mScanResultCache.values()) {
373 ScoredNetwork score = scoreCache.getScoredNetwork(result);
374 if (score == null) {
375 continue;
376 }
377
378 if (score.hasRankingScore()) {
379 mRankingScore = Math.max(mRankingScore, score.calculateRankingScore(result.level));
380 }
381 mBadge = Math.max(mBadge, score.calculateBadge(result.level));
382 }
383
384 return (oldBadge != mBadge || oldRankingScore != mRankingScore);
385 }
386
Stephen Chen21f68682017-04-04 13:23:31 -0700387 /**
388 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
389 * true if the metering changed.
390 */
391 private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
392 boolean oldMetering = mIsScoredNetworkMetered;
393 mIsScoredNetworkMetered = false;
394 for (ScanResult result : mScanResultCache.values()) {
395 ScoredNetwork score = scoreCache.getScoredNetwork(result);
396 if (score == null) {
397 continue;
398 }
399 mIsScoredNetworkMetered |= score.meteredHint;
400 }
401 return oldMetering == mIsScoredNetworkMetered;
402 }
403
Mitchell Wills18af4932016-08-10 13:49:21 -0700404 private void evictOldScanResults() {
405 long nowMs = SystemClock.elapsedRealtime();
406 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
407 ScanResult result = iter.next();
408 // result timestamp is in microseconds
409 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) {
410 iter.remove();
411 }
412 }
413 }
414
Jason Monkd52356a2015-01-28 10:40:41 -0500415 public boolean matches(ScanResult result) {
416 return ssid.equals(result.SSID) && security == getSecurity(result);
417 }
418
419 public boolean matches(WifiConfiguration config) {
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100420 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
Shinji Sogof29e1222015-12-09 17:21:38 +0900421 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100422 } else {
423 return ssid.equals(removeDoubleQuotes(config.SSID))
424 && security == getSecurity(config)
425 && (mConfig == null || mConfig.shared == config.shared);
426 }
Jason Monkd52356a2015-01-28 10:40:41 -0500427 }
428
429 public WifiConfiguration getConfig() {
430 return mConfig;
431 }
432
Peter Qiuced37db2017-03-14 15:51:22 -0700433 public String getPasspointFqdn() {
434 return mFqdn;
435 }
436
Jason Monkd52356a2015-01-28 10:40:41 -0500437 public void clearConfig() {
438 mConfig = null;
439 networkId = WifiConfiguration.INVALID_NETWORK_ID;
440 }
441
442 public WifiInfo getInfo() {
443 return mInfo;
444 }
445
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700446 /**
447 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
448 *
449 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
450 * always return at least 0.
451 */
Jason Monkd52356a2015-01-28 10:40:41 -0500452 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800453 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500454 }
455
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700456 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800457 return mRssi;
458 }
459
460 /**
461 * Updates {@link #mRssi}.
462 *
463 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
464 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700465 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
466 * value. If the access point is not connected and there are no scan results, the rssi will be
467 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800468 *
469 * <p>Old scan results will be evicted from the cache when this method is invoked.
470 */
471 private void updateRssi() {
Mitchell Wills18af4932016-08-10 13:49:21 -0700472 evictOldScanResults();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800473
474 if (this.isActive()) {
475 return;
476 }
477
478 int rssi = UNREACHABLE_RSSI;
Mitchell Wills18af4932016-08-10 13:49:21 -0700479 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700480 if (result.level > rssi) {
481 rssi = result.level;
482 }
483 }
484
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700485 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
486 mRssi = (mRssi + rssi) / 2; // half-life previous value
487 } else {
488 mRssi = rssi;
489 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700490 }
491
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800492 /**
493 * Updates {@link #mSeen} based on the scan result cache.
494 *
495 * <p>Old scan results will be evicted from the cache when this method is invoked.
496 */
497 private void updateSeen() {
Mitchell Wills18af4932016-08-10 13:49:21 -0700498 evictOldScanResults();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800499
500 // TODO(sghuman): Set to now if connected
501
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700502 long seen = 0;
Mitchell Wills18af4932016-08-10 13:49:21 -0700503 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700504 if (result.timestamp > seen) {
505 seen = result.timestamp;
506 }
507 }
508
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800509 mSeen = seen;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700510 }
511
Stephen Chen21f68682017-04-04 13:23:31 -0700512 /**
513 * Returns if the network is marked metered. Metering can be marked through its config in
514 * {@link WifiConfiguration}, after connection in {@link WifiInfo}, or from a score config in
515 * {@link ScoredNetwork}.
516 */
517 public boolean isMetered() {
518 return mIsScoredNetworkMetered
519 || (mConfig != null && mConfig.meteredHint)
520 || (mInfo != null && mInfo.getMeteredHint());
521 }
522
Jason Monkd52356a2015-01-28 10:40:41 -0500523 public NetworkInfo getNetworkInfo() {
524 return mNetworkInfo;
525 }
526
527 public int getSecurity() {
528 return security;
529 }
530
531 public String getSecurityString(boolean concise) {
532 Context context = mContext;
Sanket Padawed1878802015-05-12 10:27:19 -0700533 if (mConfig != null && mConfig.isPasspoint()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700534 return concise ? context.getString(R.string.wifi_security_short_eap) :
535 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700536 }
Jason Monkd52356a2015-01-28 10:40:41 -0500537 switch(security) {
538 case SECURITY_EAP:
539 return concise ? context.getString(R.string.wifi_security_short_eap) :
540 context.getString(R.string.wifi_security_eap);
541 case SECURITY_PSK:
542 switch (pskType) {
543 case PSK_WPA:
544 return concise ? context.getString(R.string.wifi_security_short_wpa) :
545 context.getString(R.string.wifi_security_wpa);
546 case PSK_WPA2:
547 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
548 context.getString(R.string.wifi_security_wpa2);
549 case PSK_WPA_WPA2:
550 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
551 context.getString(R.string.wifi_security_wpa_wpa2);
552 case PSK_UNKNOWN:
553 default:
554 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
555 : context.getString(R.string.wifi_security_psk_generic);
556 }
557 case SECURITY_WEP:
558 return concise ? context.getString(R.string.wifi_security_short_wep) :
559 context.getString(R.string.wifi_security_wep);
560 case SECURITY_NONE:
561 default:
562 return concise ? "" : context.getString(R.string.wifi_security_none);
563 }
564 }
565
Jason Monk6980d122015-06-15 10:07:55 -0400566 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500567 return ssid;
568 }
569
Jason Monk60a82ff2016-02-25 13:55:03 -0500570 public String getBssid() {
571 return bssid;
572 }
573
Jason Monk6980d122015-06-15 10:07:55 -0400574 public CharSequence getSsid() {
Fan Zhangeb83a0d2016-09-21 11:34:08 -0700575 final SpannableString str = new SpannableString(ssid);
576 str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
Jason Monk6980d122015-06-15 10:07:55 -0400577 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
578 return str;
579 }
580
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700581 public String getConfigName() {
582 if (mConfig != null && mConfig.isPasspoint()) {
583 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700584 } else if (mFqdn != null) {
585 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700586 } else {
587 return ssid;
588 }
589 }
590
Jason Monkd52356a2015-01-28 10:40:41 -0500591 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700592 if (mNetworkInfo != null) {
593 return mNetworkInfo.getDetailedState();
594 }
595 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
596 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500597 }
598
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700599 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700600 WifiConfiguration config = mConfig;
601 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700602 PackageManager pm = mContext.getPackageManager();
603 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700604 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700605 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700606 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700607 appInfo = mContext.getApplicationInfo();
608 } else {
609 try {
610 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700611 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700612 } catch (RemoteException rex) {
613 }
614 }
615 if (appInfo != null &&
616 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
617 !appInfo.packageName.equals(
618 mContext.getString(R.string.certinstaller_package))) {
619 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
620 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700621 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700622 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700623 }
624
Jason Monkd52356a2015-01-28 10:40:41 -0500625 public String getSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700626 return getSettingsSummary(mConfig);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700627 }
628
629 public String getSettingsSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700630 return getSettingsSummary(mConfig);
631 }
632
633 private String getSettingsSummary(WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500634 // Update to new summary
635 StringBuilder summary = new StringBuilder();
636
Fan Zhang51365c32016-09-20 12:22:18 -0700637 if (isActive() && config != null && config.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700638 // This is the active connection on passpoint
Jason Monkd52356a2015-01-28 10:40:41 -0500639 summary.append(getSummary(mContext, getDetailedState(),
Fan Zhang51365c32016-09-20 12:22:18 -0700640 false, config.providerFriendlyName));
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700641 } else if (isActive()) {
642 // This is the active connection on non-passpoint network
643 summary.append(getSummary(mContext, getDetailedState(),
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700644 mInfo != null && mInfo.isEphemeral()));
Yuxin Chang6b750862017-01-11 14:59:17 +0900645 } else if (config != null && config.isPasspoint()
646 && config.getNetworkSelectionStatus().isNetworkEnabled()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700647 String format = mContext.getString(R.string.available_via_passpoint);
Fan Zhang51365c32016-09-20 12:22:18 -0700648 summary.append(String.format(format, config.providerFriendlyName));
649 } else if (config != null && config.hasNoInternetAccess()) {
Salvador Martinez5d937fc2016-09-23 08:54:20 -0700650 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
651 ? R.string.wifi_no_internet_no_reconnect
652 : R.string.wifi_no_internet;
653 summary.append(mContext.getString(messageID));
Fan Zhang51365c32016-09-20 12:22:18 -0700654 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
xinhef7705c32015-12-01 14:44:37 -0800655 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700656 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800657 switch (networkStatus.getNetworkSelectionDisableReason()) {
658 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
Jason Monkd52356a2015-01-28 10:40:41 -0500659 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
xinhef7705c32015-12-01 14:44:37 -0800660 break;
661 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
662 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
663 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
664 break;
665 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
666 summary.append(mContext.getString(R.string.wifi_disabled_generic));
667 break;
Jason Monkd52356a2015-01-28 10:40:41 -0500668 }
Amin Shaikh98773d42017-02-02 17:50:12 -0800669 } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
670 summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
Dave Schaefer98537432017-02-08 11:26:08 -0800671 } else if (!isReachable()) { // Wifi out of range
Jason Monkd52356a2015-01-28 10:40:41 -0500672 summary.append(mContext.getString(R.string.wifi_not_in_range));
673 } else { // In range, not disabled.
Fan Zhang51365c32016-09-20 12:22:18 -0700674 if (config != null) { // Is saved network
Jason Monkd52356a2015-01-28 10:40:41 -0500675 summary.append(mContext.getString(R.string.wifi_remembered));
676 }
677 }
678
679 if (WifiTracker.sVerboseLogging > 0) {
680 // Add RSSI/band information for this config, what was seen up to 6 seconds ago
681 // verbose WiFi Logging is only turned on thru developers settings
682 if (mInfo != null && mNetworkInfo != null) { // This is the active connection
683 summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
684 }
685 summary.append(" " + getVisibilityStatus());
Fan Zhang51365c32016-09-20 12:22:18 -0700686 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
687 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
688 if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
Jason Monkd52356a2015-01-28 10:40:41 -0500689 long now = System.currentTimeMillis();
Fan Zhang51365c32016-09-20 12:22:18 -0700690 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
Jason Monkd52356a2015-01-28 10:40:41 -0500691 long sec = diff%60; //seconds
692 long min = (diff/60)%60; //minutes
693 long hour = (min/60)%60; //hours
694 summary.append(", ");
695 if (hour > 0) summary.append(Long.toString(hour) + "h ");
696 summary.append( Long.toString(min) + "m ");
697 summary.append( Long.toString(sec) + "s ");
698 }
699 summary.append(")");
700 }
xinhef7705c32015-12-01 14:44:37 -0800701
Fan Zhang51365c32016-09-20 12:22:18 -0700702 if (config != null) {
xinhef7705c32015-12-01 14:44:37 -0800703 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700704 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800705 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
706 index < WifiConfiguration.NetworkSelectionStatus
707 .NETWORK_SELECTION_DISABLED_MAX; index++) {
708 if (networkStatus.getDisableReasonCounter(index) != 0) {
709 summary.append(" " + WifiConfiguration.NetworkSelectionStatus
710 .getNetworkDisableReasonString(index) + "="
711 + networkStatus.getDisableReasonCounter(index));
712 }
713 }
Jason Monkd52356a2015-01-28 10:40:41 -0500714 }
715 }
716 return summary.toString();
717 }
718
719 /**
720 * Returns the visibility status of the WifiConfiguration.
721 *
722 * @return autojoin debugging information
723 * TODO: use a string formatter
724 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
725 * For instance [-40,5/-30,2]
726 */
727 private String getVisibilityStatus() {
728 StringBuilder visibility = new StringBuilder();
729 StringBuilder scans24GHz = null;
730 StringBuilder scans5GHz = null;
731 String bssid = null;
732
733 long now = System.currentTimeMillis();
734
735 if (mInfo != null) {
736 bssid = mInfo.getBSSID();
737 if (bssid != null) {
738 visibility.append(" ").append(bssid);
739 }
740 visibility.append(" rssi=").append(mInfo.getRssi());
741 visibility.append(" ");
742 visibility.append(" score=").append(mInfo.score);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800743 visibility.append(" rankingScore=").append(getRankingScore());
744 visibility.append(" badge=").append(getBadge());
Jason Monkd52356a2015-01-28 10:40:41 -0500745 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
746 visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
747 visibility.append(String.format("%.1f ", mInfo.txBadRate));
748 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
749 }
750
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700751 int rssi5 = WifiConfiguration.INVALID_RSSI;
752 int rssi24 = WifiConfiguration.INVALID_RSSI;
753 int num5 = 0;
754 int num24 = 0;
755 int numBlackListed = 0;
756 int n24 = 0; // Number scan results we included in the string
757 int n5 = 0; // Number scan results we included in the string
Mitchell Wills18af4932016-08-10 13:49:21 -0700758 evictOldScanResults();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700759 // TODO: sort list by RSSI or age
Mitchell Wills18af4932016-08-10 13:49:21 -0700760 for (ScanResult result : mScanResultCache.values()) {
Jason Monkd52356a2015-01-28 10:40:41 -0500761
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700762 if (result.frequency >= LOWER_FREQ_5GHZ
763 && result.frequency <= HIGHER_FREQ_5GHZ) {
764 // Strictly speaking: [4915, 5825]
765 // number of known BSSID on 5GHz band
766 num5 = num5 + 1;
767 } else if (result.frequency >= LOWER_FREQ_24GHZ
768 && result.frequency <= HIGHER_FREQ_24GHZ) {
769 // Strictly speaking: [2412, 2482]
770 // number of known BSSID on 2.4Ghz band
771 num24 = num24 + 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500772 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700773
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700774
775 if (result.frequency >= LOWER_FREQ_5GHZ
776 && result.frequency <= HIGHER_FREQ_5GHZ) {
777 if (result.level > rssi5) {
778 rssi5 = result.level;
Jason Monkd52356a2015-01-28 10:40:41 -0500779 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700780 if (n5 < 4) {
781 if (scans5GHz == null) scans5GHz = new StringBuilder();
782 scans5GHz.append(" \n{").append(result.BSSID);
783 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
784 scans5GHz.append("=").append(result.frequency);
785 scans5GHz.append(",").append(result.level);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700786 scans5GHz.append("}");
787 n5++;
Jason Monkd52356a2015-01-28 10:40:41 -0500788 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700789 } else if (result.frequency >= LOWER_FREQ_24GHZ
790 && result.frequency <= HIGHER_FREQ_24GHZ) {
791 if (result.level > rssi24) {
792 rssi24 = result.level;
793 }
794 if (n24 < 4) {
795 if (scans24GHz == null) scans24GHz = new StringBuilder();
796 scans24GHz.append(" \n{").append(result.BSSID);
797 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
798 scans24GHz.append("=").append(result.frequency);
799 scans24GHz.append(",").append(result.level);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700800 scans24GHz.append("}");
801 n24++;
Jason Monkd52356a2015-01-28 10:40:41 -0500802 }
803 }
804 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700805 visibility.append(" [");
806 if (num24 > 0) {
807 visibility.append("(").append(num24).append(")");
808 if (n24 <= 4) {
809 if (scans24GHz != null) {
810 visibility.append(scans24GHz.toString());
811 }
812 } else {
813 visibility.append("max=").append(rssi24);
814 if (scans24GHz != null) {
815 visibility.append(",").append(scans24GHz.toString());
816 }
817 }
818 }
819 visibility.append(";");
820 if (num5 > 0) {
821 visibility.append("(").append(num5).append(")");
822 if (n5 <= 4) {
823 if (scans5GHz != null) {
824 visibility.append(scans5GHz.toString());
825 }
826 } else {
827 visibility.append("max=").append(rssi5);
828 if (scans5GHz != null) {
829 visibility.append(",").append(scans5GHz.toString());
830 }
831 }
832 }
833 if (numBlackListed > 0)
834 visibility.append("!").append(numBlackListed);
835 visibility.append("]");
Jason Monkd52356a2015-01-28 10:40:41 -0500836
837 return visibility.toString();
838 }
839
840 /**
841 * Return whether this is the active connection.
842 * For ephemeral connections (networkId is invalid), this returns false if the network is
843 * disconnected.
844 */
845 public boolean isActive() {
846 return mNetworkInfo != null &&
847 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
848 mNetworkInfo.getState() != State.DISCONNECTED);
849 }
850
851 public boolean isConnectable() {
852 return getLevel() != -1 && getDetailedState() == null;
853 }
854
855 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700856 return mInfo != null && mInfo.isEphemeral() &&
857 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -0500858 }
859
Peter Qiuced37db2017-03-14 15:51:22 -0700860 /**
861 * Return true if this AccessPoint represents a Passpoint AP.
862 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -0700863 public boolean isPasspoint() {
864 return mConfig != null && mConfig.isPasspoint();
865 }
866
Mitchell Wills5a42db22015-08-03 09:46:08 -0700867 /**
Peter Qiuced37db2017-03-14 15:51:22 -0700868 * Return true if this AccessPoint represents a Passpoint provider configuration.
869 */
870 public boolean isPasspointConfig() {
871 return mFqdn != null;
872 }
873
874 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -0700875 * Return whether the given {@link WifiInfo} is for this access point.
876 * If the current AP does not have a network Id then the config is used to
877 * match based on SSID and security.
878 */
879 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Vinit Deshpande5b7352c2015-07-09 16:53:12 -0700880 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -0500881 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -0700882 } else if (config != null) {
883 return matches(config);
884 }
885 else {
Jason Monkd52356a2015-01-28 10:40:41 -0500886 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
887 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
888 // TODO: Handle hex string SSIDs.
889 return ssid.equals(removeDoubleQuotes(info.getSSID()));
890 }
891 }
892
893 public boolean isSaved() {
894 return networkId != WifiConfiguration.INVALID_NETWORK_ID;
895 }
896
897 public Object getTag() {
898 return mTag;
899 }
900
901 public void setTag(Object tag) {
902 mTag = tag;
903 }
904
905 /**
906 * Generate and save a default wifiConfiguration with common values.
907 * Can only be called for unsecured networks.
908 */
909 public void generateOpenNetworkConfig() {
910 if (security != SECURITY_NONE)
911 throw new IllegalStateException();
912 if (mConfig != null)
913 return;
914 mConfig = new WifiConfiguration();
915 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
916 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
917 }
918
919 void loadConfig(WifiConfiguration config) {
Peter Qiu2c3b5ee22017-02-01 11:49:15 -0800920 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
Jason Monk60a82ff2016-02-25 13:55:03 -0500921 bssid = config.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -0500922 security = getSecurity(config);
923 networkId = config.networkId;
924 mConfig = config;
925 }
926
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700927 private void initWithScanResult(ScanResult result) {
Jason Monkd52356a2015-01-28 10:40:41 -0500928 ssid = result.SSID;
Jason Monk60a82ff2016-02-25 13:55:03 -0500929 bssid = result.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -0500930 security = getSecurity(result);
931 if (security == SECURITY_PSK)
932 pskType = getPskType(result);
933 mRssi = result.level;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700934 mSeen = result.timestamp;
Jason Monkd52356a2015-01-28 10:40:41 -0500935 }
936
937 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700938 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
939 savedState.putInt(KEY_SECURITY, security);
940 savedState.putInt(KEY_PSKTYPE, pskType);
941 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -0500942 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Mitchell Wills18af4932016-08-10 13:49:21 -0700943 evictOldScanResults();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700944 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
Mitchell Wills18af4932016-08-10 13:49:21 -0700945 new ArrayList<ScanResult>(mScanResultCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -0500946 if (mNetworkInfo != null) {
947 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
948 }
Peter Qiuced37db2017-03-14 15:51:22 -0700949 if (mFqdn != null) {
950 savedState.putString(KEY_FQDN, mFqdn);
951 }
952 if (mProviderFriendlyName != null) {
953 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
954 }
Jason Monkd52356a2015-01-28 10:40:41 -0500955 }
956
957 public void setListener(AccessPointListener listener) {
958 mAccessPointListener = listener;
959 }
960
961 boolean update(ScanResult result) {
Mitchell Wills5a42db22015-08-03 09:46:08 -0700962 if (matches(result)) {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800963 int oldLevel = getLevel();
964
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700965 /* Add or update the scan result for the BSSID */
966 mScanResultCache.put(result.BSSID, result);
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800967 updateSeen();
968 updateRssi();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700969 int newLevel = getLevel();
970
971 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
972 mAccessPointListener.onLevelChanged(this);
Jason Monkd52356a2015-01-28 10:40:41 -0500973 }
974 // This flag only comes from scans, is not easily saved in config
975 if (security == SECURITY_PSK) {
976 pskType = getPskType(result);
977 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700978
Jason Monkd52356a2015-01-28 10:40:41 -0500979 if (mAccessPointListener != null) {
980 mAccessPointListener.onAccessPointChanged(this);
981 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700982
Jason Monkd52356a2015-01-28 10:40:41 -0500983 return true;
984 }
985 return false;
986 }
987
Sundeep Ghumandc6cf4b2017-03-08 16:18:29 -0800988 public boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Jason Monkd52356a2015-01-28 10:40:41 -0500989 boolean reorder = false;
Mitchell Wills5a42db22015-08-03 09:46:08 -0700990 if (info != null && isInfoForThisAccessPoint(config, info)) {
Jason Monkd52356a2015-01-28 10:40:41 -0500991 reorder = (mInfo == null);
992 mRssi = info.getRssi();
993 mInfo = info;
994 mNetworkInfo = networkInfo;
995 if (mAccessPointListener != null) {
996 mAccessPointListener.onAccessPointChanged(this);
997 }
998 } else if (mInfo != null) {
999 reorder = true;
1000 mInfo = null;
1001 mNetworkInfo = null;
1002 if (mAccessPointListener != null) {
1003 mAccessPointListener.onAccessPointChanged(this);
1004 }
1005 }
1006 return reorder;
1007 }
1008
Vinit Deshpandefc406002015-04-15 18:10:55 -07001009 void update(WifiConfiguration config) {
1010 mConfig = config;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001011 networkId = config.networkId;
1012 if (mAccessPointListener != null) {
1013 mAccessPointListener.onAccessPointChanged(this);
1014 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001015 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001016
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001017 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -07001018 void setRssi(int rssi) {
1019 mRssi = rssi;
1020 }
1021
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001022 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1023 void setUnreachable() {
1024 setRssi(AccessPoint.UNREACHABLE_RSSI);
1025 }
1026
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -08001027 int getRankingScore() {
1028 return mRankingScore;
1029 }
1030
1031 int getBadge() {
1032 return mBadge;
1033 }
1034
Dave Schaefer98537432017-02-08 11:26:08 -08001035 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -07001036 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -08001037 return mRssi != UNREACHABLE_RSSI;
1038 }
1039
Jason Monkd52356a2015-01-28 10:40:41 -05001040 public static String getSummary(Context context, String ssid, DetailedState state,
Vinit Deshpandefc406002015-04-15 18:10:55 -07001041 boolean isEphemeral, String passpointProvider) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001042 if (state == DetailedState.CONNECTED && ssid == null) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001043 if (TextUtils.isEmpty(passpointProvider) == false) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001044 // Special case for connected + passpoint networks.
Vinit Deshpandefc406002015-04-15 18:10:55 -07001045 String format = context.getString(R.string.connected_via_passpoint);
1046 return String.format(format, passpointProvider);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001047 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001048 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001049 final NetworkScoreManager networkScoreManager = context.getSystemService(
1050 NetworkScoreManager.class);
1051 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1052 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1053 String format = context.getString(R.string.connected_via_network_scorer);
1054 return String.format(format, scorer.getRecommendationServiceLabel());
1055 } else {
1056 return context.getString(R.string.connected_via_network_scorer_default);
1057 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001058 }
Jason Monkd52356a2015-01-28 10:40:41 -05001059 }
1060
Sanket Padawe7094d222015-05-01 16:55:00 -07001061 // Case when there is wifi connected without internet connectivity.
1062 final ConnectivityManager cm = (ConnectivityManager)
1063 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1064 if (state == DetailedState.CONNECTED) {
1065 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1066 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001067 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001068
1069 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001070 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1071 } catch (RemoteException e) {}
1072
1073 if (nc != null) {
1074 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1075 return context.getString(
1076 com.android.internal.R.string.network_available_sign_in);
1077 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1078 return context.getString(R.string.wifi_connected_no_internet);
1079 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001080 }
1081 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001082 if (state == null) {
1083 Log.w(TAG, "state is null, returning empty summary");
1084 return "";
1085 }
Jason Monkd52356a2015-01-28 10:40:41 -05001086 String[] formats = context.getResources().getStringArray((ssid == null)
1087 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1088 int index = state.ordinal();
1089
1090 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001091 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001092 }
1093 return String.format(formats[index], ssid);
1094 }
1095
1096 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001097 return getSummary(context, null, state, isEphemeral, null);
1098 }
1099
1100 public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1101 String passpointProvider) {
1102 return getSummary(context, null, state, isEphemeral, passpointProvider);
Jason Monkd52356a2015-01-28 10:40:41 -05001103 }
1104
1105 public static String convertToQuotedString(String string) {
1106 return "\"" + string + "\"";
1107 }
1108
1109 private static int getPskType(ScanResult result) {
1110 boolean wpa = result.capabilities.contains("WPA-PSK");
1111 boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1112 if (wpa2 && wpa) {
1113 return PSK_WPA_WPA2;
1114 } else if (wpa2) {
1115 return PSK_WPA2;
1116 } else if (wpa) {
1117 return PSK_WPA;
1118 } else {
1119 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1120 return PSK_UNKNOWN;
1121 }
1122 }
1123
1124 private static int getSecurity(ScanResult result) {
1125 if (result.capabilities.contains("WEP")) {
1126 return SECURITY_WEP;
1127 } else if (result.capabilities.contains("PSK")) {
1128 return SECURITY_PSK;
1129 } else if (result.capabilities.contains("EAP")) {
1130 return SECURITY_EAP;
1131 }
1132 return SECURITY_NONE;
1133 }
1134
1135 static int getSecurity(WifiConfiguration config) {
1136 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1137 return SECURITY_PSK;
1138 }
1139 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1140 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1141 return SECURITY_EAP;
1142 }
1143 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1144 }
1145
1146 public static String securityToString(int security, int pskType) {
1147 if (security == SECURITY_WEP) {
1148 return "WEP";
1149 } else if (security == SECURITY_PSK) {
1150 if (pskType == PSK_WPA) {
1151 return "WPA";
1152 } else if (pskType == PSK_WPA2) {
1153 return "WPA2";
1154 } else if (pskType == PSK_WPA_WPA2) {
1155 return "WPA_WPA2";
1156 }
1157 return "PSK";
1158 } else if (security == SECURITY_EAP) {
1159 return "EAP";
1160 }
1161 return "NONE";
1162 }
1163
1164 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001165 if (TextUtils.isEmpty(string)) {
1166 return "";
1167 }
Jason Monkd52356a2015-01-28 10:40:41 -05001168 int length = string.length();
1169 if ((length > 1) && (string.charAt(0) == '"')
1170 && (string.charAt(length - 1) == '"')) {
1171 return string.substring(1, length - 1);
1172 }
1173 return string;
1174 }
1175
1176 public interface AccessPointListener {
1177 void onAccessPointChanged(AccessPoint accessPoint);
1178 void onLevelChanged(AccessPoint accessPoint);
1179 }
1180}