blob: 37969e01b94f2afb45301175b15c7af8919f6e27 [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 Ghumanfedf4612017-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;
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -070067import java.util.Objects;
Mitchell Wills18af4932016-08-10 13:49:21 -070068import java.util.concurrent.ConcurrentHashMap;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -070069import java.util.concurrent.atomic.AtomicInteger;
Jason Monkd52356a2015-01-28 10:40:41 -050070
71
72public class AccessPoint implements Comparable<AccessPoint> {
73 static final String TAG = "SettingsLib.AccessPoint";
74
75 /**
76 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
77 */
78 public static final int LOWER_FREQ_24GHZ = 2400;
79
80 /**
81 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
82 */
83 public static final int HIGHER_FREQ_24GHZ = 2500;
84
85 /**
86 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
87 */
88 public static final int LOWER_FREQ_5GHZ = 4900;
89
90 /**
91 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
92 */
93 public static final int HIGHER_FREQ_5GHZ = 5900;
94
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070095 @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST})
96 @Retention(RetentionPolicy.SOURCE)
97 public @interface Speed {
98 /**
99 * Constant value representing an unlabeled / unscored network.
100 */
101 int NONE = 0;
102 /**
103 * Constant value representing a slow speed network connection.
104 */
105 int SLOW = 5;
106 /**
107 * Constant value representing a medium speed network connection.
108 */
109 int MODERATE = 10;
110 /**
111 * Constant value representing a fast speed network connection.
112 */
113 int FAST = 20;
114 /**
115 * Constant value representing a very fast speed network connection.
116 */
117 int VERY_FAST = 30;
118 }
Jason Monkd52356a2015-01-28 10:40:41 -0500119
120 /**
121 * Experimental: we should be able to show the user the list of BSSIDs and bands
122 * for that SSID.
123 * For now this data is used only with Verbose Logging so as to show the band and number
124 * of BSSIDs on which that network is seen.
125 */
Mitchell Wills18af4932016-08-10 13:49:21 -0700126 private final ConcurrentHashMap<String, ScanResult> mScanResultCache =
127 new ConcurrentHashMap<String, ScanResult>(32);
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700128
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700129 /**
130 * Map of BSSIDs to scored networks for individual bssids.
131 *
132 * <p>This cache should not be evicted with scan results, as the values here are used to
133 * generate a fallback in the absence of scores for the visible APs.
134 */
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700135 private final Map<String, TimestampedScoredNetwork> mScoredNetworkCache = new HashMap<>();
136
137 /** Maximum age in millis of cached scored networks in {@link #mScoredNetworkCache}. */
138 @VisibleForTesting static final long MAX_CACHED_SCORE_AGE_MILLIS =
139 24 * DateUtils.DAY_IN_MILLIS;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700140
Sundeep Ghuman42058742017-07-21 18:42:10 -0700141 /** Maximum age of scan results to hold onto while actively scanning. **/
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700142 private static final long MAX_SCAN_RESULT_AGE_MILLIS = 15000;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700143
Dave Schaefer98537432017-02-08 11:26:08 -0800144 static final String KEY_NETWORKINFO = "key_networkinfo";
145 static final String KEY_WIFIINFO = "key_wifiinfo";
146 static final String KEY_SCANRESULT = "key_scanresult";
147 static final String KEY_SSID = "key_ssid";
148 static final String KEY_SECURITY = "key_security";
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700149 static final String KEY_SPEED = "key_speed";
Dave Schaefer98537432017-02-08 11:26:08 -0800150 static final String KEY_PSKTYPE = "key_psktype";
151 static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700152 static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
Dave Schaefer98537432017-02-08 11:26:08 -0800153 static final String KEY_CONFIG = "key_config";
Peter Qiuced37db2017-03-14 15:51:22 -0700154 static final String KEY_FQDN = "key_fqdn";
155 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
Peter Qiu280581b2017-07-24 14:18:56 -0700156 static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
157 static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
158 static final String KEY_CARRIER_NAME = "key_carrier_name";
Dave Schaefer98537432017-02-08 11:26:08 -0800159 static final AtomicInteger sLastId = new AtomicInteger(0);
Jason Monkd52356a2015-01-28 10:40:41 -0500160
161 /**
162 * These values are matched in string arrays -- changes must be kept in sync
163 */
164 public static final int SECURITY_NONE = 0;
165 public static final int SECURITY_WEP = 1;
166 public static final int SECURITY_PSK = 2;
167 public static final int SECURITY_EAP = 3;
168
169 private static final int PSK_UNKNOWN = 0;
170 private static final int PSK_WPA = 1;
171 private static final int PSK_WPA2 = 2;
172 private static final int PSK_WPA_WPA2 = 3;
173
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700174 /**
175 * The number of distinct wifi levels.
176 *
177 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
178 */
179 public static final int SIGNAL_LEVELS = 5;
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800180
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700181 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
Dave Schaefer98537432017-02-08 11:26:08 -0800182
Jason Monkd52356a2015-01-28 10:40:41 -0500183 private final Context mContext;
184
185 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500186 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500187 private int security;
188 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
189
190 private int pskType = PSK_UNKNOWN;
191
192 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500193
Dave Schaefer98537432017-02-08 11:26:08 -0800194 private int mRssi = UNREACHABLE_RSSI;
Jason Monkd52356a2015-01-28 10:40:41 -0500195
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 Ghumanbe3a74c2017-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 Ghumanbe3a74c2017-08-01 17:50:59 -0700252 if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700253 ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700254 savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700255 for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
256 mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
Sundeep Ghumanbe3a74c2017-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();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700278 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500279 }
280
Peter Qiuced37db2017-03-14 15:51:22 -0700281 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500282 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700283 loadConfig(config);
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700284 mId = sLastId.incrementAndGet();
Jason Monkd52356a2015-01-28 10:40:41 -0500285 }
286
Peter Qiuced37db2017-03-14 15:51:22 -0700287 /**
288 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
289 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
290 */
291 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500292 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700293 mFqdn = config.getHomeSp().getFqdn();
294 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700295 mId = sLastId.incrementAndGet();
296 }
297
298 AccessPoint(Context context, AccessPoint other) {
299 mContext = context;
300 copyFrom(other);
301 }
302
Peter Qiuced37db2017-03-14 15:51:22 -0700303 AccessPoint(Context context, ScanResult result) {
304 mContext = context;
305 initWithScanResult(result);
306 mId = sLastId.incrementAndGet();
307 }
308
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700309 /**
310 * Copy accesspoint information. NOTE: We do not copy tag information because that is never
311 * set on the internal copy.
312 * @param that
313 */
314 void copyFrom(AccessPoint that) {
315 that.evictOldScanResults();
316 this.ssid = that.ssid;
317 this.bssid = that.bssid;
318 this.security = that.security;
319 this.networkId = that.networkId;
320 this.pskType = that.pskType;
321 this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated.
322 this.mRssi = that.mRssi;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700323 this.mInfo = that.mInfo;
324 this.mNetworkInfo = that.mNetworkInfo;
325 this.mScanResultCache.clear();
326 this.mScanResultCache.putAll(that.mScanResultCache);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700327 this.mScoredNetworkCache.clear();
328 this.mScoredNetworkCache.putAll(that.mScoredNetworkCache);
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700329 this.mId = that.mId;
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700330 this.mSpeed = that.mSpeed;
Stephen Chen21f68682017-04-04 13:23:31 -0700331 this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered;
Peter Qiu280581b2017-07-24 14:18:56 -0700332 this.mIsCarrierAp = that.mIsCarrierAp;
333 this.mCarrierApEapType = that.mCarrierApEapType;
334 this.mCarrierName = that.mCarrierName;
Jason Monkd52356a2015-01-28 10:40:41 -0500335 }
336
Dave Schaefer98537432017-02-08 11:26:08 -0800337 /**
338 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
339 * equal to, or greater than the other AccessPoint.
340 *
341 * Sort order rules for AccessPoints:
342 * 1. Active before inactive
343 * 2. Reachable before unreachable
344 * 3. Saved before unsaved
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700345 * 4. Network speed value
Dave Schaefer98537432017-02-08 11:26:08 -0800346 * 5. Stronger signal before weaker signal
347 * 6. SSID alphabetically
348 *
349 * Note that AccessPoints with a signal are usually also Reachable,
350 * and will thus appear before unreachable saved AccessPoints.
351 */
Jason Monkd52356a2015-01-28 10:40:41 -0500352 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800353 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500354 // Active one goes first.
355 if (isActive() && !other.isActive()) return -1;
356 if (!isActive() && other.isActive()) return 1;
357
358 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800359 if (isReachable() && !other.isReachable()) return -1;
360 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500361
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800362 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800363 if (isSaved() && !other.isSaved()) return -1;
364 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500365
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700366 // Faster speeds go before slower speeds - but only if visible change in speed label
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700367 if (getSpeed() != other.getSpeed()) {
368 return other.getSpeed() - getSpeed();
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800369 }
370
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800371 // Sort by signal strength, bucketed by level
372 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
373 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500374 if (difference != 0) {
375 return difference;
376 }
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700377
Jason Monkd52356a2015-01-28 10:40:41 -0500378 // Sort by ssid.
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700379 difference = getSsidStr().compareToIgnoreCase(other.getSsidStr());
380 if (difference != 0) {
381 return difference;
382 }
383
384 // Do a case sensitive comparison to distinguish SSIDs that differ in case only
385 return getSsidStr().compareTo(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500386 }
387
388 @Override
389 public boolean equals(Object other) {
390 if (!(other instanceof AccessPoint)) return false;
391 return (this.compareTo((AccessPoint) other) == 0);
392 }
393
394 @Override
395 public int hashCode() {
396 int result = 0;
397 if (mInfo != null) result += 13 * mInfo.hashCode();
398 result += 19 * mRssi;
399 result += 23 * networkId;
400 result += 29 * ssid.hashCode();
401 return result;
402 }
403
404 @Override
405 public String toString() {
406 StringBuilder builder = new StringBuilder().append("AccessPoint(")
407 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800408 if (bssid != null) {
409 builder.append(":").append(bssid);
410 }
Jason Monkd52356a2015-01-28 10:40:41 -0500411 if (isSaved()) {
412 builder.append(',').append("saved");
413 }
414 if (isActive()) {
415 builder.append(',').append("active");
416 }
417 if (isEphemeral()) {
418 builder.append(',').append("ephemeral");
419 }
420 if (isConnectable()) {
421 builder.append(',').append("connectable");
422 }
423 if (security != SECURITY_NONE) {
424 builder.append(',').append(securityToString(security, pskType));
425 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800426 builder.append(",level=").append(getLevel());
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700427 if (mSpeed != Speed.NONE) {
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700428 builder.append(",speed=").append(mSpeed);
Sundeep Ghuman8920e9c2017-04-27 16:16:41 -0700429 }
Stephen Chen21f68682017-04-04 13:23:31 -0700430 builder.append(",metered=").append(isMetered());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800431
Jason Monkd52356a2015-01-28 10:40:41 -0500432 return builder.append(')').toString();
433 }
434
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800435 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700436 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
Stephen Chen21f68682017-04-04 13:23:31 -0700437 * changed.
438 *
439 * @param scoreCache The score cache to use to retrieve scores.
440 * @param scoringUiEnabled Whether to show scoring and badging UI.
441 */
442 boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) {
443 boolean scoreChanged = false;
444 if (scoringUiEnabled) {
445 scoreChanged = updateScores(scoreCache);
446 }
447 return updateMetered(scoreCache) || scoreChanged;
448 }
449
450 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700451 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800452 *
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700453 * <p>Any cached {@link TimestampedScoredNetwork} objects older than
454 * {@link #MAX_CACHED_SCORE_AGE_MILLIS} will be removed when this method is invoked.
455 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700456 * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
457 *
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800458 * @param scoreCache The score cache to use to retrieve scores.
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700459 * @return true if the set speed has changed
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800460 */
Stephen Chen21f68682017-04-04 13:23:31 -0700461 private boolean updateScores(WifiNetworkScoreCache scoreCache) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700462 long nowMillis = SystemClock.elapsedRealtime();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700463 for (ScanResult result : mScanResultCache.values()) {
464 ScoredNetwork score = scoreCache.getScoredNetwork(result);
465 if (score == null) {
466 continue;
467 }
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700468 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
469 if (timedScore == null) {
470 mScoredNetworkCache.put(
471 result.BSSID, new TimestampedScoredNetwork(score, nowMillis));
472 } else {
473 // Update data since the has been seen in the score cache
474 timedScore.update(score, nowMillis);
475 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700476 }
477
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700478 // Remove old cached networks
479 long evictionCutoff = nowMillis - MAX_CACHED_SCORE_AGE_MILLIS;
480 Iterator<TimestampedScoredNetwork> iterator = mScoredNetworkCache.values().iterator();
481 iterator.forEachRemaining(timestampedScoredNetwork -> {
482 if (timestampedScoredNetwork.getUpdatedTimestampMillis() < evictionCutoff) {
483 iterator.remove();
484 }
485 });
486
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700487 return updateSpeed();
488 }
489
490 /**
491 * Updates the internal speed, returning true if the update resulted in a speed label change.
492 */
493 private boolean updateSpeed() {
494 int oldSpeed = mSpeed;
495 mSpeed = generateAverageSpeedForSsid();
496
497 // set speed to the connected ScanResult if the AccessPoint is the active network
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700498 if (isActive() && mInfo != null) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700499 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(mInfo.getBSSID());
500 if (timedScore != null) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700501 if (Log.isLoggable(TAG, Log.DEBUG)) {
502 Log.d(TAG, "Set score using specific access point curve for connected AP: "
503 + getSsidStr());
504 }
505 // TODO(b/63073866): Map using getLevel rather than specific rssi value so score
506 // doesn't change without a visible wifi bar change.
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700507 int speed = timedScore.getScore().calculateBadge(mInfo.getRssi());
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700508 if (speed != Speed.NONE) {
509 mSpeed = speed;
510 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800511 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700512 }
513
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700514 boolean changed = oldSpeed != mSpeed;
515 if(WifiTracker.sVerboseLogging && changed) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700516 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800517 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700518 return changed;
519 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800520
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700521 /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
522 @Speed private int generateAverageSpeedForSsid() {
523 if (mScoredNetworkCache.isEmpty()) {
524 return Speed.NONE;
525 }
526
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700527 if (Log.isLoggable(TAG, Log.DEBUG)) {
528 Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
529 getSsidStr(), mScoredNetworkCache));
530 }
531
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700532 int count = 0;
533 int totalSpeed = 0;
534 for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
535 int speed = timedScore.getScore().calculateBadge(mRssi);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700536 if (speed != Speed.NONE) {
537 count++;
538 totalSpeed += speed;
539 }
540 }
541 int speed = count == 0 ? Speed.NONE : totalSpeed / count;
542 if (WifiTracker.sVerboseLogging) {
543 Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
544 }
545 return roundToClosestSpeedEnum(speed);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800546 }
547
Stephen Chen21f68682017-04-04 13:23:31 -0700548 /**
549 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
550 * true if the metering changed.
551 */
552 private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
553 boolean oldMetering = mIsScoredNetworkMetered;
554 mIsScoredNetworkMetered = false;
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700555
556 if (isActive() && mInfo != null) {
Eric Schwarzenbach733ea262017-08-08 10:28:21 -0700557 NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700558 ScoredNetwork score = scoreCache.getScoredNetwork(key);
559 if (score != null) {
560 mIsScoredNetworkMetered |= score.meteredHint;
Stephen Chen21f68682017-04-04 13:23:31 -0700561 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700562 } else {
563 for (ScanResult result : mScanResultCache.values()) {
564 ScoredNetwork score = scoreCache.getScoredNetwork(result);
565 if (score == null) {
566 continue;
567 }
568 mIsScoredNetworkMetered |= score.meteredHint;
569 }
Stephen Chen21f68682017-04-04 13:23:31 -0700570 }
571 return oldMetering == mIsScoredNetworkMetered;
572 }
573
Mitchell Wills18af4932016-08-10 13:49:21 -0700574 private void evictOldScanResults() {
575 long nowMs = SystemClock.elapsedRealtime();
576 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
577 ScanResult result = iter.next();
578 // result timestamp is in microseconds
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700579 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MILLIS) {
Mitchell Wills18af4932016-08-10 13:49:21 -0700580 iter.remove();
581 }
582 }
583 }
584
Jason Monkd52356a2015-01-28 10:40:41 -0500585 public boolean matches(ScanResult result) {
586 return ssid.equals(result.SSID) && security == getSecurity(result);
587 }
588
589 public boolean matches(WifiConfiguration config) {
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100590 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
Shinji Sogof29e1222015-12-09 17:21:38 +0900591 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100592 } else {
593 return ssid.equals(removeDoubleQuotes(config.SSID))
594 && security == getSecurity(config)
595 && (mConfig == null || mConfig.shared == config.shared);
596 }
Jason Monkd52356a2015-01-28 10:40:41 -0500597 }
598
599 public WifiConfiguration getConfig() {
600 return mConfig;
601 }
602
Peter Qiuced37db2017-03-14 15:51:22 -0700603 public String getPasspointFqdn() {
604 return mFqdn;
605 }
606
Jason Monkd52356a2015-01-28 10:40:41 -0500607 public void clearConfig() {
608 mConfig = null;
609 networkId = WifiConfiguration.INVALID_NETWORK_ID;
610 }
611
612 public WifiInfo getInfo() {
613 return mInfo;
614 }
615
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700616 /**
617 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
618 *
619 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
620 * always return at least 0.
621 */
Jason Monkd52356a2015-01-28 10:40:41 -0500622 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800623 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500624 }
625
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700626 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800627 return mRssi;
628 }
629
630 /**
631 * Updates {@link #mRssi}.
632 *
633 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
634 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700635 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
636 * value. If the access point is not connected and there are no scan results, the rssi will be
637 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800638 */
639 private void updateRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800640 if (this.isActive()) {
641 return;
642 }
643
644 int rssi = UNREACHABLE_RSSI;
Mitchell Wills18af4932016-08-10 13:49:21 -0700645 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700646 if (result.level > rssi) {
647 rssi = result.level;
648 }
649 }
650
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700651 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
652 mRssi = (mRssi + rssi) / 2; // half-life previous value
653 } else {
654 mRssi = rssi;
655 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700656 }
657
Stephen Chen21f68682017-04-04 13:23:31 -0700658 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600659 * Returns if the network should be considered metered.
Stephen Chen21f68682017-04-04 13:23:31 -0700660 */
661 public boolean isMetered() {
662 return mIsScoredNetworkMetered
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600663 || WifiConfiguration.isMetered(mConfig, mInfo);
Stephen Chen21f68682017-04-04 13:23:31 -0700664 }
665
Jason Monkd52356a2015-01-28 10:40:41 -0500666 public NetworkInfo getNetworkInfo() {
667 return mNetworkInfo;
668 }
669
670 public int getSecurity() {
671 return security;
672 }
673
674 public String getSecurityString(boolean concise) {
675 Context context = mContext;
Tomoharu Hatano2bde6e72017-05-30 18:38:56 +0900676 if (isPasspoint() || isPasspointConfig()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700677 return concise ? context.getString(R.string.wifi_security_short_eap) :
678 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700679 }
Jason Monkd52356a2015-01-28 10:40:41 -0500680 switch(security) {
681 case SECURITY_EAP:
682 return concise ? context.getString(R.string.wifi_security_short_eap) :
683 context.getString(R.string.wifi_security_eap);
684 case SECURITY_PSK:
685 switch (pskType) {
686 case PSK_WPA:
687 return concise ? context.getString(R.string.wifi_security_short_wpa) :
688 context.getString(R.string.wifi_security_wpa);
689 case PSK_WPA2:
690 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
691 context.getString(R.string.wifi_security_wpa2);
692 case PSK_WPA_WPA2:
693 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
694 context.getString(R.string.wifi_security_wpa_wpa2);
695 case PSK_UNKNOWN:
696 default:
697 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
698 : context.getString(R.string.wifi_security_psk_generic);
699 }
700 case SECURITY_WEP:
701 return concise ? context.getString(R.string.wifi_security_short_wep) :
702 context.getString(R.string.wifi_security_wep);
703 case SECURITY_NONE:
704 default:
705 return concise ? "" : context.getString(R.string.wifi_security_none);
706 }
707 }
708
Jason Monk6980d122015-06-15 10:07:55 -0400709 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500710 return ssid;
711 }
712
Jason Monk60a82ff2016-02-25 13:55:03 -0500713 public String getBssid() {
714 return bssid;
715 }
716
Jason Monk6980d122015-06-15 10:07:55 -0400717 public CharSequence getSsid() {
Fan Zhangeb83a0d2016-09-21 11:34:08 -0700718 final SpannableString str = new SpannableString(ssid);
719 str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
Jason Monk6980d122015-06-15 10:07:55 -0400720 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
721 return str;
722 }
723
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700724 public String getConfigName() {
725 if (mConfig != null && mConfig.isPasspoint()) {
726 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700727 } else if (mFqdn != null) {
728 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700729 } else {
730 return ssid;
731 }
732 }
733
Jason Monkd52356a2015-01-28 10:40:41 -0500734 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700735 if (mNetworkInfo != null) {
736 return mNetworkInfo.getDetailedState();
737 }
738 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
739 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500740 }
741
Peter Qiu280581b2017-07-24 14:18:56 -0700742 public boolean isCarrierAp() {
743 return mIsCarrierAp;
744 }
745
746 public int getCarrierApEapType() {
747 return mCarrierApEapType;
748 }
749
750 public String getCarrierName() {
751 return mCarrierName;
752 }
753
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700754 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700755 WifiConfiguration config = mConfig;
756 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700757 PackageManager pm = mContext.getPackageManager();
758 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700759 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700760 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700761 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700762 appInfo = mContext.getApplicationInfo();
763 } else {
764 try {
765 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700766 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700767 } catch (RemoteException rex) {
768 }
769 }
770 if (appInfo != null &&
771 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
772 !appInfo.packageName.equals(
773 mContext.getString(R.string.certinstaller_package))) {
774 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
775 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700776 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700777 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700778 }
779
Jason Monkd52356a2015-01-28 10:40:41 -0500780 public String getSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700781 return getSettingsSummary(mConfig);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700782 }
783
784 public String getSettingsSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700785 return getSettingsSummary(mConfig);
786 }
787
788 private String getSettingsSummary(WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500789 // Update to new summary
790 StringBuilder summary = new StringBuilder();
791
Fan Zhang51365c32016-09-20 12:22:18 -0700792 if (isActive() && config != null && config.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700793 // This is the active connection on passpoint
Jason Monkd52356a2015-01-28 10:40:41 -0500794 summary.append(getSummary(mContext, getDetailedState(),
Fan Zhang51365c32016-09-20 12:22:18 -0700795 false, config.providerFriendlyName));
Peter Qiu280581b2017-07-24 14:18:56 -0700796 } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
797 && mIsCarrierAp) {
798 summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700799 } else if (isActive()) {
800 // This is the active connection on non-passpoint network
801 summary.append(getSummary(mContext, getDetailedState(),
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700802 mInfo != null && mInfo.isEphemeral()));
Yuxin Chang6b750862017-01-11 14:59:17 +0900803 } else if (config != null && config.isPasspoint()
804 && config.getNetworkSelectionStatus().isNetworkEnabled()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700805 String format = mContext.getString(R.string.available_via_passpoint);
Fan Zhang51365c32016-09-20 12:22:18 -0700806 summary.append(String.format(format, config.providerFriendlyName));
807 } else if (config != null && config.hasNoInternetAccess()) {
Salvador Martinez5d937fc2016-09-23 08:54:20 -0700808 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
809 ? R.string.wifi_no_internet_no_reconnect
810 : R.string.wifi_no_internet;
811 summary.append(mContext.getString(messageID));
Fan Zhang51365c32016-09-20 12:22:18 -0700812 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
xinhef7705c32015-12-01 14:44:37 -0800813 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700814 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800815 switch (networkStatus.getNetworkSelectionDisableReason()) {
816 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
Jason Monkd52356a2015-01-28 10:40:41 -0500817 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
xinhef7705c32015-12-01 14:44:37 -0800818 break;
Peter Qiu9c4c6ad2017-06-20 13:17:36 -0700819 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
820 summary.append(mContext.getString(R.string.wifi_check_password_try_again));
821 break;
xinhef7705c32015-12-01 14:44:37 -0800822 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
823 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
824 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
825 break;
826 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
827 summary.append(mContext.getString(R.string.wifi_disabled_generic));
828 break;
Jason Monkd52356a2015-01-28 10:40:41 -0500829 }
Amin Shaikh98773d42017-02-02 17:50:12 -0800830 } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
831 summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
Peter Qiu280581b2017-07-24 14:18:56 -0700832 } else if (mIsCarrierAp) {
833 summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
Dave Schaefer98537432017-02-08 11:26:08 -0800834 } else if (!isReachable()) { // Wifi out of range
Jason Monkd52356a2015-01-28 10:40:41 -0500835 summary.append(mContext.getString(R.string.wifi_not_in_range));
836 } else { // In range, not disabled.
Fan Zhang51365c32016-09-20 12:22:18 -0700837 if (config != null) { // Is saved network
Glen Kuhne446afac2017-06-22 16:02:33 -0700838 // Last attempt to connect to this failed. Show reason why
839 switch (config.recentFailure.getAssociationStatus()) {
840 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
841 summary.append(mContext.getString(
842 R.string.wifi_ap_unable_to_handle_new_sta));
843 break;
844 default:
845 // "Saved"
846 summary.append(mContext.getString(R.string.wifi_remembered));
847 break;
848 }
Jason Monkd52356a2015-01-28 10:40:41 -0500849 }
850 }
851
Sundeep Ghuman39ad5d82017-07-11 19:03:51 -0700852 if (WifiTracker.sVerboseLogging) {
Jason Monkd52356a2015-01-28 10:40:41 -0500853 // Add RSSI/band information for this config, what was seen up to 6 seconds ago
854 // verbose WiFi Logging is only turned on thru developers settings
Eric Schwarzenbachb77d3d72017-07-18 15:05:44 -0700855 if (isActive() && mInfo != null) {
Jason Monkd52356a2015-01-28 10:40:41 -0500856 summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
857 }
858 summary.append(" " + getVisibilityStatus());
Fan Zhang51365c32016-09-20 12:22:18 -0700859 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
860 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
861 if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
Jason Monkd52356a2015-01-28 10:40:41 -0500862 long now = System.currentTimeMillis();
Fan Zhang51365c32016-09-20 12:22:18 -0700863 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
Jason Monkd52356a2015-01-28 10:40:41 -0500864 long sec = diff%60; //seconds
865 long min = (diff/60)%60; //minutes
866 long hour = (min/60)%60; //hours
867 summary.append(", ");
868 if (hour > 0) summary.append(Long.toString(hour) + "h ");
869 summary.append( Long.toString(min) + "m ");
870 summary.append( Long.toString(sec) + "s ");
871 }
872 summary.append(")");
873 }
xinhef7705c32015-12-01 14:44:37 -0800874
Fan Zhang51365c32016-09-20 12:22:18 -0700875 if (config != null) {
xinhef7705c32015-12-01 14:44:37 -0800876 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700877 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800878 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
879 index < WifiConfiguration.NetworkSelectionStatus
880 .NETWORK_SELECTION_DISABLED_MAX; index++) {
881 if (networkStatus.getDisableReasonCounter(index) != 0) {
882 summary.append(" " + WifiConfiguration.NetworkSelectionStatus
883 .getNetworkDisableReasonString(index) + "="
884 + networkStatus.getDisableReasonCounter(index));
885 }
886 }
Jason Monkd52356a2015-01-28 10:40:41 -0500887 }
888 }
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700889
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700890 // If Speed label and summary are both present, use the preference combination to combine
891 // the two, else return the non-null one.
892 if (getSpeedLabel() != null && summary.length() != 0) {
Sundeep Ghumand3171ca2017-07-12 23:02:24 -0700893 return mContext.getResources().getString(
894 R.string.preference_summary_default_combination,
895 getSpeedLabel(),
896 summary.toString());
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700897 } else if (getSpeedLabel() != null) {
898 return getSpeedLabel();
Sundeep Ghumand3171ca2017-07-12 23:02:24 -0700899 } else {
900 return summary.toString();
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700901 }
Jason Monkd52356a2015-01-28 10:40:41 -0500902 }
903
904 /**
905 * Returns the visibility status of the WifiConfiguration.
906 *
907 * @return autojoin debugging information
908 * TODO: use a string formatter
909 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
910 * For instance [-40,5/-30,2]
911 */
912 private String getVisibilityStatus() {
913 StringBuilder visibility = new StringBuilder();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700914 StringBuilder scans24GHz = new StringBuilder();
915 StringBuilder scans5GHz = new StringBuilder();
Jason Monkd52356a2015-01-28 10:40:41 -0500916 String bssid = null;
917
918 long now = System.currentTimeMillis();
919
Eric Schwarzenbachb77d3d72017-07-18 15:05:44 -0700920 if (isActive() && mInfo != null) {
Jason Monkd52356a2015-01-28 10:40:41 -0500921 bssid = mInfo.getBSSID();
922 if (bssid != null) {
923 visibility.append(" ").append(bssid);
924 }
925 visibility.append(" rssi=").append(mInfo.getRssi());
926 visibility.append(" ");
927 visibility.append(" score=").append(mInfo.score);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700928 if (mSpeed != Speed.NONE) {
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700929 visibility.append(" speed=").append(getSpeedLabel());
930 }
Jason Monkd52356a2015-01-28 10:40:41 -0500931 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
932 visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
933 visibility.append(String.format("%.1f ", mInfo.txBadRate));
934 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
935 }
936
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700937 int maxRssi5 = WifiConfiguration.INVALID_RSSI;
938 int maxRssi24 = WifiConfiguration.INVALID_RSSI;
939 final int maxDisplayedScans = 4;
940 int num5 = 0; // number of scanned BSSID on 5GHz band
941 int num24 = 0; // number of scanned BSSID on 2.4Ghz band
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700942 int numBlackListed = 0;
Mitchell Wills18af4932016-08-10 13:49:21 -0700943 evictOldScanResults();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700944
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700945 // TODO: sort list by RSSI or age
Mitchell Wills18af4932016-08-10 13:49:21 -0700946 for (ScanResult result : mScanResultCache.values()) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700947 if (result.frequency >= LOWER_FREQ_5GHZ
948 && result.frequency <= HIGHER_FREQ_5GHZ) {
949 // Strictly speaking: [4915, 5825]
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700950 num5++;
951
952 if (result.level > maxRssi5) {
953 maxRssi5 = result.level;
954 }
955 if (num5 <= maxDisplayedScans) {
956 scans5GHz.append(verboseScanResultSummary(result, bssid));
957 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700958 } else if (result.frequency >= LOWER_FREQ_24GHZ
959 && result.frequency <= HIGHER_FREQ_24GHZ) {
960 // Strictly speaking: [2412, 2482]
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700961 num24++;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700962
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700963 if (result.level > maxRssi24) {
964 maxRssi24 = result.level;
Jason Monkd52356a2015-01-28 10:40:41 -0500965 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700966 if (num24 <= maxDisplayedScans) {
967 scans24GHz.append(verboseScanResultSummary(result, bssid));
Jason Monkd52356a2015-01-28 10:40:41 -0500968 }
969 }
970 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700971 visibility.append(" [");
972 if (num24 > 0) {
973 visibility.append("(").append(num24).append(")");
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700974 if (num24 > maxDisplayedScans) {
975 visibility.append("max=").append(maxRssi24).append(",");
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700976 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700977 visibility.append(scans24GHz.toString());
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700978 }
979 visibility.append(";");
980 if (num5 > 0) {
981 visibility.append("(").append(num5).append(")");
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700982 if (num5 > maxDisplayedScans) {
983 visibility.append("max=").append(maxRssi5).append(",");
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700984 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700985 visibility.append(scans5GHz.toString());
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700986 }
987 if (numBlackListed > 0)
988 visibility.append("!").append(numBlackListed);
989 visibility.append("]");
Jason Monkd52356a2015-01-28 10:40:41 -0500990
991 return visibility.toString();
992 }
993
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700994 @VisibleForTesting
995 /* package */ String verboseScanResultSummary(ScanResult result, String bssid) {
996 StringBuilder stringBuilder = new StringBuilder();
997 stringBuilder.append(" \n{").append(result.BSSID);
998 if (result.BSSID.equals(bssid)) {
999 stringBuilder.append("*");
1000 }
1001 stringBuilder.append("=").append(result.frequency);
1002 stringBuilder.append(",").append(result.level);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001003 int speed = getSpecificApSpeed(result);
1004 if (speed != Speed.NONE) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001005 stringBuilder.append(",")
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001006 .append(getSpeedLabel(speed));
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001007 }
1008 stringBuilder.append("}");
1009 return stringBuilder.toString();
1010 }
1011
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001012 @Speed private int getSpecificApSpeed(ScanResult result) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -07001013 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
1014 if (timedScore == null) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001015 return Speed.NONE;
1016 }
1017 // For debugging purposes we may want to use mRssi rather than result.level as the average
1018 // speed wil be determined by mRssi
Sundeep Ghumanfedf4612017-08-15 15:47:18 -07001019 return timedScore.getScore().calculateBadge(result.level);
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001020 }
1021
Jason Monkd52356a2015-01-28 10:40:41 -05001022 /**
1023 * Return whether this is the active connection.
1024 * For ephemeral connections (networkId is invalid), this returns false if the network is
1025 * disconnected.
1026 */
1027 public boolean isActive() {
1028 return mNetworkInfo != null &&
1029 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1030 mNetworkInfo.getState() != State.DISCONNECTED);
1031 }
1032
1033 public boolean isConnectable() {
1034 return getLevel() != -1 && getDetailedState() == null;
1035 }
1036
1037 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001038 return mInfo != null && mInfo.isEphemeral() &&
1039 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -05001040 }
1041
Peter Qiuced37db2017-03-14 15:51:22 -07001042 /**
1043 * Return true if this AccessPoint represents a Passpoint AP.
1044 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001045 public boolean isPasspoint() {
1046 return mConfig != null && mConfig.isPasspoint();
1047 }
1048
Mitchell Wills5a42db22015-08-03 09:46:08 -07001049 /**
Peter Qiuced37db2017-03-14 15:51:22 -07001050 * Return true if this AccessPoint represents a Passpoint provider configuration.
1051 */
1052 public boolean isPasspointConfig() {
1053 return mFqdn != null;
1054 }
1055
1056 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -07001057 * Return whether the given {@link WifiInfo} is for this access point.
1058 * If the current AP does not have a network Id then the config is used to
1059 * match based on SSID and security.
1060 */
1061 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001062 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -05001063 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001064 } else if (config != null) {
1065 return matches(config);
1066 }
1067 else {
Jason Monkd52356a2015-01-28 10:40:41 -05001068 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1069 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1070 // TODO: Handle hex string SSIDs.
1071 return ssid.equals(removeDoubleQuotes(info.getSSID()));
1072 }
1073 }
1074
1075 public boolean isSaved() {
1076 return networkId != WifiConfiguration.INVALID_NETWORK_ID;
1077 }
1078
1079 public Object getTag() {
1080 return mTag;
1081 }
1082
1083 public void setTag(Object tag) {
1084 mTag = tag;
1085 }
1086
1087 /**
1088 * Generate and save a default wifiConfiguration with common values.
1089 * Can only be called for unsecured networks.
1090 */
1091 public void generateOpenNetworkConfig() {
1092 if (security != SECURITY_NONE)
1093 throw new IllegalStateException();
1094 if (mConfig != null)
1095 return;
1096 mConfig = new WifiConfiguration();
1097 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
1098 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1099 }
1100
1101 void loadConfig(WifiConfiguration config) {
Peter Qiu2c3b5ee22017-02-01 11:49:15 -08001102 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
Jason Monk60a82ff2016-02-25 13:55:03 -05001103 bssid = config.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -05001104 security = getSecurity(config);
1105 networkId = config.networkId;
1106 mConfig = config;
1107 }
1108
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001109 private void initWithScanResult(ScanResult result) {
Jason Monkd52356a2015-01-28 10:40:41 -05001110 ssid = result.SSID;
Jason Monk60a82ff2016-02-25 13:55:03 -05001111 bssid = result.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -05001112 security = getSecurity(result);
1113 if (security == SECURITY_PSK)
1114 pskType = getPskType(result);
Sundeep Ghuman24128172017-06-15 17:55:21 -07001115
1116 mScanResultCache.put(result.BSSID, result);
1117 updateRssi();
Peter Qiu280581b2017-07-24 14:18:56 -07001118 mIsCarrierAp = result.isCarrierAp;
1119 mCarrierApEapType = result.carrierApEapType;
1120 mCarrierName = result.carrierName;
Jason Monkd52356a2015-01-28 10:40:41 -05001121 }
1122
1123 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001124 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1125 savedState.putInt(KEY_SECURITY, security);
Sundeep Ghumana28050a2017-07-12 22:09:25 -07001126 savedState.putInt(KEY_SPEED, mSpeed);
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001127 savedState.putInt(KEY_PSKTYPE, pskType);
1128 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -05001129 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Mitchell Wills18af4932016-08-10 13:49:21 -07001130 evictOldScanResults();
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001131 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
Mitchell Wills18af4932016-08-10 13:49:21 -07001132 new ArrayList<ScanResult>(mScanResultCache.values()));
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001133 savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1134 new ArrayList<>(mScoredNetworkCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -05001135 if (mNetworkInfo != null) {
1136 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1137 }
Peter Qiuced37db2017-03-14 15:51:22 -07001138 if (mFqdn != null) {
1139 savedState.putString(KEY_FQDN, mFqdn);
1140 }
1141 if (mProviderFriendlyName != null) {
1142 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1143 }
Peter Qiu280581b2017-07-24 14:18:56 -07001144 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1145 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1146 savedState.putString(KEY_CARRIER_NAME, mCarrierName);
Jason Monkd52356a2015-01-28 10:40:41 -05001147 }
1148
1149 public void setListener(AccessPointListener listener) {
1150 mAccessPointListener = listener;
1151 }
1152
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001153 /**
1154 * Update the AP with the given scan result.
1155 *
1156 * @param result the ScanResult to add to the AccessPoint scan cache
1157 * @param evictOldScanResults whether stale scan results should be removed
1158 * from the cache during this update process
1159 * @return true if the scan result update caused a change in state which would impact ranking
1160 * or AccessPoint rendering (e.g. wifi level, security)
1161 */
1162 boolean update(ScanResult result, boolean evictOldScanResults) {
Mitchell Wills5a42db22015-08-03 09:46:08 -07001163 if (matches(result)) {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001164 int oldLevel = getLevel();
1165
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001166 /* Add or update the scan result for the BSSID */
1167 mScanResultCache.put(result.BSSID, result);
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001168 if (evictOldScanResults) evictOldScanResults();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001169 updateRssi();
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001170 int newLevel = getLevel();
1171
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001172 if (newLevel > 0 && newLevel != oldLevel) {
1173 // Only update labels on visible rssi changes
1174 updateSpeed();
1175 if (mAccessPointListener != null) {
1176 mAccessPointListener.onLevelChanged(this);
1177 }
Jason Monkd52356a2015-01-28 10:40:41 -05001178 }
1179 // This flag only comes from scans, is not easily saved in config
1180 if (security == SECURITY_PSK) {
1181 pskType = getPskType(result);
1182 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001183
Jason Monkd52356a2015-01-28 10:40:41 -05001184 if (mAccessPointListener != null) {
1185 mAccessPointListener.onAccessPointChanged(this);
1186 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001187
Peter Qiu280581b2017-07-24 14:18:56 -07001188 // The carrier info in the ScanResult is set by the platform based on the SSID and will
1189 // always be the same for all matching scan results.
1190 mIsCarrierAp = result.isCarrierAp;
1191 mCarrierApEapType = result.carrierApEapType;
1192 mCarrierName = result.carrierName;
1193
Jason Monkd52356a2015-01-28 10:40:41 -05001194 return true;
1195 }
1196 return false;
1197 }
1198
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001199 /** Attempt to update the AccessPoint and return true if an update occurred. */
Sundeep Ghumand911da32017-07-05 20:06:05 -07001200 public boolean update(
1201 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001202 boolean updated = false;
1203 final int oldLevel = getLevel();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001204 if (info != null && isInfoForThisAccessPoint(config, info)) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001205 updated = (mInfo == null);
Sundeep Ghumanf4d33022017-06-05 19:47:36 -07001206 if (mConfig != config) {
1207 // We do not set updated = true as we do not want to increase the amount of sorting
1208 // and copying performed in WifiTracker at this time. If issues involving refresh
1209 // are still seen, we will investigate further.
1210 update(config); // Notifies the AccessPointListener of the change
1211 }
Glen Kuhned38708c2017-07-19 14:53:34 -07001212 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001213 mRssi = info.getRssi();
1214 updated = true;
Sundeep Ghuman5c5cd7a2017-05-03 12:45:44 -07001215 } else if (mNetworkInfo != null && networkInfo != null
1216 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
Sundeep Ghuman96a53572017-04-20 21:25:41 -07001217 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001218 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001219 mInfo = info;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001220 mNetworkInfo = networkInfo;
Jason Monkd52356a2015-01-28 10:40:41 -05001221 } else if (mInfo != null) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001222 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001223 mInfo = null;
1224 mNetworkInfo = null;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001225 }
1226 if (updated && mAccessPointListener != null) {
1227 mAccessPointListener.onAccessPointChanged(this);
1228
1229 if (oldLevel != getLevel() /* current level */) {
1230 mAccessPointListener.onLevelChanged(this);
Jason Monkd52356a2015-01-28 10:40:41 -05001231 }
1232 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001233 return updated;
Jason Monkd52356a2015-01-28 10:40:41 -05001234 }
1235
Sundeep Ghumand911da32017-07-05 20:06:05 -07001236 void update(@Nullable WifiConfiguration config) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001237 mConfig = config;
Sundeep Ghumand911da32017-07-05 20:06:05 -07001238 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001239 if (mAccessPointListener != null) {
1240 mAccessPointListener.onAccessPointChanged(this);
1241 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001242 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001243
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001244 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -07001245 void setRssi(int rssi) {
1246 mRssi = rssi;
1247 }
1248
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001249 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1250 void setUnreachable() {
1251 setRssi(AccessPoint.UNREACHABLE_RSSI);
1252 }
1253
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001254 int getSpeed() { return mSpeed;}
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001255
1256 @Nullable
1257 String getSpeedLabel() {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001258 return getSpeedLabel(mSpeed);
1259 }
1260
1261 @Nullable
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001262 @Speed
1263 private int roundToClosestSpeedEnum(int speed) {
1264 if (speed < Speed.SLOW) {
1265 return Speed.NONE;
1266 } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1267 return Speed.SLOW;
1268 } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1269 return Speed.MODERATE;
1270 } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1271 return Speed.FAST;
1272 } else {
1273 return Speed.VERY_FAST;
1274 }
1275 }
1276
1277 @Nullable
1278 private String getSpeedLabel(@Speed int speed) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001279 switch (speed) {
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001280 case Speed.VERY_FAST:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001281 return mContext.getString(R.string.speed_label_very_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001282 case Speed.FAST:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001283 return mContext.getString(R.string.speed_label_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001284 case Speed.MODERATE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001285 return mContext.getString(R.string.speed_label_okay);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001286 case Speed.SLOW:
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001287 return mContext.getString(R.string.speed_label_slow);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001288 case Speed.NONE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001289 default:
1290 return null;
1291 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -08001292 }
1293
Dave Schaefer98537432017-02-08 11:26:08 -08001294 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -07001295 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -08001296 return mRssi != UNREACHABLE_RSSI;
1297 }
1298
Jason Monkd52356a2015-01-28 10:40:41 -05001299 public static String getSummary(Context context, String ssid, DetailedState state,
Vinit Deshpandefc406002015-04-15 18:10:55 -07001300 boolean isEphemeral, String passpointProvider) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001301 if (state == DetailedState.CONNECTED && ssid == null) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001302 if (TextUtils.isEmpty(passpointProvider) == false) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001303 // Special case for connected + passpoint networks.
Vinit Deshpandefc406002015-04-15 18:10:55 -07001304 String format = context.getString(R.string.connected_via_passpoint);
1305 return String.format(format, passpointProvider);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001306 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001307 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001308 final NetworkScoreManager networkScoreManager = context.getSystemService(
1309 NetworkScoreManager.class);
1310 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1311 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1312 String format = context.getString(R.string.connected_via_network_scorer);
1313 return String.format(format, scorer.getRecommendationServiceLabel());
1314 } else {
1315 return context.getString(R.string.connected_via_network_scorer_default);
1316 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001317 }
Jason Monkd52356a2015-01-28 10:40:41 -05001318 }
1319
Sanket Padawe7094d222015-05-01 16:55:00 -07001320 // Case when there is wifi connected without internet connectivity.
1321 final ConnectivityManager cm = (ConnectivityManager)
1322 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1323 if (state == DetailedState.CONNECTED) {
1324 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1325 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001326 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001327
1328 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001329 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1330 } catch (RemoteException e) {}
1331
1332 if (nc != null) {
1333 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
Maurice Lam7f6fc862017-07-12 16:43:49 -07001334 int id = context.getResources()
1335 .getIdentifier("network_available_sign_in", "string", "android");
1336 return context.getString(id);
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001337 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1338 return context.getString(R.string.wifi_connected_no_internet);
1339 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001340 }
1341 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001342 if (state == null) {
1343 Log.w(TAG, "state is null, returning empty summary");
1344 return "";
1345 }
Jason Monkd52356a2015-01-28 10:40:41 -05001346 String[] formats = context.getResources().getStringArray((ssid == null)
1347 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1348 int index = state.ordinal();
1349
1350 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001351 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001352 }
1353 return String.format(formats[index], ssid);
1354 }
1355
1356 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001357 return getSummary(context, null, state, isEphemeral, null);
1358 }
1359
1360 public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1361 String passpointProvider) {
1362 return getSummary(context, null, state, isEphemeral, passpointProvider);
Jason Monkd52356a2015-01-28 10:40:41 -05001363 }
1364
1365 public static String convertToQuotedString(String string) {
1366 return "\"" + string + "\"";
1367 }
1368
1369 private static int getPskType(ScanResult result) {
1370 boolean wpa = result.capabilities.contains("WPA-PSK");
1371 boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1372 if (wpa2 && wpa) {
1373 return PSK_WPA_WPA2;
1374 } else if (wpa2) {
1375 return PSK_WPA2;
1376 } else if (wpa) {
1377 return PSK_WPA;
1378 } else {
1379 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1380 return PSK_UNKNOWN;
1381 }
1382 }
1383
1384 private static int getSecurity(ScanResult result) {
1385 if (result.capabilities.contains("WEP")) {
1386 return SECURITY_WEP;
1387 } else if (result.capabilities.contains("PSK")) {
1388 return SECURITY_PSK;
1389 } else if (result.capabilities.contains("EAP")) {
1390 return SECURITY_EAP;
1391 }
1392 return SECURITY_NONE;
1393 }
1394
1395 static int getSecurity(WifiConfiguration config) {
1396 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1397 return SECURITY_PSK;
1398 }
1399 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1400 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1401 return SECURITY_EAP;
1402 }
1403 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1404 }
1405
1406 public static String securityToString(int security, int pskType) {
1407 if (security == SECURITY_WEP) {
1408 return "WEP";
1409 } else if (security == SECURITY_PSK) {
1410 if (pskType == PSK_WPA) {
1411 return "WPA";
1412 } else if (pskType == PSK_WPA2) {
1413 return "WPA2";
1414 } else if (pskType == PSK_WPA_WPA2) {
1415 return "WPA_WPA2";
1416 }
1417 return "PSK";
1418 } else if (security == SECURITY_EAP) {
1419 return "EAP";
1420 }
1421 return "NONE";
1422 }
1423
1424 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001425 if (TextUtils.isEmpty(string)) {
1426 return "";
1427 }
Jason Monkd52356a2015-01-28 10:40:41 -05001428 int length = string.length();
1429 if ((length > 1) && (string.charAt(0) == '"')
1430 && (string.charAt(length - 1) == '"')) {
1431 return string.substring(1, length - 1);
1432 }
1433 return string;
1434 }
1435
1436 public interface AccessPointListener {
1437 void onAccessPointChanged(AccessPoint accessPoint);
1438 void onLevelChanged(AccessPoint accessPoint);
1439 }
1440}