AccessPoint.java revision a419b9b4db99c5ca6df759ba7ffebe0855fc0891
1/*
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
19import android.annotation.IntDef;
20import android.annotation.Nullable;
21import android.app.AppGlobals;
22import android.content.Context;
23import android.content.pm.ApplicationInfo;
24import android.content.pm.IPackageManager;
25import android.content.pm.PackageManager;
26import android.net.ConnectivityManager;
27import android.net.NetworkCapabilities;
28import android.net.NetworkInfo;
29import android.net.NetworkInfo.DetailedState;
30import android.net.NetworkInfo.State;
31import android.net.NetworkKey;
32import android.net.NetworkScoreManager;
33import android.net.NetworkScorerAppData;
34import android.net.ScoredNetwork;
35import android.net.WifiKey;
36import android.net.wifi.IWifiManager;
37import android.net.wifi.ScanResult;
38import android.net.wifi.WifiConfiguration;
39import android.net.wifi.WifiConfiguration.KeyMgmt;
40import android.net.wifi.WifiEnterpriseConfig;
41import android.net.wifi.WifiInfo;
42import android.net.wifi.WifiManager;
43import android.net.wifi.WifiNetworkScoreCache;
44import android.net.wifi.hotspot2.PasspointConfiguration;
45import android.os.Bundle;
46import android.os.RemoteException;
47import android.os.ServiceManager;
48import android.os.SystemClock;
49import android.os.UserHandle;
50import android.support.annotation.NonNull;
51import android.text.Spannable;
52import android.text.SpannableString;
53import android.text.TextUtils;
54import android.text.format.DateUtils;
55import android.text.style.TtsSpan;
56import android.util.Log;
57
58import com.android.internal.annotations.VisibleForTesting;
59import com.android.settingslib.R;
60
61import java.lang.annotation.Retention;
62import java.lang.annotation.RetentionPolicy;
63import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.Iterator;
66import java.util.Map;
67import java.util.concurrent.ConcurrentHashMap;
68import java.util.concurrent.atomic.AtomicInteger;
69
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
94    @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    }
118
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     */
125    private final ConcurrentHashMap<String, ScanResult> mScanResultCache =
126            new ConcurrentHashMap<String, ScanResult>(32);
127
128    /**
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     */
134    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;
139
140    /** Maximum age of scan results to hold onto while actively scanning. **/
141    private static final long MAX_SCAN_RESULT_AGE_MILLIS = 15000;
142
143    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";
148    static final String KEY_SPEED = "key_speed";
149    static final String KEY_PSKTYPE = "key_psktype";
150    static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
151    static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
152    static final String KEY_CONFIG = "key_config";
153    static final String KEY_FQDN = "key_fqdn";
154    static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
155    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";
158    static final AtomicInteger sLastId = new AtomicInteger(0);
159
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
173    /**
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;
179
180    public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
181
182    private final Context mContext;
183
184    private String ssid;
185    private String bssid;
186    private int security;
187    private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
188
189    private int pskType = PSK_UNKNOWN;
190
191    private WifiConfiguration mConfig;
192
193    private int mRssi = UNREACHABLE_RSSI;
194    private long mSeen = 0;
195
196    private WifiInfo mInfo;
197    private NetworkInfo mNetworkInfo;
198    AccessPointListener mAccessPointListener;
199
200    private Object mTag;
201
202    @Speed private int mSpeed = Speed.NONE;
203    private boolean mIsScoredNetworkMetered = false;
204
205    // used to co-relate internal vs returned accesspoint.
206    int mId;
207
208    /**
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
215    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
222    public AccessPoint(Context context, Bundle savedState) {
223        mContext = context;
224        mConfig = savedState.getParcelable(KEY_CONFIG);
225        if (mConfig != null) {
226            loadConfig(mConfig);
227        }
228        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        }
234        if (savedState.containsKey(KEY_SPEED)) {
235            mSpeed = savedState.getInt(KEY_SPEED);
236        }
237        if (savedState.containsKey(KEY_PSKTYPE)) {
238            pskType = savedState.getInt(KEY_PSKTYPE);
239        }
240        mInfo = savedState.getParcelable(KEY_WIFIINFO);
241        if (savedState.containsKey(KEY_NETWORKINFO)) {
242            mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
243        }
244        if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
245            ArrayList<ScanResult> scanResultArrayList =
246                    savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
247            mScanResultCache.clear();
248            for (ScanResult result : scanResultArrayList) {
249                mScanResultCache.put(result.BSSID, result);
250            }
251        }
252        if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
253            ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
254                    savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
255            for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
256                mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
257            }
258        }
259        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        }
265        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        }
274        update(mConfig, mInfo, mNetworkInfo);
275
276        // Do not evict old scan results on initial creation
277        updateRssi();
278        updateSeen();
279        mId = sLastId.incrementAndGet();
280    }
281
282    public AccessPoint(Context context, WifiConfiguration config) {
283        mContext = context;
284        loadConfig(config);
285        mId = sLastId.incrementAndGet();
286    }
287
288    /**
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) {
293        mContext = context;
294        mFqdn = config.getHomeSp().getFqdn();
295        mProviderFriendlyName = config.getHomeSp().getFriendlyName();
296        mId = sLastId.incrementAndGet();
297    }
298
299    AccessPoint(Context context, AccessPoint other) {
300        mContext = context;
301        copyFrom(other);
302    }
303
304    AccessPoint(Context context, ScanResult result) {
305        mContext = context;
306        initWithScanResult(result);
307        mId = sLastId.incrementAndGet();
308    }
309
310    /**
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);
329        this.mScoredNetworkCache.clear();
330        this.mScoredNetworkCache.putAll(that.mScoredNetworkCache);
331        this.mId = that.mId;
332        this.mSpeed = that.mSpeed;
333        this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered;
334        this.mIsCarrierAp = that.mIsCarrierAp;
335        this.mCarrierApEapType = that.mCarrierApEapType;
336        this.mCarrierName = that.mCarrierName;
337    }
338
339    /**
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
347    *   4. Network speed value
348    *   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    */
354    @Override
355    public int compareTo(@NonNull AccessPoint other) {
356        // 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.
361        if (isReachable() && !other.isReachable()) return -1;
362        if (!isReachable() && other.isReachable()) return 1;
363
364        // Configured (saved) one goes before unconfigured one.
365        if (isSaved() && !other.isSaved()) return -1;
366        if (!isSaved() && other.isSaved()) return 1;
367
368        // Faster speeds go before slower speeds - but only if visible change in speed label
369        if (getSpeed() != other.getSpeed()) {
370            return other.getSpeed() - getSpeed();
371        }
372
373        // Sort by signal strength, bucketed by level
374        int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
375                - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
376        if (difference != 0) {
377            return difference;
378        }
379
380        // Sort by ssid.
381        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());
388    }
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);
410        if (bssid != null) {
411            builder.append(":").append(bssid);
412        }
413        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        }
428        builder.append(",level=").append(getLevel());
429        if (mSpeed != Speed.NONE) {
430            builder.append(",speed=").append(mSpeed);
431        }
432        builder.append(",metered=").append(isMetered());
433
434        return builder.append(')').toString();
435    }
436
437    /**
438     * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
439     * 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    /**
453     * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
454     *
455     * <p>Any cached {@link TimestampedScoredNetwork} objects older than
456     * {@link #MAX_CACHED_SCORE_AGE_MILLIS} will be removed when this method is invoked.
457     *
458     * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
459     *
460     * @param scoreCache The score cache to use to retrieve scores.
461     * @return true if the set speed has changed
462     */
463    private boolean updateScores(WifiNetworkScoreCache scoreCache) {
464        long nowMillis = SystemClock.elapsedRealtime();
465        for (ScanResult result : mScanResultCache.values()) {
466            ScoredNetwork score = scoreCache.getScoredNetwork(result);
467            if (score == null) {
468                continue;
469            }
470            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            }
478        }
479
480        // 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
489        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
500        if (isActive() && mInfo != null) {
501            TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(mInfo.getBSSID());
502            if (timedScore != null) {
503                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.
509                int speed = timedScore.getScore().calculateBadge(mInfo.getRssi());
510                if (speed != Speed.NONE) {
511                    mSpeed = speed;
512                }
513            }
514        }
515
516        boolean changed = oldSpeed != mSpeed;
517        if(WifiTracker.sVerboseLogging && changed) {
518            Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
519        }
520        return changed;
521    }
522
523    /** 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;
536        for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
537            int speed = timedScore.getScore().calculateBadge(mRssi);
538            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);
548    }
549
550    /**
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;
557
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;
564            }
565        } 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            }
573        }
574        return oldMetering == mIsScoredNetworkMetered;
575    }
576
577    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
582            if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MILLIS) {
583                iter.remove();
584            }
585        }
586    }
587
588    public boolean matches(ScanResult result) {
589        return ssid.equals(result.SSID) && security == getSecurity(result);
590    }
591
592    public boolean matches(WifiConfiguration config) {
593        if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
594            return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
595        } else {
596            return ssid.equals(removeDoubleQuotes(config.SSID))
597                    && security == getSecurity(config)
598                    && (mConfig == null || mConfig.shared == config.shared);
599        }
600    }
601
602    public WifiConfiguration getConfig() {
603        return mConfig;
604    }
605
606    public String getPasspointFqdn() {
607        return mFqdn;
608    }
609
610    public void clearConfig() {
611        mConfig = null;
612        networkId = WifiConfiguration.INVALID_NETWORK_ID;
613    }
614
615    public WifiInfo getInfo() {
616        return mInfo;
617    }
618
619    /**
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     */
625    public int getLevel() {
626        return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
627    }
628
629    public int getRssi() {
630        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
638     * 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}.
641     */
642    private void updateRssi() {
643        if (this.isActive()) {
644            return;
645        }
646
647        int rssi = UNREACHABLE_RSSI;
648        for (ScanResult result : mScanResultCache.values()) {
649            if (result.level > rssi) {
650                rssi = result.level;
651            }
652        }
653
654        if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
655            mRssi = (mRssi + rssi) / 2; // half-life previous value
656        } else {
657            mRssi = rssi;
658        }
659    }
660
661    /** Updates {@link #mSeen} based on the scan result cache. */
662    private void updateSeen() {
663        long seen = 0;
664        for (ScanResult result : mScanResultCache.values()) {
665            if (result.timestamp > seen) {
666                seen = result.timestamp;
667            }
668        }
669
670        // Only replace the previous value if we have a recent scan result to use
671        if (seen != 0) {
672            mSeen = seen;
673        }
674    }
675
676    /**
677     * Returns if the network should be considered metered.
678     */
679    public boolean isMetered() {
680        return mIsScoredNetworkMetered
681                || WifiConfiguration.isMetered(mConfig, mInfo);
682    }
683
684    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;
694        if (isPasspoint() || isPasspointConfig()) {
695            return concise ? context.getString(R.string.wifi_security_short_eap) :
696                context.getString(R.string.wifi_security_eap);
697        }
698        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
727    public String getSsidStr() {
728        return ssid;
729    }
730
731    public String getBssid() {
732        return bssid;
733    }
734
735    public CharSequence getSsid() {
736        final SpannableString str = new SpannableString(ssid);
737        str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
738                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
739        return str;
740    }
741
742    public String getConfigName() {
743        if (mConfig != null && mConfig.isPasspoint()) {
744            return mConfig.providerFriendlyName;
745        } else if (mFqdn != null) {
746            return mProviderFriendlyName;
747        } else {
748            return ssid;
749        }
750    }
751
752    public DetailedState getDetailedState() {
753        if (mNetworkInfo != null) {
754            return mNetworkInfo.getDetailedState();
755        }
756        Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
757        return null;
758    }
759
760    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
772    public String getSavedNetworkSummary() {
773        WifiConfiguration config = mConfig;
774        if (config != null) {
775            PackageManager pm = mContext.getPackageManager();
776            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
777            int userId = UserHandle.getUserId(config.creatorUid);
778            ApplicationInfo appInfo = null;
779            if (config.creatorName != null && config.creatorName.equals(systemName)) {
780                appInfo = mContext.getApplicationInfo();
781            } else {
782                try {
783                    IPackageManager ipm = AppGlobals.getPackageManager();
784                    appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
785                } 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            }
794        }
795        return "";
796    }
797
798    public String getSummary() {
799        return getSettingsSummary(mConfig);
800    }
801
802    public String getSettingsSummary() {
803        return getSettingsSummary(mConfig);
804    }
805
806    private String getSettingsSummary(WifiConfiguration config) {
807        // Update to new summary
808        StringBuilder summary = new StringBuilder();
809
810        if (isActive() && config != null && config.isPasspoint()) {
811            // This is the active connection on passpoint
812            summary.append(getSummary(mContext, getDetailedState(),
813                    false, config.providerFriendlyName));
814        } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
815                && mIsCarrierAp) {
816            summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
817        } else if (isActive()) {
818            // This is the active connection on non-passpoint network
819            summary.append(getSummary(mContext, getDetailedState(),
820                    mInfo != null && mInfo.isEphemeral()));
821        } else if (config != null && config.isPasspoint()
822                && config.getNetworkSelectionStatus().isNetworkEnabled()) {
823            String format = mContext.getString(R.string.available_via_passpoint);
824            summary.append(String.format(format, config.providerFriendlyName));
825        } else if (config != null && config.hasNoInternetAccess()) {
826            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));
830        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
831            WifiConfiguration.NetworkSelectionStatus networkStatus =
832                    config.getNetworkSelectionStatus();
833            switch (networkStatus.getNetworkSelectionDisableReason()) {
834                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
835                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
836                    break;
837                case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
838                    summary.append(mContext.getString(R.string.wifi_check_password_try_again));
839                    break;
840                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;
847            }
848        } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
849            summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
850        } else if (mIsCarrierAp) {
851            summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
852        } else if (!isReachable()) { // Wifi out of range
853            summary.append(mContext.getString(R.string.wifi_not_in_range));
854        } else { // In range, not disabled.
855            if (config != null) { // Is saved network
856                // 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                }
867            }
868        }
869
870        if (WifiTracker.sVerboseLogging) {
871            // 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
873            if (isActive() && mInfo != null) {
874                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
875            }
876            summary.append(" " + getVisibilityStatus());
877            if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
878                summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
879                if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
880                    long now = System.currentTimeMillis();
881                    long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
882                    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            }
892
893            if (config != null) {
894                WifiConfiguration.NetworkSelectionStatus networkStatus =
895                        config.getNetworkSelectionStatus();
896                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                }
905            }
906        }
907
908        // 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) {
911            return mContext.getResources().getString(
912                    R.string.preference_summary_default_combination,
913                    getSpeedLabel(),
914                    summary.toString());
915        } else if (getSpeedLabel() != null) {
916            return getSpeedLabel();
917        } else {
918            return summary.toString();
919        }
920    }
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();
932        StringBuilder scans24GHz = new StringBuilder();
933        StringBuilder scans5GHz = new StringBuilder();
934        String bssid = null;
935
936        long now = System.currentTimeMillis();
937
938        if (isActive() && mInfo != null) {
939            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);
946            if (mSpeed != Speed.NONE) {
947                visibility.append(" speed=").append(getSpeedLabel());
948            }
949            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
955        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
960        int numBlackListed = 0;
961        evictOldScanResults();
962
963        // TODO: sort list by RSSI or age
964        for (ScanResult result : mScanResultCache.values()) {
965            if (result.frequency >= LOWER_FREQ_5GHZ
966                    && result.frequency <= HIGHER_FREQ_5GHZ) {
967                // Strictly speaking: [4915, 5825]
968                num5++;
969
970                if (result.level > maxRssi5) {
971                    maxRssi5 = result.level;
972                }
973                if (num5 <= maxDisplayedScans) {
974                    scans5GHz.append(verboseScanResultSummary(result, bssid));
975                }
976            } else if (result.frequency >= LOWER_FREQ_24GHZ
977                    && result.frequency <= HIGHER_FREQ_24GHZ) {
978                // Strictly speaking: [2412, 2482]
979                num24++;
980
981                if (result.level > maxRssi24) {
982                    maxRssi24 = result.level;
983                }
984                if (num24 <= maxDisplayedScans) {
985                    scans24GHz.append(verboseScanResultSummary(result, bssid));
986                }
987            }
988        }
989        visibility.append(" [");
990        if (num24 > 0) {
991            visibility.append("(").append(num24).append(")");
992            if (num24 > maxDisplayedScans) {
993                visibility.append("max=").append(maxRssi24).append(",");
994            }
995            visibility.append(scans24GHz.toString());
996        }
997        visibility.append(";");
998        if (num5 > 0) {
999            visibility.append("(").append(num5).append(")");
1000            if (num5 > maxDisplayedScans) {
1001                visibility.append("max=").append(maxRssi5).append(",");
1002            }
1003            visibility.append(scans5GHz.toString());
1004        }
1005        if (numBlackListed > 0)
1006            visibility.append("!").append(numBlackListed);
1007        visibility.append("]");
1008
1009        return visibility.toString();
1010    }
1011
1012    @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);
1021        int speed = getSpecificApSpeed(result);
1022        if (speed != Speed.NONE) {
1023            stringBuilder.append(",")
1024                    .append(getSpeedLabel(speed));
1025        }
1026        stringBuilder.append("}");
1027        return stringBuilder.toString();
1028    }
1029
1030    @Speed private int getSpecificApSpeed(ScanResult result) {
1031        TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
1032        if (timedScore == null) {
1033            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
1037        return timedScore.getScore().calculateBadge(result.level);
1038    }
1039
1040    /**
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() {
1056        return mInfo != null && mInfo.isEphemeral() &&
1057                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
1058    }
1059
1060    /**
1061     * Return true if this AccessPoint represents a Passpoint AP.
1062     */
1063    public boolean isPasspoint() {
1064        return mConfig != null && mConfig.isPasspoint();
1065    }
1066
1067    /**
1068     * Return true if this AccessPoint represents a Passpoint provider configuration.
1069     */
1070    public boolean isPasspointConfig() {
1071        return mFqdn != null;
1072    }
1073
1074    /**
1075     * 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) {
1080        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
1081            return networkId == info.getNetworkId();
1082        } else if (config != null) {
1083            return matches(config);
1084        }
1085        else {
1086            // 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) {
1120        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
1121        bssid = config.BSSID;
1122        security = getSecurity(config);
1123        networkId = config.networkId;
1124        mConfig = config;
1125    }
1126
1127    private void initWithScanResult(ScanResult result) {
1128        ssid = result.SSID;
1129        bssid = result.BSSID;
1130        security = getSecurity(result);
1131        if (security == SECURITY_PSK)
1132            pskType = getPskType(result);
1133
1134        mScanResultCache.put(result.BSSID, result);
1135        updateRssi();
1136        mSeen = result.timestamp; // even if the timestamp is old it is still valid
1137        mIsCarrierAp = result.isCarrierAp;
1138        mCarrierApEapType = result.carrierApEapType;
1139        mCarrierName = result.carrierName;
1140    }
1141
1142    public void saveWifiState(Bundle savedState) {
1143        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1144        savedState.putInt(KEY_SECURITY, security);
1145        savedState.putInt(KEY_SPEED, mSpeed);
1146        savedState.putInt(KEY_PSKTYPE, pskType);
1147        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1148        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1149        evictOldScanResults();
1150        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
1151                new ArrayList<ScanResult>(mScanResultCache.values()));
1152        savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1153                new ArrayList<>(mScoredNetworkCache.values()));
1154        if (mNetworkInfo != null) {
1155            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1156        }
1157        if (mFqdn != null) {
1158            savedState.putString(KEY_FQDN, mFqdn);
1159        }
1160        if (mProviderFriendlyName != null) {
1161            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1162        }
1163        savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1164        savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1165        savedState.putString(KEY_CARRIER_NAME, mCarrierName);
1166    }
1167
1168    public void setListener(AccessPointListener listener) {
1169        mAccessPointListener = listener;
1170    }
1171
1172    /**
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) {
1182        if (matches(result)) {
1183            int oldLevel = getLevel();
1184
1185            /* Add or update the scan result for the BSSID */
1186            mScanResultCache.put(result.BSSID, result);
1187            if (evictOldScanResults) evictOldScanResults();
1188            updateSeen();
1189            updateRssi();
1190            int newLevel = getLevel();
1191
1192            if (newLevel > 0 && newLevel != oldLevel) {
1193                // Only update labels on visible rssi changes
1194                updateSpeed();
1195                if (mAccessPointListener != null) {
1196                    mAccessPointListener.onLevelChanged(this);
1197                }
1198            }
1199            // This flag only comes from scans, is not easily saved in config
1200            if (security == SECURITY_PSK) {
1201                pskType = getPskType(result);
1202            }
1203
1204            if (mAccessPointListener != null) {
1205                mAccessPointListener.onAccessPointChanged(this);
1206            }
1207
1208            // 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
1214            return true;
1215        }
1216        return false;
1217    }
1218
1219    /** Attempt to update the AccessPoint and return true if an update occurred. */
1220    public boolean update(
1221            @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1222        boolean updated = false;
1223        final int oldLevel = getLevel();
1224        if (info != null && isInfoForThisAccessPoint(config, info)) {
1225            updated = (mInfo == null);
1226            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            }
1232            if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
1233                mRssi = info.getRssi();
1234                updated = true;
1235            } else if (mNetworkInfo != null && networkInfo != null
1236                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1237                updated = true;
1238            }
1239            mInfo = info;
1240            mNetworkInfo = networkInfo;
1241        } else if (mInfo != null) {
1242            updated = true;
1243            mInfo = null;
1244            mNetworkInfo = null;
1245        }
1246        if (updated && mAccessPointListener != null) {
1247            mAccessPointListener.onAccessPointChanged(this);
1248
1249            if (oldLevel != getLevel() /* current level */) {
1250                mAccessPointListener.onLevelChanged(this);
1251            }
1252        }
1253        return updated;
1254    }
1255
1256    void update(@Nullable WifiConfiguration config) {
1257        mConfig = config;
1258        networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
1259        if (mAccessPointListener != null) {
1260            mAccessPointListener.onAccessPointChanged(this);
1261        }
1262    }
1263
1264    @VisibleForTesting
1265    void setRssi(int rssi) {
1266        mRssi = rssi;
1267    }
1268
1269    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1270    void setUnreachable() {
1271        setRssi(AccessPoint.UNREACHABLE_RSSI);
1272    }
1273
1274    int getSpeed() { return mSpeed;}
1275
1276    @Nullable
1277    String getSpeedLabel() {
1278        return getSpeedLabel(mSpeed);
1279    }
1280
1281    @Nullable
1282    @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) {
1299        switch (speed) {
1300            case Speed.VERY_FAST:
1301                return mContext.getString(R.string.speed_label_very_fast);
1302            case Speed.FAST:
1303                return mContext.getString(R.string.speed_label_fast);
1304            case Speed.MODERATE:
1305                return mContext.getString(R.string.speed_label_okay);
1306            case Speed.SLOW:
1307                return mContext.getString(R.string.speed_label_slow);
1308            case Speed.NONE:
1309            default:
1310                return null;
1311        }
1312    }
1313
1314    /** Return true if the current RSSI is reachable, and false otherwise. */
1315    public boolean isReachable() {
1316        return mRssi != UNREACHABLE_RSSI;
1317    }
1318
1319    public static String getSummary(Context context, String ssid, DetailedState state,
1320            boolean isEphemeral, String passpointProvider) {
1321        if (state == DetailedState.CONNECTED && ssid == null) {
1322            if (TextUtils.isEmpty(passpointProvider) == false) {
1323                // Special case for connected + passpoint networks.
1324                String format = context.getString(R.string.connected_via_passpoint);
1325                return String.format(format, passpointProvider);
1326            } else if (isEphemeral) {
1327                // Special case for connected + ephemeral networks.
1328                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                }
1337            }
1338        }
1339
1340        // 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));
1346            NetworkCapabilities nc = null;
1347
1348            try {
1349                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1350            } catch (RemoteException e) {}
1351
1352            if (nc != null) {
1353                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1354                    int id = context.getResources()
1355                            .getIdentifier("network_available_sign_in", "string", "android");
1356                    return context.getString(id);
1357                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1358                    return context.getString(R.string.wifi_connected_no_internet);
1359                }
1360            }
1361        }
1362        if (state == null) {
1363            Log.w(TAG, "state is null, returning empty summary");
1364            return "";
1365        }
1366        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) {
1371            return "";
1372        }
1373        return String.format(formats[index], ssid);
1374    }
1375
1376    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1377        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);
1383    }
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) {
1445        if (TextUtils.isEmpty(string)) {
1446            return "";
1447        }
1448        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}
1461