AccessPoint.java revision a78256947d190a84169a31340c086cfacfcf0697
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        boolean changed = oldSpeed != mSpeed;
500        if(WifiTracker.sVerboseLogging && changed) {
501            Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
502        }
503        return changed;
504    }
505
506    /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
507    @Speed private int generateAverageSpeedForSsid() {
508        if (mScoredNetworkCache.isEmpty()) {
509            return Speed.NONE;
510        }
511
512        if (Log.isLoggable(TAG, Log.DEBUG)) {
513            Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
514                    getSsidStr(), mScoredNetworkCache));
515        }
516
517        // TODO(b/63073866): If flickering issues persist, consider mapping using getLevel rather
518        // than specific rssi value so score doesn't change without a visible wifi bar change. This
519        // issue is likely to be more evident for the active AP whose RSSI value is not half-lifed.
520
521        int count = 0;
522        int totalSpeed = 0;
523        for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
524            int speed = timedScore.getScore().calculateBadge(mRssi);
525            if (speed != Speed.NONE) {
526                count++;
527                totalSpeed += speed;
528            }
529        }
530        int speed = count == 0 ? Speed.NONE : totalSpeed / count;
531        if (WifiTracker.sVerboseLogging) {
532            Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
533        }
534        return roundToClosestSpeedEnum(speed);
535    }
536
537    /**
538     * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
539     * true if the metering changed.
540     */
541    private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
542        boolean oldMetering = mIsScoredNetworkMetered;
543        mIsScoredNetworkMetered = false;
544
545        if (isActive() && mInfo != null) {
546            NetworkKey key = new NetworkKey(new WifiKey(
547                    AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID()));
548            ScoredNetwork score = scoreCache.getScoredNetwork(key);
549            if (score != null) {
550                mIsScoredNetworkMetered |= score.meteredHint;
551            }
552        } else {
553            for (ScanResult result : mScanResultCache.values()) {
554                ScoredNetwork score = scoreCache.getScoredNetwork(result);
555                if (score == null) {
556                    continue;
557                }
558                mIsScoredNetworkMetered |= score.meteredHint;
559            }
560        }
561        return oldMetering == mIsScoredNetworkMetered;
562    }
563
564    private void evictOldScanResults() {
565        long nowMs = SystemClock.elapsedRealtime();
566        for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
567            ScanResult result = iter.next();
568            // result timestamp is in microseconds
569            if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MILLIS) {
570                iter.remove();
571            }
572        }
573    }
574
575    public boolean matches(ScanResult result) {
576        return ssid.equals(result.SSID) && security == getSecurity(result);
577    }
578
579    public boolean matches(WifiConfiguration config) {
580        if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
581            return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
582        } else {
583            return ssid.equals(removeDoubleQuotes(config.SSID))
584                    && security == getSecurity(config)
585                    && (mConfig == null || mConfig.shared == config.shared);
586        }
587    }
588
589    public WifiConfiguration getConfig() {
590        return mConfig;
591    }
592
593    public String getPasspointFqdn() {
594        return mFqdn;
595    }
596
597    public void clearConfig() {
598        mConfig = null;
599        networkId = WifiConfiguration.INVALID_NETWORK_ID;
600    }
601
602    public WifiInfo getInfo() {
603        return mInfo;
604    }
605
606    /**
607     * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
608     *
609     * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
610     * always return at least 0.
611     */
612    public int getLevel() {
613        return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
614    }
615
616    public int getRssi() {
617        return mRssi;
618    }
619
620    /**
621     * Updates {@link #mRssi}.
622     *
623     * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
624     * If the given AccessPoint is not active, a value will be calculated from previous scan
625     * results, returning the best RSSI for all matching AccessPoints averaged with the previous
626     * value. If the access point is not connected and there are no scan results, the rssi will be
627     * set to {@link #UNREACHABLE_RSSI}.
628     */
629    private void updateRssi() {
630        if (this.isActive()) {
631            return;
632        }
633
634        int rssi = UNREACHABLE_RSSI;
635        for (ScanResult result : mScanResultCache.values()) {
636            if (result.level > rssi) {
637                rssi = result.level;
638            }
639        }
640
641        if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
642            mRssi = (mRssi + rssi) / 2; // half-life previous value
643        } else {
644            mRssi = rssi;
645        }
646    }
647
648    /** Updates {@link #mSeen} based on the scan result cache. */
649    private void updateSeen() {
650        long seen = 0;
651        for (ScanResult result : mScanResultCache.values()) {
652            if (result.timestamp > seen) {
653                seen = result.timestamp;
654            }
655        }
656
657        // Only replace the previous value if we have a recent scan result to use
658        if (seen != 0) {
659            mSeen = seen;
660        }
661    }
662
663    /**
664     * Returns if the network should be considered metered.
665     */
666    public boolean isMetered() {
667        return mIsScoredNetworkMetered
668                || WifiConfiguration.isMetered(mConfig, mInfo);
669    }
670
671    public NetworkInfo getNetworkInfo() {
672        return mNetworkInfo;
673    }
674
675    public int getSecurity() {
676        return security;
677    }
678
679    public String getSecurityString(boolean concise) {
680        Context context = mContext;
681        if (isPasspoint() || isPasspointConfig()) {
682            return concise ? context.getString(R.string.wifi_security_short_eap) :
683                context.getString(R.string.wifi_security_eap);
684        }
685        switch(security) {
686            case SECURITY_EAP:
687                return concise ? context.getString(R.string.wifi_security_short_eap) :
688                    context.getString(R.string.wifi_security_eap);
689            case SECURITY_PSK:
690                switch (pskType) {
691                    case PSK_WPA:
692                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
693                            context.getString(R.string.wifi_security_wpa);
694                    case PSK_WPA2:
695                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
696                            context.getString(R.string.wifi_security_wpa2);
697                    case PSK_WPA_WPA2:
698                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
699                            context.getString(R.string.wifi_security_wpa_wpa2);
700                    case PSK_UNKNOWN:
701                    default:
702                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
703                                : context.getString(R.string.wifi_security_psk_generic);
704                }
705            case SECURITY_WEP:
706                return concise ? context.getString(R.string.wifi_security_short_wep) :
707                    context.getString(R.string.wifi_security_wep);
708            case SECURITY_NONE:
709            default:
710                return concise ? "" : context.getString(R.string.wifi_security_none);
711        }
712    }
713
714    public String getSsidStr() {
715        return ssid;
716    }
717
718    public String getBssid() {
719        return bssid;
720    }
721
722    public CharSequence getSsid() {
723        final SpannableString str = new SpannableString(ssid);
724        str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
725                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
726        return str;
727    }
728
729    public String getConfigName() {
730        if (mConfig != null && mConfig.isPasspoint()) {
731            return mConfig.providerFriendlyName;
732        } else if (mFqdn != null) {
733            return mProviderFriendlyName;
734        } else {
735            return ssid;
736        }
737    }
738
739    public DetailedState getDetailedState() {
740        if (mNetworkInfo != null) {
741            return mNetworkInfo.getDetailedState();
742        }
743        Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
744        return null;
745    }
746
747    public boolean isCarrierAp() {
748        return mIsCarrierAp;
749    }
750
751    public int getCarrierApEapType() {
752        return mCarrierApEapType;
753    }
754
755    public String getCarrierName() {
756        return mCarrierName;
757    }
758
759    public String getSavedNetworkSummary() {
760        WifiConfiguration config = mConfig;
761        if (config != null) {
762            PackageManager pm = mContext.getPackageManager();
763            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
764            int userId = UserHandle.getUserId(config.creatorUid);
765            ApplicationInfo appInfo = null;
766            if (config.creatorName != null && config.creatorName.equals(systemName)) {
767                appInfo = mContext.getApplicationInfo();
768            } else {
769                try {
770                    IPackageManager ipm = AppGlobals.getPackageManager();
771                    appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
772                } catch (RemoteException rex) {
773                }
774            }
775            if (appInfo != null &&
776                    !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
777                    !appInfo.packageName.equals(
778                    mContext.getString(R.string.certinstaller_package))) {
779                return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
780            }
781        }
782        return "";
783    }
784
785    public String getSummary() {
786        return getSettingsSummary(mConfig);
787    }
788
789    public String getSettingsSummary() {
790        return getSettingsSummary(mConfig);
791    }
792
793    private String getSettingsSummary(WifiConfiguration config) {
794        // Update to new summary
795        StringBuilder summary = new StringBuilder();
796
797        if (isActive() && config != null && config.isPasspoint()) {
798            // This is the active connection on passpoint
799            summary.append(getSummary(mContext, getDetailedState(),
800                    false, config.providerFriendlyName));
801        } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
802                && mIsCarrierAp) {
803            summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
804        } else if (isActive()) {
805            // This is the active connection on non-passpoint network
806            summary.append(getSummary(mContext, getDetailedState(),
807                    mInfo != null && mInfo.isEphemeral()));
808        } else if (config != null && config.isPasspoint()
809                && config.getNetworkSelectionStatus().isNetworkEnabled()) {
810            String format = mContext.getString(R.string.available_via_passpoint);
811            summary.append(String.format(format, config.providerFriendlyName));
812        } else if (config != null && config.hasNoInternetAccess()) {
813            int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
814                    ? R.string.wifi_no_internet_no_reconnect
815                    : R.string.wifi_no_internet;
816            summary.append(mContext.getString(messageID));
817        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
818            WifiConfiguration.NetworkSelectionStatus networkStatus =
819                    config.getNetworkSelectionStatus();
820            switch (networkStatus.getNetworkSelectionDisableReason()) {
821                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
822                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
823                    break;
824                case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
825                    summary.append(mContext.getString(R.string.wifi_check_password_try_again));
826                    break;
827                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
828                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
829                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
830                    break;
831                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
832                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
833                    break;
834            }
835        } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
836            summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
837        } else if (mIsCarrierAp) {
838            summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
839        } else if (!isReachable()) { // Wifi out of range
840            summary.append(mContext.getString(R.string.wifi_not_in_range));
841        } else { // In range, not disabled.
842            if (config != null) { // Is saved network
843                // Last attempt to connect to this failed. Show reason why
844                switch (config.recentFailure.getAssociationStatus()) {
845                    case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
846                        summary.append(mContext.getString(
847                                R.string.wifi_ap_unable_to_handle_new_sta));
848                        break;
849                    default:
850                        // "Saved"
851                        summary.append(mContext.getString(R.string.wifi_remembered));
852                        break;
853                }
854            }
855        }
856
857        if (WifiTracker.sVerboseLogging) {
858            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
859            // verbose WiFi Logging is only turned on thru developers settings
860            if (isActive() && mInfo != null) {
861                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
862            }
863            summary.append(" " + getVisibilityStatus());
864            if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
865                summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
866                if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
867                    long now = System.currentTimeMillis();
868                    long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
869                    long sec = diff%60; //seconds
870                    long min = (diff/60)%60; //minutes
871                    long hour = (min/60)%60; //hours
872                    summary.append(", ");
873                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
874                    summary.append( Long.toString(min) + "m ");
875                    summary.append( Long.toString(sec) + "s ");
876                }
877                summary.append(")");
878            }
879
880            if (config != null) {
881                WifiConfiguration.NetworkSelectionStatus networkStatus =
882                        config.getNetworkSelectionStatus();
883                for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
884                        index < WifiConfiguration.NetworkSelectionStatus
885                        .NETWORK_SELECTION_DISABLED_MAX; index++) {
886                    if (networkStatus.getDisableReasonCounter(index) != 0) {
887                        summary.append(" " + WifiConfiguration.NetworkSelectionStatus
888                                .getNetworkDisableReasonString(index) + "="
889                                + networkStatus.getDisableReasonCounter(index));
890                    }
891                }
892            }
893        }
894
895        // If Speed label and summary are both present, use the preference combination to combine
896        // the two, else return the non-null one.
897        if (getSpeedLabel() != null && summary.length() != 0) {
898            return mContext.getResources().getString(
899                    R.string.preference_summary_default_combination,
900                    getSpeedLabel(),
901                    summary.toString());
902        } else if (getSpeedLabel() != null) {
903            return getSpeedLabel();
904        } else {
905            return summary.toString();
906        }
907    }
908
909    /**
910     * Returns the visibility status of the WifiConfiguration.
911     *
912     * @return autojoin debugging information
913     * TODO: use a string formatter
914     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
915     * For instance [-40,5/-30,2]
916     */
917    private String getVisibilityStatus() {
918        StringBuilder visibility = new StringBuilder();
919        StringBuilder scans24GHz = new StringBuilder();
920        StringBuilder scans5GHz = new StringBuilder();
921        String bssid = null;
922
923        long now = System.currentTimeMillis();
924
925        if (isActive() && mInfo != null) {
926            bssid = mInfo.getBSSID();
927            if (bssid != null) {
928                visibility.append(" ").append(bssid);
929            }
930            visibility.append(" rssi=").append(mInfo.getRssi());
931            visibility.append(" ");
932            visibility.append(" score=").append(mInfo.score);
933            if (mSpeed != Speed.NONE) {
934                visibility.append(" speed=").append(getSpeedLabel());
935            }
936            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
937            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
938            visibility.append(String.format("%.1f ", mInfo.txBadRate));
939            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
940        }
941
942        int maxRssi5 = WifiConfiguration.INVALID_RSSI;
943        int maxRssi24 = WifiConfiguration.INVALID_RSSI;
944        final int maxDisplayedScans = 4;
945        int num5 = 0; // number of scanned BSSID on 5GHz band
946        int num24 = 0; // number of scanned BSSID on 2.4Ghz band
947        int numBlackListed = 0;
948        evictOldScanResults();
949
950        // TODO: sort list by RSSI or age
951        for (ScanResult result : mScanResultCache.values()) {
952            if (result.frequency >= LOWER_FREQ_5GHZ
953                    && result.frequency <= HIGHER_FREQ_5GHZ) {
954                // Strictly speaking: [4915, 5825]
955                num5++;
956
957                if (result.level > maxRssi5) {
958                    maxRssi5 = result.level;
959                }
960                if (num5 <= maxDisplayedScans) {
961                    scans5GHz.append(verboseScanResultSummary(result, bssid));
962                }
963            } else if (result.frequency >= LOWER_FREQ_24GHZ
964                    && result.frequency <= HIGHER_FREQ_24GHZ) {
965                // Strictly speaking: [2412, 2482]
966                num24++;
967
968                if (result.level > maxRssi24) {
969                    maxRssi24 = result.level;
970                }
971                if (num24 <= maxDisplayedScans) {
972                    scans24GHz.append(verboseScanResultSummary(result, bssid));
973                }
974            }
975        }
976        visibility.append(" [");
977        if (num24 > 0) {
978            visibility.append("(").append(num24).append(")");
979            if (num24 > maxDisplayedScans) {
980                visibility.append("max=").append(maxRssi24).append(",");
981            }
982            visibility.append(scans24GHz.toString());
983        }
984        visibility.append(";");
985        if (num5 > 0) {
986            visibility.append("(").append(num5).append(")");
987            if (num5 > maxDisplayedScans) {
988                visibility.append("max=").append(maxRssi5).append(",");
989            }
990            visibility.append(scans5GHz.toString());
991        }
992        if (numBlackListed > 0)
993            visibility.append("!").append(numBlackListed);
994        visibility.append("]");
995
996        return visibility.toString();
997    }
998
999    @VisibleForTesting
1000    /* package */ String verboseScanResultSummary(ScanResult result, String bssid) {
1001        StringBuilder stringBuilder = new StringBuilder();
1002        stringBuilder.append(" \n{").append(result.BSSID);
1003        if (result.BSSID.equals(bssid)) {
1004            stringBuilder.append("*");
1005        }
1006        stringBuilder.append("=").append(result.frequency);
1007        stringBuilder.append(",").append(result.level);
1008        int speed = getSpecificApSpeed(result);
1009        if (speed != Speed.NONE) {
1010            stringBuilder.append(",")
1011                    .append(getSpeedLabel(speed));
1012        }
1013        stringBuilder.append("}");
1014        return stringBuilder.toString();
1015    }
1016
1017    @Speed private int getSpecificApSpeed(ScanResult result) {
1018        TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
1019        if (timedScore == null) {
1020            return Speed.NONE;
1021        }
1022        // For debugging purposes we may want to use mRssi rather than result.level as the average
1023        // speed wil be determined by mRssi
1024        return timedScore.getScore().calculateBadge(result.level);
1025    }
1026
1027    /**
1028     * Return whether this is the active connection.
1029     * For ephemeral connections (networkId is invalid), this returns false if the network is
1030     * disconnected.
1031     */
1032    public boolean isActive() {
1033        return mNetworkInfo != null &&
1034                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1035                 mNetworkInfo.getState() != State.DISCONNECTED);
1036    }
1037
1038    public boolean isConnectable() {
1039        return getLevel() != -1 && getDetailedState() == null;
1040    }
1041
1042    public boolean isEphemeral() {
1043        return mInfo != null && mInfo.isEphemeral() &&
1044                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
1045    }
1046
1047    /**
1048     * Return true if this AccessPoint represents a Passpoint AP.
1049     */
1050    public boolean isPasspoint() {
1051        return mConfig != null && mConfig.isPasspoint();
1052    }
1053
1054    /**
1055     * Return true if this AccessPoint represents a Passpoint provider configuration.
1056     */
1057    public boolean isPasspointConfig() {
1058        return mFqdn != null;
1059    }
1060
1061    /**
1062     * Return whether the given {@link WifiInfo} is for this access point.
1063     * If the current AP does not have a network Id then the config is used to
1064     * match based on SSID and security.
1065     */
1066    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
1067        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
1068            return networkId == info.getNetworkId();
1069        } else if (config != null) {
1070            return matches(config);
1071        }
1072        else {
1073            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1074            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1075            // TODO: Handle hex string SSIDs.
1076            return ssid.equals(removeDoubleQuotes(info.getSSID()));
1077        }
1078    }
1079
1080    public boolean isSaved() {
1081        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
1082    }
1083
1084    public Object getTag() {
1085        return mTag;
1086    }
1087
1088    public void setTag(Object tag) {
1089        mTag = tag;
1090    }
1091
1092    /**
1093     * Generate and save a default wifiConfiguration with common values.
1094     * Can only be called for unsecured networks.
1095     */
1096    public void generateOpenNetworkConfig() {
1097        if (security != SECURITY_NONE)
1098            throw new IllegalStateException();
1099        if (mConfig != null)
1100            return;
1101        mConfig = new WifiConfiguration();
1102        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
1103        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1104    }
1105
1106    void loadConfig(WifiConfiguration config) {
1107        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
1108        bssid = config.BSSID;
1109        security = getSecurity(config);
1110        networkId = config.networkId;
1111        mConfig = config;
1112    }
1113
1114    private void initWithScanResult(ScanResult result) {
1115        ssid = result.SSID;
1116        bssid = result.BSSID;
1117        security = getSecurity(result);
1118        if (security == SECURITY_PSK)
1119            pskType = getPskType(result);
1120
1121        mScanResultCache.put(result.BSSID, result);
1122        updateRssi();
1123        mSeen = result.timestamp; // even if the timestamp is old it is still valid
1124        mIsCarrierAp = result.isCarrierAp;
1125        mCarrierApEapType = result.carrierApEapType;
1126        mCarrierName = result.carrierName;
1127    }
1128
1129    public void saveWifiState(Bundle savedState) {
1130        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1131        savedState.putInt(KEY_SECURITY, security);
1132        savedState.putInt(KEY_SPEED, mSpeed);
1133        savedState.putInt(KEY_PSKTYPE, pskType);
1134        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1135        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1136        evictOldScanResults();
1137        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
1138                new ArrayList<ScanResult>(mScanResultCache.values()));
1139        savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1140                new ArrayList<>(mScoredNetworkCache.values()));
1141        if (mNetworkInfo != null) {
1142            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1143        }
1144        if (mFqdn != null) {
1145            savedState.putString(KEY_FQDN, mFqdn);
1146        }
1147        if (mProviderFriendlyName != null) {
1148            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1149        }
1150        savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1151        savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1152        savedState.putString(KEY_CARRIER_NAME, mCarrierName);
1153    }
1154
1155    public void setListener(AccessPointListener listener) {
1156        mAccessPointListener = listener;
1157    }
1158
1159    /**
1160     * Update the AP with the given scan result.
1161     *
1162     * @param result the ScanResult to add to the AccessPoint scan cache
1163     * @param evictOldScanResults whether stale scan results should be removed
1164     *         from the cache during this update process
1165     * @return true if the scan result update caused a change in state which would impact ranking
1166     *     or AccessPoint rendering (e.g. wifi level, security)
1167     */
1168    boolean update(ScanResult result, boolean evictOldScanResults) {
1169        if (matches(result)) {
1170            int oldLevel = getLevel();
1171
1172            /* Add or update the scan result for the BSSID */
1173            mScanResultCache.put(result.BSSID, result);
1174            if (evictOldScanResults) evictOldScanResults();
1175            updateSeen();
1176            updateRssi();
1177            int newLevel = getLevel();
1178
1179            if (newLevel > 0 && newLevel != oldLevel) {
1180                // Only update labels on visible rssi changes
1181                updateSpeed();
1182                if (mAccessPointListener != null) {
1183                    mAccessPointListener.onLevelChanged(this);
1184                }
1185            }
1186            // This flag only comes from scans, is not easily saved in config
1187            if (security == SECURITY_PSK) {
1188                pskType = getPskType(result);
1189            }
1190
1191            if (mAccessPointListener != null) {
1192                mAccessPointListener.onAccessPointChanged(this);
1193            }
1194
1195            // The carrier info in the ScanResult is set by the platform based on the SSID and will
1196            // always be the same for all matching scan results.
1197            mIsCarrierAp = result.isCarrierAp;
1198            mCarrierApEapType = result.carrierApEapType;
1199            mCarrierName = result.carrierName;
1200
1201            return true;
1202        }
1203        return false;
1204    }
1205
1206    /** Attempt to update the AccessPoint and return true if an update occurred. */
1207    public boolean update(
1208            @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1209        boolean updated = false;
1210        final int oldLevel = getLevel();
1211        if (info != null && isInfoForThisAccessPoint(config, info)) {
1212            updated = (mInfo == null);
1213            if (mConfig != config) {
1214                // We do not set updated = true as we do not want to increase the amount of sorting
1215                // and copying performed in WifiTracker at this time. If issues involving refresh
1216                // are still seen, we will investigate further.
1217                update(config); // Notifies the AccessPointListener of the change
1218            }
1219            if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
1220                mRssi = info.getRssi();
1221                updated = true;
1222            } else if (mNetworkInfo != null && networkInfo != null
1223                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1224                updated = true;
1225            }
1226            mInfo = info;
1227            mNetworkInfo = networkInfo;
1228        } else if (mInfo != null) {
1229            updated = true;
1230            mInfo = null;
1231            mNetworkInfo = null;
1232        }
1233        if (updated && mAccessPointListener != null) {
1234            mAccessPointListener.onAccessPointChanged(this);
1235
1236            if (oldLevel != getLevel() /* current level */) {
1237                mAccessPointListener.onLevelChanged(this);
1238            }
1239        }
1240        return updated;
1241    }
1242
1243    void update(@Nullable WifiConfiguration config) {
1244        mConfig = config;
1245        networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
1246        if (mAccessPointListener != null) {
1247            mAccessPointListener.onAccessPointChanged(this);
1248        }
1249    }
1250
1251    @VisibleForTesting
1252    void setRssi(int rssi) {
1253        mRssi = rssi;
1254    }
1255
1256    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1257    void setUnreachable() {
1258        setRssi(AccessPoint.UNREACHABLE_RSSI);
1259    }
1260
1261    int getSpeed() { return mSpeed;}
1262
1263    @Nullable
1264    String getSpeedLabel() {
1265        return getSpeedLabel(mSpeed);
1266    }
1267
1268    @Nullable
1269    @Speed
1270    private int roundToClosestSpeedEnum(int speed) {
1271        if (speed < Speed.SLOW) {
1272            return Speed.NONE;
1273        } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1274            return Speed.SLOW;
1275        } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1276            return Speed.MODERATE;
1277        } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1278            return Speed.FAST;
1279        } else {
1280            return Speed.VERY_FAST;
1281        }
1282    }
1283
1284    @Nullable
1285    private String getSpeedLabel(@Speed int speed) {
1286        switch (speed) {
1287            case Speed.VERY_FAST:
1288                return mContext.getString(R.string.speed_label_very_fast);
1289            case Speed.FAST:
1290                return mContext.getString(R.string.speed_label_fast);
1291            case Speed.MODERATE:
1292                return mContext.getString(R.string.speed_label_okay);
1293            case Speed.SLOW:
1294                return mContext.getString(R.string.speed_label_slow);
1295            case Speed.NONE:
1296            default:
1297                return null;
1298        }
1299    }
1300
1301    /** Return true if the current RSSI is reachable, and false otherwise. */
1302    public boolean isReachable() {
1303        return mRssi != UNREACHABLE_RSSI;
1304    }
1305
1306    public static String getSummary(Context context, String ssid, DetailedState state,
1307            boolean isEphemeral, String passpointProvider) {
1308        if (state == DetailedState.CONNECTED && ssid == null) {
1309            if (TextUtils.isEmpty(passpointProvider) == false) {
1310                // Special case for connected + passpoint networks.
1311                String format = context.getString(R.string.connected_via_passpoint);
1312                return String.format(format, passpointProvider);
1313            } else if (isEphemeral) {
1314                // Special case for connected + ephemeral networks.
1315                final NetworkScoreManager networkScoreManager = context.getSystemService(
1316                        NetworkScoreManager.class);
1317                NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1318                if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1319                    String format = context.getString(R.string.connected_via_network_scorer);
1320                    return String.format(format, scorer.getRecommendationServiceLabel());
1321                } else {
1322                    return context.getString(R.string.connected_via_network_scorer_default);
1323                }
1324            }
1325        }
1326
1327        // Case when there is wifi connected without internet connectivity.
1328        final ConnectivityManager cm = (ConnectivityManager)
1329                context.getSystemService(Context.CONNECTIVITY_SERVICE);
1330        if (state == DetailedState.CONNECTED) {
1331            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1332                    ServiceManager.getService(Context.WIFI_SERVICE));
1333            NetworkCapabilities nc = null;
1334
1335            try {
1336                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1337            } catch (RemoteException e) {}
1338
1339            if (nc != null) {
1340                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1341                    int id = context.getResources()
1342                            .getIdentifier("network_available_sign_in", "string", "android");
1343                    return context.getString(id);
1344                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1345                    return context.getString(R.string.wifi_connected_no_internet);
1346                }
1347            }
1348        }
1349        if (state == null) {
1350            Log.w(TAG, "state is null, returning empty summary");
1351            return "";
1352        }
1353        String[] formats = context.getResources().getStringArray((ssid == null)
1354                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1355        int index = state.ordinal();
1356
1357        if (index >= formats.length || formats[index].length() == 0) {
1358            return "";
1359        }
1360        return String.format(formats[index], ssid);
1361    }
1362
1363    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1364        return getSummary(context, null, state, isEphemeral, null);
1365    }
1366
1367    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1368            String passpointProvider) {
1369        return getSummary(context, null, state, isEphemeral, passpointProvider);
1370    }
1371
1372    public static String convertToQuotedString(String string) {
1373        return "\"" + string + "\"";
1374    }
1375
1376    private static int getPskType(ScanResult result) {
1377        boolean wpa = result.capabilities.contains("WPA-PSK");
1378        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1379        if (wpa2 && wpa) {
1380            return PSK_WPA_WPA2;
1381        } else if (wpa2) {
1382            return PSK_WPA2;
1383        } else if (wpa) {
1384            return PSK_WPA;
1385        } else {
1386            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1387            return PSK_UNKNOWN;
1388        }
1389    }
1390
1391    private static int getSecurity(ScanResult result) {
1392        if (result.capabilities.contains("WEP")) {
1393            return SECURITY_WEP;
1394        } else if (result.capabilities.contains("PSK")) {
1395            return SECURITY_PSK;
1396        } else if (result.capabilities.contains("EAP")) {
1397            return SECURITY_EAP;
1398        }
1399        return SECURITY_NONE;
1400    }
1401
1402    static int getSecurity(WifiConfiguration config) {
1403        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1404            return SECURITY_PSK;
1405        }
1406        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1407                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1408            return SECURITY_EAP;
1409        }
1410        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1411    }
1412
1413    public static String securityToString(int security, int pskType) {
1414        if (security == SECURITY_WEP) {
1415            return "WEP";
1416        } else if (security == SECURITY_PSK) {
1417            if (pskType == PSK_WPA) {
1418                return "WPA";
1419            } else if (pskType == PSK_WPA2) {
1420                return "WPA2";
1421            } else if (pskType == PSK_WPA_WPA2) {
1422                return "WPA_WPA2";
1423            }
1424            return "PSK";
1425        } else if (security == SECURITY_EAP) {
1426            return "EAP";
1427        }
1428        return "NONE";
1429    }
1430
1431    static String removeDoubleQuotes(String string) {
1432        if (TextUtils.isEmpty(string)) {
1433            return "";
1434        }
1435        int length = string.length();
1436        if ((length > 1) && (string.charAt(0) == '"')
1437                && (string.charAt(length - 1) == '"')) {
1438            return string.substring(1, length - 1);
1439        }
1440        return string;
1441    }
1442
1443    public interface AccessPointListener {
1444        void onAccessPointChanged(AccessPoint accessPoint);
1445        void onLevelChanged(AccessPoint accessPoint);
1446    }
1447}
1448