blob: 330eaf0e18ba186fcce69e374f06d7e395a65752 [file] [log] [blame]
Jason Monkd52356a2015-01-28 10:40:41 -05001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settingslib.wifi;
18
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070019import android.annotation.IntDef;
Sundeep Ghuman271e5de2017-05-30 14:11:39 -070020import android.annotation.Nullable;
Jason Monk6980d122015-06-15 10:07:55 -040021import android.app.AppGlobals;
Jason Monkd52356a2015-01-28 10:40:41 -050022import android.content.Context;
Jason Monk6980d122015-06-15 10:07:55 -040023import android.content.pm.ApplicationInfo;
24import android.content.pm.IPackageManager;
25import android.content.pm.PackageManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070026import android.net.ConnectivityManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070027import android.net.NetworkCapabilities;
Jason Monkd52356a2015-01-28 10:40:41 -050028import android.net.NetworkInfo;
29import android.net.NetworkInfo.DetailedState;
30import android.net.NetworkInfo.State;
Sundeep Ghumana28050a2017-07-12 22:09:25 -070031import android.net.NetworkKey;
Stephen Chen36dd5cf12017-03-20 13:27:51 -070032import android.net.NetworkScoreManager;
33import android.net.NetworkScorerAppData;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080034import android.net.ScoredNetwork;
Sundeep Ghumana28050a2017-07-12 22:09:25 -070035import android.net.WifiKey;
Sanket Padawe7094d222015-05-01 16:55:00 -070036import android.net.wifi.IWifiManager;
Jason Monkd52356a2015-01-28 10:40:41 -050037import android.net.wifi.ScanResult;
38import android.net.wifi.WifiConfiguration;
39import android.net.wifi.WifiConfiguration.KeyMgmt;
Peter Qiu280581b2017-07-24 14:18:56 -070040import android.net.wifi.WifiEnterpriseConfig;
Jason Monkd52356a2015-01-28 10:40:41 -050041import android.net.wifi.WifiInfo;
42import android.net.wifi.WifiManager;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080043import android.net.wifi.WifiNetworkScoreCache;
Peter Qiuced37db2017-03-14 15:51:22 -070044import android.net.wifi.hotspot2.PasspointConfiguration;
Jason Monkd52356a2015-01-28 10:40:41 -050045import android.os.Bundle;
Sanket Padawe7094d222015-05-01 16:55:00 -070046import android.os.RemoteException;
47import android.os.ServiceManager;
Mitchell Wills18af4932016-08-10 13:49:21 -070048import android.os.SystemClock;
Jason Monk6980d122015-06-15 10:07:55 -040049import android.os.UserHandle;
Tony Mantlera0e03dd2016-01-27 15:57:03 -080050import android.support.annotation.NonNull;
Jason Monk6980d122015-06-15 10:07:55 -040051import android.text.Spannable;
52import android.text.SpannableString;
53import android.text.TextUtils;
Sundeep Ghumana419b9b2017-08-15 15:47:18 -070054import android.text.format.DateUtils;
Jason Monk6980d122015-06-15 10:07:55 -040055import android.text.style.TtsSpan;
Jason Monkd52356a2015-01-28 10:40:41 -050056import android.util.Log;
Jason Monkd52356a2015-01-28 10:40:41 -050057
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -080058import com.android.internal.annotations.VisibleForTesting;
Jason Monkd52356a2015-01-28 10:40:41 -050059import com.android.settingslib.R;
60
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070061import java.lang.annotation.Retention;
62import java.lang.annotation.RetentionPolicy;
Vinit Deshpandefcd46122015-06-11 18:22:23 -070063import java.util.ArrayList;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070064import java.util.HashMap;
Mitchell Wills18af4932016-08-10 13:49:21 -070065import java.util.Iterator;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070066import java.util.Map;
Mitchell Wills18af4932016-08-10 13:49:21 -070067import java.util.concurrent.ConcurrentHashMap;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -070068import java.util.concurrent.atomic.AtomicInteger;
Jason Monkd52356a2015-01-28 10:40:41 -050069
70
71public class AccessPoint implements Comparable<AccessPoint> {
72 static final String TAG = "SettingsLib.AccessPoint";
73
74 /**
75 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
76 */
77 public static final int LOWER_FREQ_24GHZ = 2400;
78
79 /**
80 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
81 */
82 public static final int HIGHER_FREQ_24GHZ = 2500;
83
84 /**
85 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
86 */
87 public static final int LOWER_FREQ_5GHZ = 4900;
88
89 /**
90 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
91 */
92 public static final int HIGHER_FREQ_5GHZ = 5900;
93
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070094 @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST})
95 @Retention(RetentionPolicy.SOURCE)
96 public @interface Speed {
97 /**
98 * Constant value representing an unlabeled / unscored network.
99 */
100 int NONE = 0;
101 /**
102 * Constant value representing a slow speed network connection.
103 */
104 int SLOW = 5;
105 /**
106 * Constant value representing a medium speed network connection.
107 */
108 int MODERATE = 10;
109 /**
110 * Constant value representing a fast speed network connection.
111 */
112 int FAST = 20;
113 /**
114 * Constant value representing a very fast speed network connection.
115 */
116 int VERY_FAST = 30;
117 }
Jason Monkd52356a2015-01-28 10:40:41 -0500118
119 /**
120 * Experimental: we should be able to show the user the list of BSSIDs and bands
121 * for that SSID.
122 * For now this data is used only with Verbose Logging so as to show the band and number
123 * of BSSIDs on which that network is seen.
124 */
Mitchell Wills18af4932016-08-10 13:49:21 -0700125 private final ConcurrentHashMap<String, ScanResult> mScanResultCache =
126 new ConcurrentHashMap<String, ScanResult>(32);
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700127
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700128 /**
129 * Map of BSSIDs to scored networks for individual bssids.
130 *
131 * <p>This cache should not be evicted with scan results, as the values here are used to
132 * generate a fallback in the absence of scores for the visible APs.
133 */
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700134 private final Map<String, TimestampedScoredNetwork> mScoredNetworkCache = new HashMap<>();
135
136 /** Maximum age in millis of cached scored networks in {@link #mScoredNetworkCache}. */
137 @VisibleForTesting static final long MAX_CACHED_SCORE_AGE_MILLIS =
138 24 * DateUtils.DAY_IN_MILLIS;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700139
Sundeep Ghuman42058742017-07-21 18:42:10 -0700140 /** Maximum age of scan results to hold onto while actively scanning. **/
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700141 private static final long MAX_SCAN_RESULT_AGE_MILLIS = 15000;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700142
Dave Schaefer98537432017-02-08 11:26:08 -0800143 static final String KEY_NETWORKINFO = "key_networkinfo";
144 static final String KEY_WIFIINFO = "key_wifiinfo";
145 static final String KEY_SCANRESULT = "key_scanresult";
146 static final String KEY_SSID = "key_ssid";
147 static final String KEY_SECURITY = "key_security";
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700148 static final String KEY_SPEED = "key_speed";
Dave Schaefer98537432017-02-08 11:26:08 -0800149 static final String KEY_PSKTYPE = "key_psktype";
150 static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700151 static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
Dave Schaefer98537432017-02-08 11:26:08 -0800152 static final String KEY_CONFIG = "key_config";
Peter Qiuced37db2017-03-14 15:51:22 -0700153 static final String KEY_FQDN = "key_fqdn";
154 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
Peter Qiu280581b2017-07-24 14:18:56 -0700155 static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
156 static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
157 static final String KEY_CARRIER_NAME = "key_carrier_name";
Dave Schaefer98537432017-02-08 11:26:08 -0800158 static final AtomicInteger sLastId = new AtomicInteger(0);
Jason Monkd52356a2015-01-28 10:40:41 -0500159
160 /**
161 * These values are matched in string arrays -- changes must be kept in sync
162 */
163 public static final int SECURITY_NONE = 0;
164 public static final int SECURITY_WEP = 1;
165 public static final int SECURITY_PSK = 2;
166 public static final int SECURITY_EAP = 3;
167
168 private static final int PSK_UNKNOWN = 0;
169 private static final int PSK_WPA = 1;
170 private static final int PSK_WPA2 = 2;
171 private static final int PSK_WPA_WPA2 = 3;
172
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700173 /**
174 * The number of distinct wifi levels.
175 *
176 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
177 */
178 public static final int SIGNAL_LEVELS = 5;
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800179
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700180 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
Dave Schaefer98537432017-02-08 11:26:08 -0800181
Jason Monkd52356a2015-01-28 10:40:41 -0500182 private final Context mContext;
183
184 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500185 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500186 private int security;
187 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
188
189 private int pskType = PSK_UNKNOWN;
190
191 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500192
Dave Schaefer98537432017-02-08 11:26:08 -0800193 private int mRssi = UNREACHABLE_RSSI;
Jason Monkd52356a2015-01-28 10:40:41 -0500194 private long mSeen = 0;
195
196 private WifiInfo mInfo;
197 private NetworkInfo mNetworkInfo;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700198 AccessPointListener mAccessPointListener;
Jason Monkd52356a2015-01-28 10:40:41 -0500199
200 private Object mTag;
201
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700202 @Speed private int mSpeed = Speed.NONE;
Stephen Chen21f68682017-04-04 13:23:31 -0700203 private boolean mIsScoredNetworkMetered = false;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800204
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700205 // used to co-relate internal vs returned accesspoint.
206 int mId;
207
Peter Qiuced37db2017-03-14 15:51:22 -0700208 /**
209 * Information associated with the {@link PasspointConfiguration}. Only maintaining
210 * the relevant info to preserve spaces.
211 */
212 private String mFqdn;
213 private String mProviderFriendlyName;
214
Peter Qiu280581b2017-07-24 14:18:56 -0700215 private boolean mIsCarrierAp = false;
216 /**
217 * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
218 */
219 private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
220 private String mCarrierName = null;
221
Jason Monkd52356a2015-01-28 10:40:41 -0500222 public AccessPoint(Context context, Bundle savedState) {
223 mContext = context;
224 mConfig = savedState.getParcelable(KEY_CONFIG);
225 if (mConfig != null) {
226 loadConfig(mConfig);
227 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700228 if (savedState.containsKey(KEY_SSID)) {
229 ssid = savedState.getString(KEY_SSID);
230 }
231 if (savedState.containsKey(KEY_SECURITY)) {
232 security = savedState.getInt(KEY_SECURITY);
233 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700234 if (savedState.containsKey(KEY_SPEED)) {
235 mSpeed = savedState.getInt(KEY_SPEED);
236 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700237 if (savedState.containsKey(KEY_PSKTYPE)) {
238 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500239 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700240 mInfo = savedState.getParcelable(KEY_WIFIINFO);
Jason Monkd52356a2015-01-28 10:40:41 -0500241 if (savedState.containsKey(KEY_NETWORKINFO)) {
242 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
243 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700244 if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
245 ArrayList<ScanResult> scanResultArrayList =
246 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
Mitchell Wills18af4932016-08-10 13:49:21 -0700247 mScanResultCache.clear();
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700248 for (ScanResult result : scanResultArrayList) {
249 mScanResultCache.put(result.BSSID, result);
250 }
251 }
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700252 if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700253 ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700254 savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700255 for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
256 mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700257 }
258 }
Peter Qiuced37db2017-03-14 15:51:22 -0700259 if (savedState.containsKey(KEY_FQDN)) {
260 mFqdn = savedState.getString(KEY_FQDN);
261 }
262 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
263 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
264 }
Peter Qiu280581b2017-07-24 14:18:56 -0700265 if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
266 mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
267 }
268 if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
269 mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
270 }
271 if (savedState.containsKey(KEY_CARRIER_NAME)) {
272 mCarrierName = savedState.getString(KEY_CARRIER_NAME);
273 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700274 update(mConfig, mInfo, mNetworkInfo);
Sundeep Ghumand1e44922017-08-07 11:21:38 -0700275
276 // Do not evict old scan results on initial creation
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800277 updateRssi();
278 updateSeen();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700279 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500280 }
281
Peter Qiuced37db2017-03-14 15:51:22 -0700282 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500283 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700284 loadConfig(config);
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700285 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500286 }
287
Peter Qiuced37db2017-03-14 15:51:22 -0700288 /**
289 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
290 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
291 */
292 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500293 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700294 mFqdn = config.getHomeSp().getFqdn();
295 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700296 mId = sLastId.incrementAndGet();
297 }
298
299 AccessPoint(Context context, AccessPoint other) {
300 mContext = context;
301 copyFrom(other);
302 }
303
Peter Qiuced37db2017-03-14 15:51:22 -0700304 AccessPoint(Context context, ScanResult result) {
305 mContext = context;
306 initWithScanResult(result);
307 mId = sLastId.incrementAndGet();
308 }
309
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700310 /**
311 * Copy accesspoint information. NOTE: We do not copy tag information because that is never
312 * set on the internal copy.
313 * @param that
314 */
315 void copyFrom(AccessPoint that) {
316 that.evictOldScanResults();
317 this.ssid = that.ssid;
318 this.bssid = that.bssid;
319 this.security = that.security;
320 this.networkId = that.networkId;
321 this.pskType = that.pskType;
322 this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated.
323 this.mRssi = that.mRssi;
324 this.mSeen = that.mSeen;
325 this.mInfo = that.mInfo;
326 this.mNetworkInfo = that.mNetworkInfo;
327 this.mScanResultCache.clear();
328 this.mScanResultCache.putAll(that.mScanResultCache);
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700329 this.mScoredNetworkCache.clear();
330 this.mScoredNetworkCache.putAll(that.mScoredNetworkCache);
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700331 this.mId = that.mId;
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700332 this.mSpeed = that.mSpeed;
Stephen Chen21f68682017-04-04 13:23:31 -0700333 this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered;
Peter Qiu280581b2017-07-24 14:18:56 -0700334 this.mIsCarrierAp = that.mIsCarrierAp;
335 this.mCarrierApEapType = that.mCarrierApEapType;
336 this.mCarrierName = that.mCarrierName;
Jason Monkd52356a2015-01-28 10:40:41 -0500337 }
338
Dave Schaefer98537432017-02-08 11:26:08 -0800339 /**
340 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
341 * equal to, or greater than the other AccessPoint.
342 *
343 * Sort order rules for AccessPoints:
344 * 1. Active before inactive
345 * 2. Reachable before unreachable
346 * 3. Saved before unsaved
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700347 * 4. Network speed value
Dave Schaefer98537432017-02-08 11:26:08 -0800348 * 5. Stronger signal before weaker signal
349 * 6. SSID alphabetically
350 *
351 * Note that AccessPoints with a signal are usually also Reachable,
352 * and will thus appear before unreachable saved AccessPoints.
353 */
Jason Monkd52356a2015-01-28 10:40:41 -0500354 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800355 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500356 // Active one goes first.
357 if (isActive() && !other.isActive()) return -1;
358 if (!isActive() && other.isActive()) return 1;
359
360 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800361 if (isReachable() && !other.isReachable()) return -1;
362 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500363
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800364 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800365 if (isSaved() && !other.isSaved()) return -1;
366 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500367
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700368 // Faster speeds go before slower speeds - but only if visible change in speed label
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700369 if (getSpeed() != other.getSpeed()) {
370 return other.getSpeed() - getSpeed();
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800371 }
372
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800373 // Sort by signal strength, bucketed by level
374 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
375 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500376 if (difference != 0) {
377 return difference;
378 }
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700379
Jason Monkd52356a2015-01-28 10:40:41 -0500380 // Sort by ssid.
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700381 difference = getSsidStr().compareToIgnoreCase(other.getSsidStr());
382 if (difference != 0) {
383 return difference;
384 }
385
386 // Do a case sensitive comparison to distinguish SSIDs that differ in case only
387 return getSsidStr().compareTo(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500388 }
389
390 @Override
391 public boolean equals(Object other) {
392 if (!(other instanceof AccessPoint)) return false;
393 return (this.compareTo((AccessPoint) other) == 0);
394 }
395
396 @Override
397 public int hashCode() {
398 int result = 0;
399 if (mInfo != null) result += 13 * mInfo.hashCode();
400 result += 19 * mRssi;
401 result += 23 * networkId;
402 result += 29 * ssid.hashCode();
403 return result;
404 }
405
406 @Override
407 public String toString() {
408 StringBuilder builder = new StringBuilder().append("AccessPoint(")
409 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800410 if (bssid != null) {
411 builder.append(":").append(bssid);
412 }
Jason Monkd52356a2015-01-28 10:40:41 -0500413 if (isSaved()) {
414 builder.append(',').append("saved");
415 }
416 if (isActive()) {
417 builder.append(',').append("active");
418 }
419 if (isEphemeral()) {
420 builder.append(',').append("ephemeral");
421 }
422 if (isConnectable()) {
423 builder.append(',').append("connectable");
424 }
425 if (security != SECURITY_NONE) {
426 builder.append(',').append(securityToString(security, pskType));
427 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800428 builder.append(",level=").append(getLevel());
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700429 if (mSpeed != Speed.NONE) {
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700430 builder.append(",speed=").append(mSpeed);
Sundeep Ghuman8920e9c2017-04-27 16:16:41 -0700431 }
Stephen Chen21f68682017-04-04 13:23:31 -0700432 builder.append(",metered=").append(isMetered());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800433
Jason Monkd52356a2015-01-28 10:40:41 -0500434 return builder.append(')').toString();
435 }
436
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800437 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700438 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
Stephen Chen21f68682017-04-04 13:23:31 -0700439 * changed.
440 *
441 * @param scoreCache The score cache to use to retrieve scores.
442 * @param scoringUiEnabled Whether to show scoring and badging UI.
443 */
444 boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) {
445 boolean scoreChanged = false;
446 if (scoringUiEnabled) {
447 scoreChanged = updateScores(scoreCache);
448 }
449 return updateMetered(scoreCache) || scoreChanged;
450 }
451
452 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700453 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800454 *
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700455 * <p>Any cached {@link TimestampedScoredNetwork} objects older than
456 * {@link #MAX_CACHED_SCORE_AGE_MILLIS} will be removed when this method is invoked.
457 *
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700458 * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
459 *
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800460 * @param scoreCache The score cache to use to retrieve scores.
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700461 * @return true if the set speed has changed
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800462 */
Stephen Chen21f68682017-04-04 13:23:31 -0700463 private boolean updateScores(WifiNetworkScoreCache scoreCache) {
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700464 long nowMillis = SystemClock.elapsedRealtime();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700465 for (ScanResult result : mScanResultCache.values()) {
466 ScoredNetwork score = scoreCache.getScoredNetwork(result);
467 if (score == null) {
468 continue;
469 }
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700470 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
471 if (timedScore == null) {
472 mScoredNetworkCache.put(
473 result.BSSID, new TimestampedScoredNetwork(score, nowMillis));
474 } else {
475 // Update data since the has been seen in the score cache
476 timedScore.update(score, nowMillis);
477 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700478 }
479
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700480 // Remove old cached networks
481 long evictionCutoff = nowMillis - MAX_CACHED_SCORE_AGE_MILLIS;
482 Iterator<TimestampedScoredNetwork> iterator = mScoredNetworkCache.values().iterator();
483 iterator.forEachRemaining(timestampedScoredNetwork -> {
484 if (timestampedScoredNetwork.getUpdatedTimestampMillis() < evictionCutoff) {
485 iterator.remove();
486 }
487 });
488
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700489 return updateSpeed();
490 }
491
492 /**
493 * Updates the internal speed, returning true if the update resulted in a speed label change.
494 */
495 private boolean updateSpeed() {
496 int oldSpeed = mSpeed;
497 mSpeed = generateAverageSpeedForSsid();
498
499 // set speed to the connected ScanResult if the AccessPoint is the active network
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700500 if (isActive() && mInfo != null) {
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700501 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(mInfo.getBSSID());
502 if (timedScore != null) {
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700503 if (Log.isLoggable(TAG, Log.DEBUG)) {
504 Log.d(TAG, "Set score using specific access point curve for connected AP: "
505 + getSsidStr());
506 }
507 // TODO(b/63073866): Map using getLevel rather than specific rssi value so score
508 // doesn't change without a visible wifi bar change.
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700509 int speed = timedScore.getScore().calculateBadge(mInfo.getRssi());
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700510 if (speed != Speed.NONE) {
511 mSpeed = speed;
512 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800513 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700514 }
515
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700516 boolean changed = oldSpeed != mSpeed;
517 if(WifiTracker.sVerboseLogging && changed) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700518 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800519 }
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700520 return changed;
521 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800522
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700523 /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
524 @Speed private int generateAverageSpeedForSsid() {
525 if (mScoredNetworkCache.isEmpty()) {
526 return Speed.NONE;
527 }
528
529 if (Log.isLoggable(TAG, Log.DEBUG)) {
530 Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
531 getSsidStr(), mScoredNetworkCache));
532 }
533
534 int count = 0;
535 int totalSpeed = 0;
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700536 for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
537 int speed = timedScore.getScore().calculateBadge(mRssi);
Sundeep Ghuman6390fa82017-08-01 17:50:59 -0700538 if (speed != Speed.NONE) {
539 count++;
540 totalSpeed += speed;
541 }
542 }
543 int speed = count == 0 ? Speed.NONE : totalSpeed / count;
544 if (WifiTracker.sVerboseLogging) {
545 Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
546 }
547 return roundToClosestSpeedEnum(speed);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800548 }
549
Stephen Chen21f68682017-04-04 13:23:31 -0700550 /**
551 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
552 * true if the metering changed.
553 */
554 private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
555 boolean oldMetering = mIsScoredNetworkMetered;
556 mIsScoredNetworkMetered = false;
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700557
558 if (isActive() && mInfo != null) {
559 NetworkKey key = new NetworkKey(new WifiKey(
560 AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID()));
561 ScoredNetwork score = scoreCache.getScoredNetwork(key);
562 if (score != null) {
563 mIsScoredNetworkMetered |= score.meteredHint;
Stephen Chen21f68682017-04-04 13:23:31 -0700564 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700565 } else {
566 for (ScanResult result : mScanResultCache.values()) {
567 ScoredNetwork score = scoreCache.getScoredNetwork(result);
568 if (score == null) {
569 continue;
570 }
571 mIsScoredNetworkMetered |= score.meteredHint;
572 }
Stephen Chen21f68682017-04-04 13:23:31 -0700573 }
574 return oldMetering == mIsScoredNetworkMetered;
575 }
576
Mitchell Wills18af4932016-08-10 13:49:21 -0700577 private void evictOldScanResults() {
578 long nowMs = SystemClock.elapsedRealtime();
579 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
580 ScanResult result = iter.next();
581 // result timestamp is in microseconds
Sundeep Ghumana419b9b2017-08-15 15:47:18 -0700582 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MILLIS) {
Mitchell Wills18af4932016-08-10 13:49:21 -0700583 iter.remove();
584 }
585 }
586 }
587
Jason Monkd52356a2015-01-28 10:40:41 -0500588 public boolean matches(ScanResult result) {
589 return ssid.equals(result.SSID) && security == getSecurity(result);
590 }
591
592 public boolean matches(WifiConfiguration config) {
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100593 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
Shinji Sogof29e1222015-12-09 17:21:38 +0900594 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100595 } else {
596 return ssid.equals(removeDoubleQuotes(config.SSID))
597 && security == getSecurity(config)
598 && (mConfig == null || mConfig.shared == config.shared);
599 }
Jason Monkd52356a2015-01-28 10:40:41 -0500600 }
601
602 public WifiConfiguration getConfig() {
603 return mConfig;
604 }
605
Peter Qiuced37db2017-03-14 15:51:22 -0700606 public String getPasspointFqdn() {
607 return mFqdn;
608 }
609
Jason Monkd52356a2015-01-28 10:40:41 -0500610 public void clearConfig() {
611 mConfig = null;
612 networkId = WifiConfiguration.INVALID_NETWORK_ID;
613 }
614
615 public WifiInfo getInfo() {
616 return mInfo;
617 }
618
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700619 /**
620 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
621 *
622 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
623 * always return at least 0.
624 */
Jason Monkd52356a2015-01-28 10:40:41 -0500625 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800626 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500627 }
628
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700629 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800630 return mRssi;
631 }
632
633 /**
634 * Updates {@link #mRssi}.
635 *
636 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
637 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700638 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
639 * value. If the access point is not connected and there are no scan results, the rssi will be
640 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800641 */
642 private void updateRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800643 if (this.isActive()) {
644 return;
645 }
646
647 int rssi = UNREACHABLE_RSSI;
Mitchell Wills18af4932016-08-10 13:49:21 -0700648 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700649 if (result.level > rssi) {
650 rssi = result.level;
651 }
652 }
653
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700654 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
655 mRssi = (mRssi + rssi) / 2; // half-life previous value
656 } else {
657 mRssi = rssi;
658 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700659 }
660
Sundeep Ghumand1e44922017-08-07 11:21:38 -0700661 /** Updates {@link #mSeen} based on the scan result cache. */
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800662 private void updateSeen() {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700663 long seen = 0;
Mitchell Wills18af4932016-08-10 13:49:21 -0700664 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700665 if (result.timestamp > seen) {
666 seen = result.timestamp;
667 }
668 }
669
Sundeep Ghuman24128172017-06-15 17:55:21 -0700670 // Only replace the previous value if we have a recent scan result to use
671 if (seen != 0) {
672 mSeen = seen;
673 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700674 }
675
Stephen Chen21f68682017-04-04 13:23:31 -0700676 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600677 * Returns if the network should be considered metered.
Stephen Chen21f68682017-04-04 13:23:31 -0700678 */
679 public boolean isMetered() {
680 return mIsScoredNetworkMetered
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600681 || WifiConfiguration.isMetered(mConfig, mInfo);
Stephen Chen21f68682017-04-04 13:23:31 -0700682 }
683
Jason Monkd52356a2015-01-28 10:40:41 -0500684 public NetworkInfo getNetworkInfo() {
685 return mNetworkInfo;
686 }
687
688 public int getSecurity() {
689 return security;
690 }
691
692 public String getSecurityString(boolean concise) {
693 Context context = mContext;
Tomoharu Hatano2bde6e72017-05-30 18:38:56 +0900694 if (isPasspoint() || isPasspointConfig()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700695 return concise ? context.getString(R.string.wifi_security_short_eap) :
696 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700697 }
Jason Monkd52356a2015-01-28 10:40:41 -0500698 switch(security) {
699 case SECURITY_EAP:
700 return concise ? context.getString(R.string.wifi_security_short_eap) :
701 context.getString(R.string.wifi_security_eap);
702 case SECURITY_PSK:
703 switch (pskType) {
704 case PSK_WPA:
705 return concise ? context.getString(R.string.wifi_security_short_wpa) :
706 context.getString(R.string.wifi_security_wpa);
707 case PSK_WPA2:
708 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
709 context.getString(R.string.wifi_security_wpa2);
710 case PSK_WPA_WPA2:
711 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
712 context.getString(R.string.wifi_security_wpa_wpa2);
713 case PSK_UNKNOWN:
714 default:
715 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
716 : context.getString(R.string.wifi_security_psk_generic);
717 }
718 case SECURITY_WEP:
719 return concise ? context.getString(R.string.wifi_security_short_wep) :
720 context.getString(R.string.wifi_security_wep);
721 case SECURITY_NONE:
722 default:
723 return concise ? "" : context.getString(R.string.wifi_security_none);
724 }
725 }
726
Jason Monk6980d122015-06-15 10:07:55 -0400727 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500728 return ssid;
729 }
730
Jason Monk60a82ff2016-02-25 13:55:03 -0500731 public String getBssid() {
732 return bssid;
733 }
734
Jason Monk6980d122015-06-15 10:07:55 -0400735 public CharSequence getSsid() {
Fan Zhangeb83a0d2016-09-21 11:34:08 -0700736 final SpannableString str = new SpannableString(ssid);
737 str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
Jason Monk6980d122015-06-15 10:07:55 -0400738 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
739 return str;
740 }
741
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700742 public String getConfigName() {
743 if (mConfig != null && mConfig.isPasspoint()) {
744 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700745 } else if (mFqdn != null) {
746 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700747 } else {
748 return ssid;
749 }
750 }
751
Jason Monkd52356a2015-01-28 10:40:41 -0500752 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700753 if (mNetworkInfo != null) {
754 return mNetworkInfo.getDetailedState();
755 }
756 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
757 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500758 }
759
Peter Qiu280581b2017-07-24 14:18:56 -0700760 public boolean isCarrierAp() {
761 return mIsCarrierAp;
762 }
763
764 public int getCarrierApEapType() {
765 return mCarrierApEapType;
766 }
767
768 public String getCarrierName() {
769 return mCarrierName;
770 }
771
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700772 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700773 WifiConfiguration config = mConfig;
774 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700775 PackageManager pm = mContext.getPackageManager();
776 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700777 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700778 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700779 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700780 appInfo = mContext.getApplicationInfo();
781 } else {
782 try {
783 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700784 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700785 } catch (RemoteException rex) {
786 }
787 }
788 if (appInfo != null &&
789 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
790 !appInfo.packageName.equals(
791 mContext.getString(R.string.certinstaller_package))) {
792 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
793 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700794 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700795 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700796 }
797
Jason Monkd52356a2015-01-28 10:40:41 -0500798 public String getSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700799 return getSettingsSummary(mConfig);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700800 }
801
802 public String getSettingsSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700803 return getSettingsSummary(mConfig);
804 }
805
806 private String getSettingsSummary(WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500807 // Update to new summary
808 StringBuilder summary = new StringBuilder();
809
Fan Zhang51365c32016-09-20 12:22:18 -0700810 if (isActive() && config != null && config.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700811 // This is the active connection on passpoint
Jason Monkd52356a2015-01-28 10:40:41 -0500812 summary.append(getSummary(mContext, getDetailedState(),
Fan Zhang51365c32016-09-20 12:22:18 -0700813 false, config.providerFriendlyName));
Peter Qiu280581b2017-07-24 14:18:56 -0700814 } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
815 && mIsCarrierAp) {
816 summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700817 } else if (isActive()) {
818 // This is the active connection on non-passpoint network
819 summary.append(getSummary(mContext, getDetailedState(),
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700820 mInfo != null && mInfo.isEphemeral()));
Yuxin Chang6b750862017-01-11 14:59:17 +0900821 } else if (config != null && config.isPasspoint()
822 && config.getNetworkSelectionStatus().isNetworkEnabled()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700823 String format = mContext.getString(R.string.available_via_passpoint);
Fan Zhang51365c32016-09-20 12:22:18 -0700824 summary.append(String.format(format, config.providerFriendlyName));
825 } else if (config != null && config.hasNoInternetAccess()) {
Salvador Martinez5d937fc2016-09-23 08:54:20 -0700826 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
827 ? R.string.wifi_no_internet_no_reconnect
828 : R.string.wifi_no_internet;
829 summary.append(mContext.getString(messageID));
Fan Zhang51365c32016-09-20 12:22:18 -0700830 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
xinhef7705c32015-12-01 14:44:37 -0800831 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700832 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800833 switch (networkStatus.getNetworkSelectionDisableReason()) {
834 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
Jason Monkd52356a2015-01-28 10:40:41 -0500835 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
xinhef7705c32015-12-01 14:44:37 -0800836 break;
Peter Qiu9c4c6ad2017-06-20 13:17:36 -0700837 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
838 summary.append(mContext.getString(R.string.wifi_check_password_try_again));
839 break;
xinhef7705c32015-12-01 14:44:37 -0800840 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
841 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
842 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
843 break;
844 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
845 summary.append(mContext.getString(R.string.wifi_disabled_generic));
846 break;
Jason Monkd52356a2015-01-28 10:40:41 -0500847 }
Amin Shaikh98773d42017-02-02 17:50:12 -0800848 } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
849 summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
Peter Qiu280581b2017-07-24 14:18:56 -0700850 } else if (mIsCarrierAp) {
851 summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
Dave Schaefer98537432017-02-08 11:26:08 -0800852 } else if (!isReachable()) { // Wifi out of range
Jason Monkd52356a2015-01-28 10:40:41 -0500853 summary.append(mContext.getString(R.string.wifi_not_in_range));
854 } else { // In range, not disabled.
Fan Zhang51365c32016-09-20 12:22:18 -0700855 if (config != null) { // Is saved network
Glen Kuhne446afac2017-06-22 16:02:33 -0700856 // Last attempt to connect to this failed. Show reason why
857 switch (config.recentFailure.getAssociationStatus()) {
858 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
859 summary.append(mContext.getString(
860 R.string.wifi_ap_unable_to_handle_new_sta));
861 break;
862 default:
863 // "Saved"
864 summary.append(mContext.getString(R.string.wifi_remembered));
865 break;
866 }
Jason Monkd52356a2015-01-28 10:40:41 -0500867 }
868 }
869
Sundeep Ghuman39ad5d82017-07-11 19:03:51 -0700870 if (WifiTracker.sVerboseLogging) {
Jason Monkd52356a2015-01-28 10:40:41 -0500871 // Add RSSI/band information for this config, what was seen up to 6 seconds ago
872 // verbose WiFi Logging is only turned on thru developers settings
Eric Schwarzenbachb77d3d72017-07-18 15:05:44 -0700873 if (isActive() && mInfo != null) {
Jason Monkd52356a2015-01-28 10:40:41 -0500874 summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
875 }
876 summary.append(" " + getVisibilityStatus());
Fan Zhang51365c32016-09-20 12:22:18 -0700877 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
878 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
879 if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
Jason Monkd52356a2015-01-28 10:40:41 -0500880 long now = System.currentTimeMillis();
Fan Zhang51365c32016-09-20 12:22:18 -0700881 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
Jason Monkd52356a2015-01-28 10:40:41 -0500882 long sec = diff%60; //seconds
883 long min = (diff/60)%60; //minutes
884 long hour = (min/60)%60; //hours
885 summary.append(", ");
886 if (hour > 0) summary.append(Long.toString(hour) + "h ");
887 summary.append( Long.toString(min) + "m ");
888 summary.append( Long.toString(sec) + "s ");
889 }
890 summary.append(")");
891 }
xinhef7705c32015-12-01 14:44:37 -0800892
Fan Zhang51365c32016-09-20 12:22:18 -0700893 if (config != null) {
xinhef7705c32015-12-01 14:44:37 -0800894 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700895 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800896 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
897 index < WifiConfiguration.NetworkSelectionStatus
898 .NETWORK_SELECTION_DISABLED_MAX; index++) {
899 if (networkStatus.getDisableReasonCounter(index) != 0) {
900 summary.append(" " + WifiConfiguration.NetworkSelectionStatus
901 .getNetworkDisableReasonString(index) + "="
902 + networkStatus.getDisableReasonCounter(index));
903 }
904 }
Jason Monkd52356a2015-01-28 10:40:41 -0500905 }
906 }
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700907
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700908 // If Speed label and summary are both present, use the preference combination to combine
909 // the two, else return the non-null one.
910 if (getSpeedLabel() != null && summary.length() != 0) {
Sundeep Ghumand3171ca2017-07-12 23:02:24 -0700911 return mContext.getResources().getString(
912 R.string.preference_summary_default_combination,
913 getSpeedLabel(),
914 summary.toString());
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700915 } else if (getSpeedLabel() != null) {
916 return getSpeedLabel();
Sundeep Ghumand3171ca2017-07-12 23:02:24 -0700917 } else {
918 return summary.toString();
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700919 }
Jason Monkd52356a2015-01-28 10:40:41 -0500920 }
921
922 /**
923 * Returns the visibility status of the WifiConfiguration.
924 *
925 * @return autojoin debugging information
926 * TODO: use a string formatter
927 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
928 * For instance [-40,5/-30,2]
929 */
930 private String getVisibilityStatus() {
931 StringBuilder visibility = new StringBuilder();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700932 StringBuilder scans24GHz = new StringBuilder();
933 StringBuilder scans5GHz = new StringBuilder();
Jason Monkd52356a2015-01-28 10:40:41 -0500934 String bssid = null;
935
936 long now = System.currentTimeMillis();
937
Eric Schwarzenbachb77d3d72017-07-18 15:05:44 -0700938 if (isActive() && mInfo != null) {
Jason Monkd52356a2015-01-28 10:40:41 -0500939 bssid = mInfo.getBSSID();
940 if (bssid != null) {
941 visibility.append(" ").append(bssid);
942 }
943 visibility.append(" rssi=").append(mInfo.getRssi());
944 visibility.append(" ");
945 visibility.append(" score=").append(mInfo.score);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700946 if (mSpeed != Speed.NONE) {
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700947 visibility.append(" speed=").append(getSpeedLabel());
948 }
Jason Monkd52356a2015-01-28 10:40:41 -0500949 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
950 visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
951 visibility.append(String.format("%.1f ", mInfo.txBadRate));
952 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
953 }
954
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700955 int maxRssi5 = WifiConfiguration.INVALID_RSSI;
956 int maxRssi24 = WifiConfiguration.INVALID_RSSI;
957 final int maxDisplayedScans = 4;
958 int num5 = 0; // number of scanned BSSID on 5GHz band
959 int num24 = 0; // number of scanned BSSID on 2.4Ghz band
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700960 int numBlackListed = 0;
Mitchell Wills18af4932016-08-10 13:49:21 -0700961 evictOldScanResults();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700962
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700963 // TODO: sort list by RSSI or age
Mitchell Wills18af4932016-08-10 13:49:21 -0700964 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700965 if (result.frequency >= LOWER_FREQ_5GHZ
966 && result.frequency <= HIGHER_FREQ_5GHZ) {
967 // Strictly speaking: [4915, 5825]
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700968 num5++;
969
970 if (result.level > maxRssi5) {
971 maxRssi5 = result.level;
972 }
973 if (num5 <= maxDisplayedScans) {
974 scans5GHz.append(verboseScanResultSummary(result, bssid));
975 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700976 } else if (result.frequency >= LOWER_FREQ_24GHZ
977 && result.frequency <= HIGHER_FREQ_24GHZ) {
978 // Strictly speaking: [2412, 2482]
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700979 num24++;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700980
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700981 if (result.level > maxRssi24) {
982 maxRssi24 = result.level;
Jason Monkd52356a2015-01-28 10:40:41 -0500983 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700984 if (num24 <= maxDisplayedScans) {
985 scans24GHz.append(verboseScanResultSummary(result, bssid));
Jason Monkd52356a2015-01-28 10:40:41 -0500986 }
987 }
988 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700989 visibility.append(" [");
990 if (num24 > 0) {
991 visibility.append("(").append(num24).append(")");
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700992 if (num24 > maxDisplayedScans) {
993 visibility.append("max=").append(maxRssi24).append(",");
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700994 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700995 visibility.append(scans24GHz.toString());
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700996 }
997 visibility.append(";");
998 if (num5 > 0) {
999 visibility.append("(").append(num5).append(")");
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001000 if (num5 > maxDisplayedScans) {
1001 visibility.append("max=").append(maxRssi5).append(",");
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001002 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001003 visibility.append(scans5GHz.toString());
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001004 }
1005 if (numBlackListed > 0)
1006 visibility.append("!").append(numBlackListed);
1007 visibility.append("]");
Jason Monkd52356a2015-01-28 10:40:41 -05001008
1009 return visibility.toString();
1010 }
1011
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001012 @VisibleForTesting
1013 /* package */ String verboseScanResultSummary(ScanResult result, String bssid) {
1014 StringBuilder stringBuilder = new StringBuilder();
1015 stringBuilder.append(" \n{").append(result.BSSID);
1016 if (result.BSSID.equals(bssid)) {
1017 stringBuilder.append("*");
1018 }
1019 stringBuilder.append("=").append(result.frequency);
1020 stringBuilder.append(",").append(result.level);
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001021 int speed = getSpecificApSpeed(result);
1022 if (speed != Speed.NONE) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001023 stringBuilder.append(",")
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001024 .append(getSpeedLabel(speed));
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001025 }
1026 stringBuilder.append("}");
1027 return stringBuilder.toString();
1028 }
1029
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001030 @Speed private int getSpecificApSpeed(ScanResult result) {
Sundeep Ghumana419b9b2017-08-15 15:47:18 -07001031 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
1032 if (timedScore == null) {
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001033 return Speed.NONE;
1034 }
1035 // For debugging purposes we may want to use mRssi rather than result.level as the average
1036 // speed wil be determined by mRssi
Sundeep Ghumana419b9b2017-08-15 15:47:18 -07001037 return timedScore.getScore().calculateBadge(result.level);
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001038 }
1039
Jason Monkd52356a2015-01-28 10:40:41 -05001040 /**
1041 * Return whether this is the active connection.
1042 * For ephemeral connections (networkId is invalid), this returns false if the network is
1043 * disconnected.
1044 */
1045 public boolean isActive() {
1046 return mNetworkInfo != null &&
1047 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1048 mNetworkInfo.getState() != State.DISCONNECTED);
1049 }
1050
1051 public boolean isConnectable() {
1052 return getLevel() != -1 && getDetailedState() == null;
1053 }
1054
1055 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001056 return mInfo != null && mInfo.isEphemeral() &&
1057 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -05001058 }
1059
Peter Qiuced37db2017-03-14 15:51:22 -07001060 /**
1061 * Return true if this AccessPoint represents a Passpoint AP.
1062 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001063 public boolean isPasspoint() {
1064 return mConfig != null && mConfig.isPasspoint();
1065 }
1066
Mitchell Wills5a42db22015-08-03 09:46:08 -07001067 /**
Peter Qiuced37db2017-03-14 15:51:22 -07001068 * Return true if this AccessPoint represents a Passpoint provider configuration.
1069 */
1070 public boolean isPasspointConfig() {
1071 return mFqdn != null;
1072 }
1073
1074 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -07001075 * Return whether the given {@link WifiInfo} is for this access point.
1076 * If the current AP does not have a network Id then the config is used to
1077 * match based on SSID and security.
1078 */
1079 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001080 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -05001081 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001082 } else if (config != null) {
1083 return matches(config);
1084 }
1085 else {
Jason Monkd52356a2015-01-28 10:40:41 -05001086 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1087 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1088 // TODO: Handle hex string SSIDs.
1089 return ssid.equals(removeDoubleQuotes(info.getSSID()));
1090 }
1091 }
1092
1093 public boolean isSaved() {
1094 return networkId != WifiConfiguration.INVALID_NETWORK_ID;
1095 }
1096
1097 public Object getTag() {
1098 return mTag;
1099 }
1100
1101 public void setTag(Object tag) {
1102 mTag = tag;
1103 }
1104
1105 /**
1106 * Generate and save a default wifiConfiguration with common values.
1107 * Can only be called for unsecured networks.
1108 */
1109 public void generateOpenNetworkConfig() {
1110 if (security != SECURITY_NONE)
1111 throw new IllegalStateException();
1112 if (mConfig != null)
1113 return;
1114 mConfig = new WifiConfiguration();
1115 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
1116 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1117 }
1118
1119 void loadConfig(WifiConfiguration config) {
Peter Qiu2c3b5ee22017-02-01 11:49:15 -08001120 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
Jason Monk60a82ff2016-02-25 13:55:03 -05001121 bssid = config.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -05001122 security = getSecurity(config);
1123 networkId = config.networkId;
1124 mConfig = config;
1125 }
1126
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001127 private void initWithScanResult(ScanResult result) {
Jason Monkd52356a2015-01-28 10:40:41 -05001128 ssid = result.SSID;
Jason Monk60a82ff2016-02-25 13:55:03 -05001129 bssid = result.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -05001130 security = getSecurity(result);
1131 if (security == SECURITY_PSK)
1132 pskType = getPskType(result);
Sundeep Ghuman24128172017-06-15 17:55:21 -07001133
1134 mScanResultCache.put(result.BSSID, result);
1135 updateRssi();
1136 mSeen = result.timestamp; // even if the timestamp is old it is still valid
Peter Qiu280581b2017-07-24 14:18:56 -07001137 mIsCarrierAp = result.isCarrierAp;
1138 mCarrierApEapType = result.carrierApEapType;
1139 mCarrierName = result.carrierName;
Jason Monkd52356a2015-01-28 10:40:41 -05001140 }
1141
1142 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001143 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1144 savedState.putInt(KEY_SECURITY, security);
Sundeep Ghumana28050a2017-07-12 22:09:25 -07001145 savedState.putInt(KEY_SPEED, mSpeed);
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001146 savedState.putInt(KEY_PSKTYPE, pskType);
1147 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -05001148 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Mitchell Wills18af4932016-08-10 13:49:21 -07001149 evictOldScanResults();
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001150 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
Mitchell Wills18af4932016-08-10 13:49:21 -07001151 new ArrayList<ScanResult>(mScanResultCache.values()));
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001152 savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1153 new ArrayList<>(mScoredNetworkCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -05001154 if (mNetworkInfo != null) {
1155 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1156 }
Peter Qiuced37db2017-03-14 15:51:22 -07001157 if (mFqdn != null) {
1158 savedState.putString(KEY_FQDN, mFqdn);
1159 }
1160 if (mProviderFriendlyName != null) {
1161 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1162 }
Peter Qiu280581b2017-07-24 14:18:56 -07001163 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1164 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1165 savedState.putString(KEY_CARRIER_NAME, mCarrierName);
Jason Monkd52356a2015-01-28 10:40:41 -05001166 }
1167
1168 public void setListener(AccessPointListener listener) {
1169 mAccessPointListener = listener;
1170 }
1171
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001172 /**
1173 * Update the AP with the given scan result.
1174 *
1175 * @param result the ScanResult to add to the AccessPoint scan cache
1176 * @param evictOldScanResults whether stale scan results should be removed
1177 * from the cache during this update process
1178 * @return true if the scan result update caused a change in state which would impact ranking
1179 * or AccessPoint rendering (e.g. wifi level, security)
1180 */
1181 boolean update(ScanResult result, boolean evictOldScanResults) {
Mitchell Wills5a42db22015-08-03 09:46:08 -07001182 if (matches(result)) {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001183 int oldLevel = getLevel();
1184
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001185 /* Add or update the scan result for the BSSID */
1186 mScanResultCache.put(result.BSSID, result);
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001187 if (evictOldScanResults) evictOldScanResults();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001188 updateSeen();
1189 updateRssi();
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001190 int newLevel = getLevel();
1191
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001192 if (newLevel > 0 && newLevel != oldLevel) {
1193 // Only update labels on visible rssi changes
1194 updateSpeed();
1195 if (mAccessPointListener != null) {
1196 mAccessPointListener.onLevelChanged(this);
1197 }
Jason Monkd52356a2015-01-28 10:40:41 -05001198 }
1199 // This flag only comes from scans, is not easily saved in config
1200 if (security == SECURITY_PSK) {
1201 pskType = getPskType(result);
1202 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001203
Jason Monkd52356a2015-01-28 10:40:41 -05001204 if (mAccessPointListener != null) {
1205 mAccessPointListener.onAccessPointChanged(this);
1206 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001207
Peter Qiu280581b2017-07-24 14:18:56 -07001208 // The carrier info in the ScanResult is set by the platform based on the SSID and will
1209 // always be the same for all matching scan results.
1210 mIsCarrierAp = result.isCarrierAp;
1211 mCarrierApEapType = result.carrierApEapType;
1212 mCarrierName = result.carrierName;
1213
Jason Monkd52356a2015-01-28 10:40:41 -05001214 return true;
1215 }
1216 return false;
1217 }
1218
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001219 /** Attempt to update the AccessPoint and return true if an update occurred. */
Sundeep Ghumand911da32017-07-05 20:06:05 -07001220 public boolean update(
1221 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001222 boolean updated = false;
1223 final int oldLevel = getLevel();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001224 if (info != null && isInfoForThisAccessPoint(config, info)) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001225 updated = (mInfo == null);
Sundeep Ghumanf4d33022017-06-05 19:47:36 -07001226 if (mConfig != config) {
1227 // We do not set updated = true as we do not want to increase the amount of sorting
1228 // and copying performed in WifiTracker at this time. If issues involving refresh
1229 // are still seen, we will investigate further.
1230 update(config); // Notifies the AccessPointListener of the change
1231 }
Glen Kuhned38708c2017-07-19 14:53:34 -07001232 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001233 mRssi = info.getRssi();
1234 updated = true;
Sundeep Ghuman5c5cd7a2017-05-03 12:45:44 -07001235 } else if (mNetworkInfo != null && networkInfo != null
1236 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
Sundeep Ghuman96a53572017-04-20 21:25:41 -07001237 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001238 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001239 mInfo = info;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001240 mNetworkInfo = networkInfo;
Jason Monkd52356a2015-01-28 10:40:41 -05001241 } else if (mInfo != null) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001242 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001243 mInfo = null;
1244 mNetworkInfo = null;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001245 }
1246 if (updated && mAccessPointListener != null) {
1247 mAccessPointListener.onAccessPointChanged(this);
1248
1249 if (oldLevel != getLevel() /* current level */) {
1250 mAccessPointListener.onLevelChanged(this);
Jason Monkd52356a2015-01-28 10:40:41 -05001251 }
1252 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001253 return updated;
Jason Monkd52356a2015-01-28 10:40:41 -05001254 }
1255
Sundeep Ghumand911da32017-07-05 20:06:05 -07001256 void update(@Nullable WifiConfiguration config) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001257 mConfig = config;
Sundeep Ghumand911da32017-07-05 20:06:05 -07001258 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001259 if (mAccessPointListener != null) {
1260 mAccessPointListener.onAccessPointChanged(this);
1261 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001262 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001263
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001264 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -07001265 void setRssi(int rssi) {
1266 mRssi = rssi;
1267 }
1268
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001269 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1270 void setUnreachable() {
1271 setRssi(AccessPoint.UNREACHABLE_RSSI);
1272 }
1273
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001274 int getSpeed() { return mSpeed;}
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001275
1276 @Nullable
1277 String getSpeedLabel() {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001278 return getSpeedLabel(mSpeed);
1279 }
1280
1281 @Nullable
Sundeep Ghuman6390fa82017-08-01 17:50:59 -07001282 @Speed
1283 private int roundToClosestSpeedEnum(int speed) {
1284 if (speed < Speed.SLOW) {
1285 return Speed.NONE;
1286 } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1287 return Speed.SLOW;
1288 } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1289 return Speed.MODERATE;
1290 } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1291 return Speed.FAST;
1292 } else {
1293 return Speed.VERY_FAST;
1294 }
1295 }
1296
1297 @Nullable
1298 private String getSpeedLabel(@Speed int speed) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001299 switch (speed) {
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001300 case Speed.VERY_FAST:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001301 return mContext.getString(R.string.speed_label_very_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001302 case Speed.FAST:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001303 return mContext.getString(R.string.speed_label_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001304 case Speed.MODERATE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001305 return mContext.getString(R.string.speed_label_okay);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001306 case Speed.SLOW:
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001307 return mContext.getString(R.string.speed_label_slow);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001308 case Speed.NONE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001309 default:
1310 return null;
1311 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -08001312 }
1313
Dave Schaefer98537432017-02-08 11:26:08 -08001314 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -07001315 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -08001316 return mRssi != UNREACHABLE_RSSI;
1317 }
1318
Jason Monkd52356a2015-01-28 10:40:41 -05001319 public static String getSummary(Context context, String ssid, DetailedState state,
Vinit Deshpandefc406002015-04-15 18:10:55 -07001320 boolean isEphemeral, String passpointProvider) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001321 if (state == DetailedState.CONNECTED && ssid == null) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001322 if (TextUtils.isEmpty(passpointProvider) == false) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001323 // Special case for connected + passpoint networks.
Vinit Deshpandefc406002015-04-15 18:10:55 -07001324 String format = context.getString(R.string.connected_via_passpoint);
1325 return String.format(format, passpointProvider);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001326 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001327 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001328 final NetworkScoreManager networkScoreManager = context.getSystemService(
1329 NetworkScoreManager.class);
1330 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1331 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1332 String format = context.getString(R.string.connected_via_network_scorer);
1333 return String.format(format, scorer.getRecommendationServiceLabel());
1334 } else {
1335 return context.getString(R.string.connected_via_network_scorer_default);
1336 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001337 }
Jason Monkd52356a2015-01-28 10:40:41 -05001338 }
1339
Sanket Padawe7094d222015-05-01 16:55:00 -07001340 // Case when there is wifi connected without internet connectivity.
1341 final ConnectivityManager cm = (ConnectivityManager)
1342 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1343 if (state == DetailedState.CONNECTED) {
1344 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1345 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001346 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001347
1348 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001349 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1350 } catch (RemoteException e) {}
1351
1352 if (nc != null) {
1353 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
Maurice Lam7f6fc862017-07-12 16:43:49 -07001354 int id = context.getResources()
1355 .getIdentifier("network_available_sign_in", "string", "android");
1356 return context.getString(id);
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001357 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1358 return context.getString(R.string.wifi_connected_no_internet);
1359 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001360 }
1361 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001362 if (state == null) {
1363 Log.w(TAG, "state is null, returning empty summary");
1364 return "";
1365 }
Jason Monkd52356a2015-01-28 10:40:41 -05001366 String[] formats = context.getResources().getStringArray((ssid == null)
1367 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1368 int index = state.ordinal();
1369
1370 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001371 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001372 }
1373 return String.format(formats[index], ssid);
1374 }
1375
1376 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001377 return getSummary(context, null, state, isEphemeral, null);
1378 }
1379
1380 public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1381 String passpointProvider) {
1382 return getSummary(context, null, state, isEphemeral, passpointProvider);
Jason Monkd52356a2015-01-28 10:40:41 -05001383 }
1384
1385 public static String convertToQuotedString(String string) {
1386 return "\"" + string + "\"";
1387 }
1388
1389 private static int getPskType(ScanResult result) {
1390 boolean wpa = result.capabilities.contains("WPA-PSK");
1391 boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1392 if (wpa2 && wpa) {
1393 return PSK_WPA_WPA2;
1394 } else if (wpa2) {
1395 return PSK_WPA2;
1396 } else if (wpa) {
1397 return PSK_WPA;
1398 } else {
1399 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1400 return PSK_UNKNOWN;
1401 }
1402 }
1403
1404 private static int getSecurity(ScanResult result) {
1405 if (result.capabilities.contains("WEP")) {
1406 return SECURITY_WEP;
1407 } else if (result.capabilities.contains("PSK")) {
1408 return SECURITY_PSK;
1409 } else if (result.capabilities.contains("EAP")) {
1410 return SECURITY_EAP;
1411 }
1412 return SECURITY_NONE;
1413 }
1414
1415 static int getSecurity(WifiConfiguration config) {
1416 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1417 return SECURITY_PSK;
1418 }
1419 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1420 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1421 return SECURITY_EAP;
1422 }
1423 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1424 }
1425
1426 public static String securityToString(int security, int pskType) {
1427 if (security == SECURITY_WEP) {
1428 return "WEP";
1429 } else if (security == SECURITY_PSK) {
1430 if (pskType == PSK_WPA) {
1431 return "WPA";
1432 } else if (pskType == PSK_WPA2) {
1433 return "WPA2";
1434 } else if (pskType == PSK_WPA_WPA2) {
1435 return "WPA_WPA2";
1436 }
1437 return "PSK";
1438 } else if (security == SECURITY_EAP) {
1439 return "EAP";
1440 }
1441 return "NONE";
1442 }
1443
1444 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001445 if (TextUtils.isEmpty(string)) {
1446 return "";
1447 }
Jason Monkd52356a2015-01-28 10:40:41 -05001448 int length = string.length();
1449 if ((length > 1) && (string.charAt(0) == '"')
1450 && (string.charAt(length - 1) == '"')) {
1451 return string.substring(1, length - 1);
1452 }
1453 return string;
1454 }
1455
1456 public interface AccessPointListener {
1457 void onAccessPointChanged(AccessPoint accessPoint);
1458 void onLevelChanged(AccessPoint accessPoint);
1459 }
1460}