AccessPoint.java revision 9bb85d3c4d0698e41dd5a27a534d55d9f983daaf
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.style.TtsSpan;
55import android.util.Log;
56
57import com.android.internal.annotations.VisibleForTesting;
58import com.android.settingslib.R;
59
60import java.lang.annotation.Retention;
61import java.lang.annotation.RetentionPolicy;
62import java.util.ArrayList;
63import java.util.HashMap;
64import java.util.Iterator;
65import java.util.Map;
66import java.util.Objects;
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 of scan results to hold onto while actively scanning. **/
137    private static final long MAX_SCAN_RESULT_AGE_MILLIS = 15000;
138
139    static final String KEY_NETWORKINFO = "key_networkinfo";
140    static final String KEY_WIFIINFO = "key_wifiinfo";
141    static final String KEY_SCANRESULT = "key_scanresult";
142    static final String KEY_SSID = "key_ssid";
143    static final String KEY_SECURITY = "key_security";
144    static final String KEY_SPEED = "key_speed";
145    static final String KEY_PSKTYPE = "key_psktype";
146    static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
147    static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
148    static final String KEY_CONFIG = "key_config";
149    static final String KEY_FQDN = "key_fqdn";
150    static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
151    static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
152    static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
153    static final String KEY_CARRIER_NAME = "key_carrier_name";
154    static final AtomicInteger sLastId = new AtomicInteger(0);
155
156    /**
157     * These values are matched in string arrays -- changes must be kept in sync
158     */
159    public static final int SECURITY_NONE = 0;
160    public static final int SECURITY_WEP = 1;
161    public static final int SECURITY_PSK = 2;
162    public static final int SECURITY_EAP = 3;
163
164    private static final int PSK_UNKNOWN = 0;
165    private static final int PSK_WPA = 1;
166    private static final int PSK_WPA2 = 2;
167    private static final int PSK_WPA_WPA2 = 3;
168
169    /**
170     * The number of distinct wifi levels.
171     *
172     * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
173     */
174    public static final int SIGNAL_LEVELS = 5;
175
176    public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
177
178    private final Context mContext;
179
180    private String ssid;
181    private String bssid;
182    private int security;
183    private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
184
185    private int pskType = PSK_UNKNOWN;
186
187    private WifiConfiguration mConfig;
188
189    private int mRssi = UNREACHABLE_RSSI;
190
191    private WifiInfo mInfo;
192    private NetworkInfo mNetworkInfo;
193    AccessPointListener mAccessPointListener;
194
195    private Object mTag;
196
197    @Speed private int mSpeed = Speed.NONE;
198    private boolean mIsScoredNetworkMetered = false;
199
200    // used to co-relate internal vs returned accesspoint.
201    int mId;
202
203    /**
204     * Information associated with the {@link PasspointConfiguration}.  Only maintaining
205     * the relevant info to preserve spaces.
206     */
207    private String mFqdn;
208    private String mProviderFriendlyName;
209
210    private boolean mIsCarrierAp = false;
211    /**
212     * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
213     */
214    private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
215    private String mCarrierName = null;
216
217    public AccessPoint(Context context, Bundle savedState) {
218        mContext = context;
219        mConfig = savedState.getParcelable(KEY_CONFIG);
220        if (mConfig != null) {
221            loadConfig(mConfig);
222        }
223        if (savedState.containsKey(KEY_SSID)) {
224            ssid = savedState.getString(KEY_SSID);
225        }
226        if (savedState.containsKey(KEY_SECURITY)) {
227            security = savedState.getInt(KEY_SECURITY);
228        }
229        if (savedState.containsKey(KEY_SPEED)) {
230            mSpeed = savedState.getInt(KEY_SPEED);
231        }
232        if (savedState.containsKey(KEY_PSKTYPE)) {
233            pskType = savedState.getInt(KEY_PSKTYPE);
234        }
235        mInfo = savedState.getParcelable(KEY_WIFIINFO);
236        if (savedState.containsKey(KEY_NETWORKINFO)) {
237            mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
238        }
239        if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
240            ArrayList<ScanResult> scanResultArrayList =
241                    savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
242            mScanResultCache.clear();
243            for (ScanResult result : scanResultArrayList) {
244                mScanResultCache.put(result.BSSID, result);
245            }
246        }
247        if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
248            ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
249                    savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
250            for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
251                mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
252            }
253        }
254        if (savedState.containsKey(KEY_FQDN)) {
255            mFqdn = savedState.getString(KEY_FQDN);
256        }
257        if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
258            mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
259        }
260        if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
261            mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
262        }
263        if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
264            mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
265        }
266        if (savedState.containsKey(KEY_CARRIER_NAME)) {
267            mCarrierName = savedState.getString(KEY_CARRIER_NAME);
268        }
269        update(mConfig, mInfo, mNetworkInfo);
270
271        // Do not evict old scan results on initial creation
272        updateRssi();
273        mId = sLastId.incrementAndGet();
274    }
275
276    public AccessPoint(Context context, WifiConfiguration config) {
277        mContext = context;
278        loadConfig(config);
279        mId = sLastId.incrementAndGet();
280    }
281
282    /**
283     * Initialize an AccessPoint object for a {@link PasspointConfiguration}.  This is mainly
284     * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
285     */
286    public AccessPoint(Context context, PasspointConfiguration config) {
287        mContext = context;
288        mFqdn = config.getHomeSp().getFqdn();
289        mProviderFriendlyName = config.getHomeSp().getFriendlyName();
290        mId = sLastId.incrementAndGet();
291    }
292
293    AccessPoint(Context context, AccessPoint other) {
294        mContext = context;
295        copyFrom(other);
296    }
297
298    AccessPoint(Context context, ScanResult result) {
299        mContext = context;
300        initWithScanResult(result);
301        mId = sLastId.incrementAndGet();
302    }
303
304    /**
305     * Copy accesspoint information. NOTE: We do not copy tag information because that is never
306     * set on the internal copy.
307     * @param that
308     */
309    void copyFrom(AccessPoint that) {
310        that.evictOldScanResults();
311        this.ssid = that.ssid;
312        this.bssid = that.bssid;
313        this.security = that.security;
314        this.networkId = that.networkId;
315        this.pskType = that.pskType;
316        this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated.
317        this.mRssi = that.mRssi;
318        this.mInfo = that.mInfo;
319        this.mNetworkInfo = that.mNetworkInfo;
320        this.mScanResultCache.clear();
321        this.mScanResultCache.putAll(that.mScanResultCache);
322        this.mScoredNetworkCache.clear();
323        this.mScoredNetworkCache.putAll(that.mScoredNetworkCache);
324        this.mId = that.mId;
325        this.mSpeed = that.mSpeed;
326        this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered;
327        this.mIsCarrierAp = that.mIsCarrierAp;
328        this.mCarrierApEapType = that.mCarrierApEapType;
329        this.mCarrierName = that.mCarrierName;
330    }
331
332    /**
333    * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
334    * equal to, or greater than the other AccessPoint.
335    *
336    * Sort order rules for AccessPoints:
337    *   1. Active before inactive
338    *   2. Reachable before unreachable
339    *   3. Saved before unsaved
340    *   4. Network speed value
341    *   5. Stronger signal before weaker signal
342    *   6. SSID alphabetically
343    *
344    * Note that AccessPoints with a signal are usually also Reachable,
345    * and will thus appear before unreachable saved AccessPoints.
346    */
347    @Override
348    public int compareTo(@NonNull AccessPoint other) {
349        // Active one goes first.
350        if (isActive() && !other.isActive()) return -1;
351        if (!isActive() && other.isActive()) return 1;
352
353        // Reachable one goes before unreachable one.
354        if (isReachable() && !other.isReachable()) return -1;
355        if (!isReachable() && other.isReachable()) return 1;
356
357        // Configured (saved) one goes before unconfigured one.
358        if (isSaved() && !other.isSaved()) return -1;
359        if (!isSaved() && other.isSaved()) return 1;
360
361        // Faster speeds go before slower speeds - but only if visible change in speed label
362        if (getSpeed() != other.getSpeed()) {
363            return other.getSpeed() - getSpeed();
364        }
365
366        // Sort by signal strength, bucketed by level
367        int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
368                - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
369        if (difference != 0) {
370            return difference;
371        }
372
373        // Sort by ssid.
374        difference = getSsidStr().compareToIgnoreCase(other.getSsidStr());
375        if (difference != 0) {
376            return difference;
377        }
378
379        // Do a case sensitive comparison to distinguish SSIDs that differ in case only
380        return getSsidStr().compareTo(other.getSsidStr());
381    }
382
383    @Override
384    public boolean equals(Object other) {
385        if (!(other instanceof AccessPoint)) return false;
386        return (this.compareTo((AccessPoint) other) == 0);
387    }
388
389    @Override
390    public int hashCode() {
391        int result = 0;
392        if (mInfo != null) result += 13 * mInfo.hashCode();
393        result += 19 * mRssi;
394        result += 23 * networkId;
395        result += 29 * ssid.hashCode();
396        return result;
397    }
398
399    @Override
400    public String toString() {
401        StringBuilder builder = new StringBuilder().append("AccessPoint(")
402                .append(ssid);
403        if (bssid != null) {
404            builder.append(":").append(bssid);
405        }
406        if (isSaved()) {
407            builder.append(',').append("saved");
408        }
409        if (isActive()) {
410            builder.append(',').append("active");
411        }
412        if (isEphemeral()) {
413            builder.append(',').append("ephemeral");
414        }
415        if (isConnectable()) {
416            builder.append(',').append("connectable");
417        }
418        if (security != SECURITY_NONE) {
419            builder.append(',').append(securityToString(security, pskType));
420        }
421        builder.append(",level=").append(getLevel());
422        if (mSpeed != Speed.NONE) {
423            builder.append(",speed=").append(mSpeed);
424        }
425        builder.append(",metered=").append(isMetered());
426
427        return builder.append(')').toString();
428    }
429
430    /**
431     * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
432     * changed.
433     *
434     * @param scoreCache The score cache to use to retrieve scores
435     * @param scoringUiEnabled Whether to show scoring and badging UI
436     * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
437     *         generating speed labels
438     */
439    boolean update(
440            WifiNetworkScoreCache scoreCache,
441            boolean scoringUiEnabled,
442            long maxScoreCacheAgeMillis) {
443        boolean scoreChanged = false;
444        if (scoringUiEnabled) {
445            scoreChanged = updateScores(scoreCache, maxScoreCacheAgeMillis);
446        }
447        return updateMetered(scoreCache) || scoreChanged;
448    }
449
450    /**
451     * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
452     *
453     * <p>Any cached {@link TimestampedScoredNetwork} objects older than the given max age in millis
454     * will be removed when this method is invoked.
455     *
456     * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
457     *
458     * @param scoreCache The score cache to use to retrieve scores
459     * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
460     *         generating speed labels
461     *
462     * @return true if the set speed has changed
463     */
464    private boolean updateScores(WifiNetworkScoreCache scoreCache, long maxScoreCacheAgeMillis) {
465        long nowMillis = SystemClock.elapsedRealtime();
466        for (ScanResult result : mScanResultCache.values()) {
467            ScoredNetwork score = scoreCache.getScoredNetwork(result);
468            if (score == null) {
469                continue;
470            }
471            TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
472            if (timedScore == null) {
473                mScoredNetworkCache.put(
474                        result.BSSID, new TimestampedScoredNetwork(score, nowMillis));
475            } else {
476                // Update data since the has been seen in the score cache
477                timedScore.update(score, nowMillis);
478            }
479        }
480
481        // Remove old cached networks
482        long evictionCutoff = nowMillis - maxScoreCacheAgeMillis;
483        Iterator<TimestampedScoredNetwork> iterator = mScoredNetworkCache.values().iterator();
484        iterator.forEachRemaining(timestampedScoredNetwork -> {
485            if (timestampedScoredNetwork.getUpdatedTimestampMillis() < evictionCutoff) {
486                iterator.remove();
487            }
488        });
489
490        return updateSpeed();
491    }
492
493    /**
494     * Updates the internal speed, returning true if the update resulted in a speed label change.
495     */
496    private boolean updateSpeed() {
497        int oldSpeed = mSpeed;
498        mSpeed = generateAverageSpeedForSsid();
499
500        boolean changed = oldSpeed != mSpeed;
501        if(WifiTracker.sVerboseLogging && changed) {
502            Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
503        }
504        return changed;
505    }
506
507    /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
508    @Speed private int generateAverageSpeedForSsid() {
509        if (mScoredNetworkCache.isEmpty()) {
510            return Speed.NONE;
511        }
512
513        if (Log.isLoggable(TAG, Log.DEBUG)) {
514            Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
515                    getSsidStr(), mScoredNetworkCache));
516        }
517
518        // TODO(b/63073866): If flickering issues persist, consider mapping using getLevel rather
519        // than specific rssi value so score doesn't change without a visible wifi bar change. This
520        // issue is likely to be more evident for the active AP whose RSSI value is not half-lifed.
521
522        int count = 0;
523        int totalSpeed = 0;
524        for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
525            int speed = timedScore.getScore().calculateBadge(mRssi);
526            if (speed != Speed.NONE) {
527                count++;
528                totalSpeed += speed;
529            }
530        }
531        int speed = count == 0 ? Speed.NONE : totalSpeed / count;
532        if (WifiTracker.sVerboseLogging) {
533            Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
534        }
535        return roundToClosestSpeedEnum(speed);
536    }
537
538    /**
539     * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
540     * true if the metering changed.
541     */
542    private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
543        boolean oldMetering = mIsScoredNetworkMetered;
544        mIsScoredNetworkMetered = false;
545
546        if (isActive() && mInfo != null) {
547            NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
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    /**
649     * Returns if the network should be considered metered.
650     */
651    public boolean isMetered() {
652        return mIsScoredNetworkMetered
653                || WifiConfiguration.isMetered(mConfig, mInfo);
654    }
655
656    public NetworkInfo getNetworkInfo() {
657        return mNetworkInfo;
658    }
659
660    public int getSecurity() {
661        return security;
662    }
663
664    public String getSecurityString(boolean concise) {
665        Context context = mContext;
666        if (isPasspoint() || isPasspointConfig()) {
667            return concise ? context.getString(R.string.wifi_security_short_eap) :
668                context.getString(R.string.wifi_security_eap);
669        }
670        switch(security) {
671            case SECURITY_EAP:
672                return concise ? context.getString(R.string.wifi_security_short_eap) :
673                    context.getString(R.string.wifi_security_eap);
674            case SECURITY_PSK:
675                switch (pskType) {
676                    case PSK_WPA:
677                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
678                            context.getString(R.string.wifi_security_wpa);
679                    case PSK_WPA2:
680                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
681                            context.getString(R.string.wifi_security_wpa2);
682                    case PSK_WPA_WPA2:
683                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
684                            context.getString(R.string.wifi_security_wpa_wpa2);
685                    case PSK_UNKNOWN:
686                    default:
687                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
688                                : context.getString(R.string.wifi_security_psk_generic);
689                }
690            case SECURITY_WEP:
691                return concise ? context.getString(R.string.wifi_security_short_wep) :
692                    context.getString(R.string.wifi_security_wep);
693            case SECURITY_NONE:
694            default:
695                return concise ? "" : context.getString(R.string.wifi_security_none);
696        }
697    }
698
699    public String getSsidStr() {
700        return ssid;
701    }
702
703    public String getBssid() {
704        return bssid;
705    }
706
707    public CharSequence getSsid() {
708        final SpannableString str = new SpannableString(ssid);
709        str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
710                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
711        return str;
712    }
713
714    public String getConfigName() {
715        if (mConfig != null && mConfig.isPasspoint()) {
716            return mConfig.providerFriendlyName;
717        } else if (mFqdn != null) {
718            return mProviderFriendlyName;
719        } else {
720            return ssid;
721        }
722    }
723
724    public DetailedState getDetailedState() {
725        if (mNetworkInfo != null) {
726            return mNetworkInfo.getDetailedState();
727        }
728        Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
729        return null;
730    }
731
732    public boolean isCarrierAp() {
733        return mIsCarrierAp;
734    }
735
736    public int getCarrierApEapType() {
737        return mCarrierApEapType;
738    }
739
740    public String getCarrierName() {
741        return mCarrierName;
742    }
743
744    public String getSavedNetworkSummary() {
745        WifiConfiguration config = mConfig;
746        if (config != null) {
747            PackageManager pm = mContext.getPackageManager();
748            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
749            int userId = UserHandle.getUserId(config.creatorUid);
750            ApplicationInfo appInfo = null;
751            if (config.creatorName != null && config.creatorName.equals(systemName)) {
752                appInfo = mContext.getApplicationInfo();
753            } else {
754                try {
755                    IPackageManager ipm = AppGlobals.getPackageManager();
756                    appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
757                } catch (RemoteException rex) {
758                }
759            }
760            if (appInfo != null &&
761                    !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
762                    !appInfo.packageName.equals(
763                    mContext.getString(R.string.certinstaller_package))) {
764                return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
765            }
766        }
767        return "";
768    }
769
770    public String getSummary() {
771        return getSettingsSummary(mConfig);
772    }
773
774    public String getSettingsSummary() {
775        return getSettingsSummary(mConfig);
776    }
777
778    private String getSettingsSummary(WifiConfiguration config) {
779        // Update to new summary
780        StringBuilder summary = new StringBuilder();
781
782        if (isActive() && config != null && config.isPasspoint()) {
783            // This is the active connection on passpoint
784            summary.append(getSummary(mContext, getDetailedState(),
785                    false, config.providerFriendlyName));
786        } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
787                && mIsCarrierAp) {
788            summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
789        } else if (isActive()) {
790            // This is the active connection on non-passpoint network
791            summary.append(getSummary(mContext, getDetailedState(),
792                    mInfo != null && mInfo.isEphemeral()));
793        } else if (config != null && config.isPasspoint()
794                && config.getNetworkSelectionStatus().isNetworkEnabled()) {
795            String format = mContext.getString(R.string.available_via_passpoint);
796            summary.append(String.format(format, config.providerFriendlyName));
797        } else if (config != null && config.hasNoInternetAccess()) {
798            int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
799                    ? R.string.wifi_no_internet_no_reconnect
800                    : R.string.wifi_no_internet;
801            summary.append(mContext.getString(messageID));
802        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
803            WifiConfiguration.NetworkSelectionStatus networkStatus =
804                    config.getNetworkSelectionStatus();
805            switch (networkStatus.getNetworkSelectionDisableReason()) {
806                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
807                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
808                    break;
809                case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
810                    summary.append(mContext.getString(R.string.wifi_check_password_try_again));
811                    break;
812                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
813                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
814                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
815                    break;
816                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
817                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
818                    break;
819            }
820        } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
821            summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
822        } else if (mIsCarrierAp) {
823            summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
824        } else if (!isReachable()) { // Wifi out of range
825            summary.append(mContext.getString(R.string.wifi_not_in_range));
826        } else { // In range, not disabled.
827            if (config != null) { // Is saved network
828                // Last attempt to connect to this failed. Show reason why
829                switch (config.recentFailure.getAssociationStatus()) {
830                    case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
831                        summary.append(mContext.getString(
832                                R.string.wifi_ap_unable_to_handle_new_sta));
833                        break;
834                    default:
835                        // "Saved"
836                        summary.append(mContext.getString(R.string.wifi_remembered));
837                        break;
838                }
839            }
840        }
841
842        if (WifiTracker.sVerboseLogging) {
843            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
844            // verbose WiFi Logging is only turned on thru developers settings
845            if (isActive() && mInfo != null) {
846                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
847            }
848            summary.append(" " + getVisibilityStatus());
849            if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
850                summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
851                if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
852                    long now = System.currentTimeMillis();
853                    long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
854                    long sec = diff%60; //seconds
855                    long min = (diff/60)%60; //minutes
856                    long hour = (min/60)%60; //hours
857                    summary.append(", ");
858                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
859                    summary.append( Long.toString(min) + "m ");
860                    summary.append( Long.toString(sec) + "s ");
861                }
862                summary.append(")");
863            }
864
865            if (config != null) {
866                WifiConfiguration.NetworkSelectionStatus networkStatus =
867                        config.getNetworkSelectionStatus();
868                for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
869                        index < WifiConfiguration.NetworkSelectionStatus
870                        .NETWORK_SELECTION_DISABLED_MAX; index++) {
871                    if (networkStatus.getDisableReasonCounter(index) != 0) {
872                        summary.append(" " + WifiConfiguration.NetworkSelectionStatus
873                                .getNetworkDisableReasonString(index) + "="
874                                + networkStatus.getDisableReasonCounter(index));
875                    }
876                }
877            }
878        }
879
880        // If Speed label and summary are both present, use the preference combination to combine
881        // the two, else return the non-null one.
882        if (getSpeedLabel() != null && summary.length() != 0) {
883            return mContext.getResources().getString(
884                    R.string.preference_summary_default_combination,
885                    getSpeedLabel(),
886                    summary.toString());
887        } else if (getSpeedLabel() != null) {
888            return getSpeedLabel();
889        } else {
890            return summary.toString();
891        }
892    }
893
894    /**
895     * Returns the visibility status of the WifiConfiguration.
896     *
897     * @return autojoin debugging information
898     * TODO: use a string formatter
899     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
900     * For instance [-40,5/-30,2]
901     */
902    private String getVisibilityStatus() {
903        StringBuilder visibility = new StringBuilder();
904        StringBuilder scans24GHz = new StringBuilder();
905        StringBuilder scans5GHz = new StringBuilder();
906        String bssid = null;
907
908        long now = System.currentTimeMillis();
909
910        if (isActive() && mInfo != null) {
911            bssid = mInfo.getBSSID();
912            if (bssid != null) {
913                visibility.append(" ").append(bssid);
914            }
915            visibility.append(" rssi=").append(mInfo.getRssi());
916            visibility.append(" ");
917            visibility.append(" score=").append(mInfo.score);
918            if (mSpeed != Speed.NONE) {
919                visibility.append(" speed=").append(getSpeedLabel());
920            }
921            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
922            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
923            visibility.append(String.format("%.1f ", mInfo.txBadRate));
924            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
925        }
926
927        int maxRssi5 = WifiConfiguration.INVALID_RSSI;
928        int maxRssi24 = WifiConfiguration.INVALID_RSSI;
929        final int maxDisplayedScans = 4;
930        int num5 = 0; // number of scanned BSSID on 5GHz band
931        int num24 = 0; // number of scanned BSSID on 2.4Ghz band
932        int numBlackListed = 0;
933        evictOldScanResults();
934
935        // TODO: sort list by RSSI or age
936        for (ScanResult result : mScanResultCache.values()) {
937            if (result.frequency >= LOWER_FREQ_5GHZ
938                    && result.frequency <= HIGHER_FREQ_5GHZ) {
939                // Strictly speaking: [4915, 5825]
940                num5++;
941
942                if (result.level > maxRssi5) {
943                    maxRssi5 = result.level;
944                }
945                if (num5 <= maxDisplayedScans) {
946                    scans5GHz.append(verboseScanResultSummary(result, bssid));
947                }
948            } else if (result.frequency >= LOWER_FREQ_24GHZ
949                    && result.frequency <= HIGHER_FREQ_24GHZ) {
950                // Strictly speaking: [2412, 2482]
951                num24++;
952
953                if (result.level > maxRssi24) {
954                    maxRssi24 = result.level;
955                }
956                if (num24 <= maxDisplayedScans) {
957                    scans24GHz.append(verboseScanResultSummary(result, bssid));
958                }
959            }
960        }
961        visibility.append(" [");
962        if (num24 > 0) {
963            visibility.append("(").append(num24).append(")");
964            if (num24 > maxDisplayedScans) {
965                visibility.append("max=").append(maxRssi24).append(",");
966            }
967            visibility.append(scans24GHz.toString());
968        }
969        visibility.append(";");
970        if (num5 > 0) {
971            visibility.append("(").append(num5).append(")");
972            if (num5 > maxDisplayedScans) {
973                visibility.append("max=").append(maxRssi5).append(",");
974            }
975            visibility.append(scans5GHz.toString());
976        }
977        if (numBlackListed > 0)
978            visibility.append("!").append(numBlackListed);
979        visibility.append("]");
980
981        return visibility.toString();
982    }
983
984    @VisibleForTesting
985    /* package */ String verboseScanResultSummary(ScanResult result, String bssid) {
986        StringBuilder stringBuilder = new StringBuilder();
987        stringBuilder.append(" \n{").append(result.BSSID);
988        if (result.BSSID.equals(bssid)) {
989            stringBuilder.append("*");
990        }
991        stringBuilder.append("=").append(result.frequency);
992        stringBuilder.append(",").append(result.level);
993        int speed = getSpecificApSpeed(result);
994        if (speed != Speed.NONE) {
995            stringBuilder.append(",")
996                    .append(getSpeedLabel(speed));
997        }
998        stringBuilder.append("}");
999        return stringBuilder.toString();
1000    }
1001
1002    @Speed private int getSpecificApSpeed(ScanResult result) {
1003        TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
1004        if (timedScore == null) {
1005            return Speed.NONE;
1006        }
1007        // For debugging purposes we may want to use mRssi rather than result.level as the average
1008        // speed wil be determined by mRssi
1009        return timedScore.getScore().calculateBadge(result.level);
1010    }
1011
1012    /**
1013     * Return whether this is the active connection.
1014     * For ephemeral connections (networkId is invalid), this returns false if the network is
1015     * disconnected.
1016     */
1017    public boolean isActive() {
1018        return mNetworkInfo != null &&
1019                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1020                 mNetworkInfo.getState() != State.DISCONNECTED);
1021    }
1022
1023    public boolean isConnectable() {
1024        return getLevel() != -1 && getDetailedState() == null;
1025    }
1026
1027    public boolean isEphemeral() {
1028        return mInfo != null && mInfo.isEphemeral() &&
1029                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
1030    }
1031
1032    /**
1033     * Return true if this AccessPoint represents a Passpoint AP.
1034     */
1035    public boolean isPasspoint() {
1036        return mConfig != null && mConfig.isPasspoint();
1037    }
1038
1039    /**
1040     * Return true if this AccessPoint represents a Passpoint provider configuration.
1041     */
1042    public boolean isPasspointConfig() {
1043        return mFqdn != null;
1044    }
1045
1046    /**
1047     * Return whether the given {@link WifiInfo} is for this access point.
1048     * If the current AP does not have a network Id then the config is used to
1049     * match based on SSID and security.
1050     */
1051    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
1052        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
1053            return networkId == info.getNetworkId();
1054        } else if (config != null) {
1055            return matches(config);
1056        }
1057        else {
1058            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1059            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1060            // TODO: Handle hex string SSIDs.
1061            return ssid.equals(removeDoubleQuotes(info.getSSID()));
1062        }
1063    }
1064
1065    public boolean isSaved() {
1066        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
1067    }
1068
1069    public Object getTag() {
1070        return mTag;
1071    }
1072
1073    public void setTag(Object tag) {
1074        mTag = tag;
1075    }
1076
1077    /**
1078     * Generate and save a default wifiConfiguration with common values.
1079     * Can only be called for unsecured networks.
1080     */
1081    public void generateOpenNetworkConfig() {
1082        if (security != SECURITY_NONE)
1083            throw new IllegalStateException();
1084        if (mConfig != null)
1085            return;
1086        mConfig = new WifiConfiguration();
1087        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
1088        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1089    }
1090
1091    void loadConfig(WifiConfiguration config) {
1092        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
1093        bssid = config.BSSID;
1094        security = getSecurity(config);
1095        networkId = config.networkId;
1096        mConfig = config;
1097    }
1098
1099    private void initWithScanResult(ScanResult result) {
1100        ssid = result.SSID;
1101        bssid = result.BSSID;
1102        security = getSecurity(result);
1103        if (security == SECURITY_PSK)
1104            pskType = getPskType(result);
1105
1106        mScanResultCache.put(result.BSSID, result);
1107        updateRssi();
1108        mIsCarrierAp = result.isCarrierAp;
1109        mCarrierApEapType = result.carrierApEapType;
1110        mCarrierName = result.carrierName;
1111    }
1112
1113    public void saveWifiState(Bundle savedState) {
1114        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1115        savedState.putInt(KEY_SECURITY, security);
1116        savedState.putInt(KEY_SPEED, mSpeed);
1117        savedState.putInt(KEY_PSKTYPE, pskType);
1118        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1119        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1120        evictOldScanResults();
1121        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
1122                new ArrayList<ScanResult>(mScanResultCache.values()));
1123        savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1124                new ArrayList<>(mScoredNetworkCache.values()));
1125        if (mNetworkInfo != null) {
1126            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1127        }
1128        if (mFqdn != null) {
1129            savedState.putString(KEY_FQDN, mFqdn);
1130        }
1131        if (mProviderFriendlyName != null) {
1132            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1133        }
1134        savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1135        savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1136        savedState.putString(KEY_CARRIER_NAME, mCarrierName);
1137    }
1138
1139    public void setListener(AccessPointListener listener) {
1140        mAccessPointListener = listener;
1141    }
1142
1143    /**
1144     * Update the AP with the given scan result.
1145     *
1146     * @param result the ScanResult to add to the AccessPoint scan cache
1147     * @param evictOldScanResults whether stale scan results should be removed
1148     *         from the cache during this update process
1149     * @return true if the scan result update caused a change in state which would impact ranking
1150     *     or AccessPoint rendering (e.g. wifi level, security)
1151     */
1152    boolean update(ScanResult result, boolean evictOldScanResults) {
1153        if (matches(result)) {
1154            int oldLevel = getLevel();
1155
1156            /* Add or update the scan result for the BSSID */
1157            mScanResultCache.put(result.BSSID, result);
1158            if (evictOldScanResults) evictOldScanResults();
1159            updateRssi();
1160            int newLevel = getLevel();
1161
1162            if (newLevel > 0 && newLevel != oldLevel) {
1163                // Only update labels on visible rssi changes
1164                updateSpeed();
1165                if (mAccessPointListener != null) {
1166                    mAccessPointListener.onLevelChanged(this);
1167                }
1168            }
1169            // This flag only comes from scans, is not easily saved in config
1170            if (security == SECURITY_PSK) {
1171                pskType = getPskType(result);
1172            }
1173
1174            if (mAccessPointListener != null) {
1175                mAccessPointListener.onAccessPointChanged(this);
1176            }
1177
1178            // The carrier info in the ScanResult is set by the platform based on the SSID and will
1179            // always be the same for all matching scan results.
1180            mIsCarrierAp = result.isCarrierAp;
1181            mCarrierApEapType = result.carrierApEapType;
1182            mCarrierName = result.carrierName;
1183
1184            return true;
1185        }
1186        return false;
1187    }
1188
1189    /** Attempt to update the AccessPoint and return true if an update occurred. */
1190    public boolean update(
1191            @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1192        boolean updated = false;
1193        final int oldLevel = getLevel();
1194        if (info != null && isInfoForThisAccessPoint(config, info)) {
1195            updated = (mInfo == null);
1196            if (mConfig != config) {
1197                // We do not set updated = true as we do not want to increase the amount of sorting
1198                // and copying performed in WifiTracker at this time. If issues involving refresh
1199                // are still seen, we will investigate further.
1200                update(config); // Notifies the AccessPointListener of the change
1201            }
1202            if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
1203                mRssi = info.getRssi();
1204                updated = true;
1205            } else if (mNetworkInfo != null && networkInfo != null
1206                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1207                updated = true;
1208            }
1209            mInfo = info;
1210            mNetworkInfo = networkInfo;
1211        } else if (mInfo != null) {
1212            updated = true;
1213            mInfo = null;
1214            mNetworkInfo = null;
1215        }
1216        if (updated && mAccessPointListener != null) {
1217            mAccessPointListener.onAccessPointChanged(this);
1218
1219            if (oldLevel != getLevel() /* current level */) {
1220                mAccessPointListener.onLevelChanged(this);
1221            }
1222        }
1223        return updated;
1224    }
1225
1226    void update(@Nullable WifiConfiguration config) {
1227        mConfig = config;
1228        networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
1229        if (mAccessPointListener != null) {
1230            mAccessPointListener.onAccessPointChanged(this);
1231        }
1232    }
1233
1234    @VisibleForTesting
1235    void setRssi(int rssi) {
1236        mRssi = rssi;
1237    }
1238
1239    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1240    void setUnreachable() {
1241        setRssi(AccessPoint.UNREACHABLE_RSSI);
1242    }
1243
1244    int getSpeed() { return mSpeed;}
1245
1246    @Nullable
1247    String getSpeedLabel() {
1248        return getSpeedLabel(mSpeed);
1249    }
1250
1251    @Nullable
1252    @Speed
1253    private int roundToClosestSpeedEnum(int speed) {
1254        if (speed < Speed.SLOW) {
1255            return Speed.NONE;
1256        } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1257            return Speed.SLOW;
1258        } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1259            return Speed.MODERATE;
1260        } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1261            return Speed.FAST;
1262        } else {
1263            return Speed.VERY_FAST;
1264        }
1265    }
1266
1267    @Nullable
1268    private String getSpeedLabel(@Speed int speed) {
1269        switch (speed) {
1270            case Speed.VERY_FAST:
1271                return mContext.getString(R.string.speed_label_very_fast);
1272            case Speed.FAST:
1273                return mContext.getString(R.string.speed_label_fast);
1274            case Speed.MODERATE:
1275                return mContext.getString(R.string.speed_label_okay);
1276            case Speed.SLOW:
1277                return mContext.getString(R.string.speed_label_slow);
1278            case Speed.NONE:
1279            default:
1280                return null;
1281        }
1282    }
1283
1284    /** Return true if the current RSSI is reachable, and false otherwise. */
1285    public boolean isReachable() {
1286        return mRssi != UNREACHABLE_RSSI;
1287    }
1288
1289    public static String getSummary(Context context, String ssid, DetailedState state,
1290            boolean isEphemeral, String passpointProvider) {
1291        if (state == DetailedState.CONNECTED && ssid == null) {
1292            if (TextUtils.isEmpty(passpointProvider) == false) {
1293                // Special case for connected + passpoint networks.
1294                String format = context.getString(R.string.connected_via_passpoint);
1295                return String.format(format, passpointProvider);
1296            } else if (isEphemeral) {
1297                // Special case for connected + ephemeral networks.
1298                final NetworkScoreManager networkScoreManager = context.getSystemService(
1299                        NetworkScoreManager.class);
1300                NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1301                if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1302                    String format = context.getString(R.string.connected_via_network_scorer);
1303                    return String.format(format, scorer.getRecommendationServiceLabel());
1304                } else {
1305                    return context.getString(R.string.connected_via_network_scorer_default);
1306                }
1307            }
1308        }
1309
1310        // Case when there is wifi connected without internet connectivity.
1311        final ConnectivityManager cm = (ConnectivityManager)
1312                context.getSystemService(Context.CONNECTIVITY_SERVICE);
1313        if (state == DetailedState.CONNECTED) {
1314            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1315                    ServiceManager.getService(Context.WIFI_SERVICE));
1316            NetworkCapabilities nc = null;
1317
1318            try {
1319                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1320            } catch (RemoteException e) {}
1321
1322            if (nc != null) {
1323                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1324                    int id = context.getResources()
1325                            .getIdentifier("network_available_sign_in", "string", "android");
1326                    return context.getString(id);
1327                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1328                    return context.getString(R.string.wifi_connected_no_internet);
1329                }
1330            }
1331        }
1332        if (state == null) {
1333            Log.w(TAG, "state is null, returning empty summary");
1334            return "";
1335        }
1336        String[] formats = context.getResources().getStringArray((ssid == null)
1337                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1338        int index = state.ordinal();
1339
1340        if (index >= formats.length || formats[index].length() == 0) {
1341            return "";
1342        }
1343        return String.format(formats[index], ssid);
1344    }
1345
1346    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1347        return getSummary(context, null, state, isEphemeral, null);
1348    }
1349
1350    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1351            String passpointProvider) {
1352        return getSummary(context, null, state, isEphemeral, passpointProvider);
1353    }
1354
1355    public static String convertToQuotedString(String string) {
1356        return "\"" + string + "\"";
1357    }
1358
1359    private static int getPskType(ScanResult result) {
1360        boolean wpa = result.capabilities.contains("WPA-PSK");
1361        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1362        if (wpa2 && wpa) {
1363            return PSK_WPA_WPA2;
1364        } else if (wpa2) {
1365            return PSK_WPA2;
1366        } else if (wpa) {
1367            return PSK_WPA;
1368        } else {
1369            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1370            return PSK_UNKNOWN;
1371        }
1372    }
1373
1374    private static int getSecurity(ScanResult result) {
1375        if (result.capabilities.contains("WEP")) {
1376            return SECURITY_WEP;
1377        } else if (result.capabilities.contains("PSK")) {
1378            return SECURITY_PSK;
1379        } else if (result.capabilities.contains("EAP")) {
1380            return SECURITY_EAP;
1381        }
1382        return SECURITY_NONE;
1383    }
1384
1385    static int getSecurity(WifiConfiguration config) {
1386        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1387            return SECURITY_PSK;
1388        }
1389        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1390                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1391            return SECURITY_EAP;
1392        }
1393        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1394    }
1395
1396    public static String securityToString(int security, int pskType) {
1397        if (security == SECURITY_WEP) {
1398            return "WEP";
1399        } else if (security == SECURITY_PSK) {
1400            if (pskType == PSK_WPA) {
1401                return "WPA";
1402            } else if (pskType == PSK_WPA2) {
1403                return "WPA2";
1404            } else if (pskType == PSK_WPA_WPA2) {
1405                return "WPA_WPA2";
1406            }
1407            return "PSK";
1408        } else if (security == SECURITY_EAP) {
1409            return "EAP";
1410        }
1411        return "NONE";
1412    }
1413
1414    static String removeDoubleQuotes(String string) {
1415        if (TextUtils.isEmpty(string)) {
1416            return "";
1417        }
1418        int length = string.length();
1419        if ((length > 1) && (string.charAt(0) == '"')
1420                && (string.charAt(length - 1) == '"')) {
1421            return string.substring(1, length - 1);
1422        }
1423        return string;
1424    }
1425
1426    public interface AccessPointListener {
1427        void onAccessPointChanged(AccessPoint accessPoint);
1428        void onLevelChanged(AccessPoint accessPoint);
1429    }
1430}
1431