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