AccessPoint.java revision d52356aa5e82c7c5db61672bbe8d0f44861f3e59
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.content.Context;
20import android.net.NetworkInfo;
21import android.net.NetworkInfo.DetailedState;
22import android.net.NetworkInfo.State;
23import android.net.wifi.ScanResult;
24import android.net.wifi.WifiConfiguration;
25import android.net.wifi.WifiConfiguration.KeyMgmt;
26import android.net.wifi.WifiInfo;
27import android.net.wifi.WifiManager;
28import android.os.Bundle;
29import android.util.Log;
30import android.util.LruCache;
31
32import com.android.settingslib.R;
33
34import java.util.Map;
35
36
37public class AccessPoint implements Comparable<AccessPoint> {
38    static final String TAG = "SettingsLib.AccessPoint";
39
40    /**
41     * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
42     */
43    public static final int LOWER_FREQ_24GHZ = 2400;
44
45    /**
46     * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
47     */
48    public static final int HIGHER_FREQ_24GHZ = 2500;
49
50    /**
51     * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
52     */
53    public static final int LOWER_FREQ_5GHZ = 4900;
54
55    /**
56     * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
57     */
58    public static final int HIGHER_FREQ_5GHZ = 5900;
59
60
61    /**
62     * Experimental: we should be able to show the user the list of BSSIDs and bands
63     *  for that SSID.
64     *  For now this data is used only with Verbose Logging so as to show the band and number
65     *  of BSSIDs on which that network is seen.
66     */
67    public LruCache<String, ScanResult> mScanResultCache;
68    private static final String KEY_NETWORKINFO = "key_networkinfo";
69    private static final String KEY_WIFIINFO = "key_wifiinfo";
70    private static final String KEY_SCANRESULT = "key_scanresult";
71    private static final String KEY_CONFIG = "key_config";
72
73    /**
74     * These values are matched in string arrays -- changes must be kept in sync
75     */
76    public static final int SECURITY_NONE = 0;
77    public static final int SECURITY_WEP = 1;
78    public static final int SECURITY_PSK = 2;
79    public static final int SECURITY_EAP = 3;
80
81    private static final int PSK_UNKNOWN = 0;
82    private static final int PSK_WPA = 1;
83    private static final int PSK_WPA2 = 2;
84    private static final int PSK_WPA_WPA2 = 3;
85
86    private static final int VISIBILITY_OUTDATED_AGE_IN_MILLI = 20000;
87    private final Context mContext;
88
89    private String ssid;
90    private int security;
91    private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
92
93    private int pskType = PSK_UNKNOWN;
94
95    private WifiConfiguration mConfig;
96    private ScanResult mScanResult;
97
98    private int mRssi = Integer.MAX_VALUE;
99    private long mSeen = 0;
100
101    private WifiInfo mInfo;
102    private NetworkInfo mNetworkInfo;
103    private AccessPointListener mAccessPointListener;
104
105    private Object mTag;
106
107    public AccessPoint(Context context, Bundle savedState) {
108        mContext = context;
109        mConfig = savedState.getParcelable(KEY_CONFIG);
110        if (mConfig != null) {
111            loadConfig(mConfig);
112        }
113        mScanResult = (ScanResult) savedState.getParcelable(KEY_SCANRESULT);
114        if (mScanResult != null) {
115            loadResult(mScanResult);
116        }
117        mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
118        if (savedState.containsKey(KEY_NETWORKINFO)) {
119            mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
120        }
121        update(mInfo, mNetworkInfo);
122    }
123
124    AccessPoint(Context context, ScanResult result) {
125        mContext = context;
126        loadResult(result);
127    }
128
129    AccessPoint(Context context, WifiConfiguration config) {
130        mContext = context;
131        loadConfig(config);
132    }
133
134    @Override
135    public int compareTo(AccessPoint other) {
136        // Active one goes first.
137        if (isActive() && !other.isActive()) return -1;
138        if (!isActive() && other.isActive()) return 1;
139
140        // Reachable one goes before unreachable one.
141        if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1;
142        if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1;
143
144        // Configured one goes before unconfigured one.
145        if (networkId != WifiConfiguration.INVALID_NETWORK_ID
146                && other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1;
147        if (networkId == WifiConfiguration.INVALID_NETWORK_ID
148                && other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1;
149
150        // Sort by signal strength.
151        int difference = WifiManager.compareSignalLevel(other.mRssi, mRssi);
152        if (difference != 0) {
153            return difference;
154        }
155        // Sort by ssid.
156        return ssid.compareToIgnoreCase(other.ssid);
157    }
158
159    @Override
160    public boolean equals(Object other) {
161        if (!(other instanceof AccessPoint)) return false;
162        return (this.compareTo((AccessPoint) other) == 0);
163    }
164
165    @Override
166    public int hashCode() {
167        int result = 0;
168        if (mInfo != null) result += 13 * mInfo.hashCode();
169        result += 19 * mRssi;
170        result += 23 * networkId;
171        result += 29 * ssid.hashCode();
172        return result;
173    }
174
175    @Override
176    public String toString() {
177        StringBuilder builder = new StringBuilder().append("AccessPoint(")
178                .append(ssid);
179        if (isSaved()) {
180            builder.append(',').append("saved");
181        }
182        if (isActive()) {
183            builder.append(',').append("active");
184        }
185        if (isEphemeral()) {
186            builder.append(',').append("ephemeral");
187        }
188        if (isConnectable()) {
189            builder.append(',').append("connectable");
190        }
191        if (security != SECURITY_NONE) {
192            builder.append(',').append(securityToString(security, pskType));
193        }
194        return builder.append(')').toString();
195    }
196
197    public boolean matches(ScanResult result) {
198        return ssid.equals(result.SSID) && security == getSecurity(result);
199    }
200
201    public boolean matches(WifiConfiguration config) {
202        return ssid.equals(removeDoubleQuotes(config.SSID)) && security == getSecurity(config);
203    }
204
205    public WifiConfiguration getConfig() {
206        return mConfig;
207    }
208
209    public void clearConfig() {
210        mConfig = null;
211        networkId = WifiConfiguration.INVALID_NETWORK_ID;
212    }
213
214    public WifiInfo getInfo() {
215        return mInfo;
216    }
217
218    public int getLevel() {
219        if (mRssi == Integer.MAX_VALUE) {
220            return -1;
221        }
222        return WifiManager.calculateSignalLevel(mRssi, 4);
223    }
224
225    public NetworkInfo getNetworkInfo() {
226        return mNetworkInfo;
227    }
228
229    public int getSecurity() {
230        return security;
231    }
232
233    public String getSecurityString(boolean concise) {
234        Context context = mContext;
235        switch(security) {
236            case SECURITY_EAP:
237                return concise ? context.getString(R.string.wifi_security_short_eap) :
238                    context.getString(R.string.wifi_security_eap);
239            case SECURITY_PSK:
240                switch (pskType) {
241                    case PSK_WPA:
242                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
243                            context.getString(R.string.wifi_security_wpa);
244                    case PSK_WPA2:
245                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
246                            context.getString(R.string.wifi_security_wpa2);
247                    case PSK_WPA_WPA2:
248                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
249                            context.getString(R.string.wifi_security_wpa_wpa2);
250                    case PSK_UNKNOWN:
251                    default:
252                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
253                                : context.getString(R.string.wifi_security_psk_generic);
254                }
255            case SECURITY_WEP:
256                return concise ? context.getString(R.string.wifi_security_short_wep) :
257                    context.getString(R.string.wifi_security_wep);
258            case SECURITY_NONE:
259            default:
260                return concise ? "" : context.getString(R.string.wifi_security_none);
261        }
262    }
263
264    public String getSsid() {
265        return ssid;
266    }
267
268    public DetailedState getDetailedState() {
269        return mNetworkInfo != null ? mNetworkInfo.getDetailedState() : null;
270    }
271
272    public String getSummary() {
273        // Update to new summary
274        StringBuilder summary = new StringBuilder();
275
276        if (isActive()) { // This is the active connection
277            summary.append(getSummary(mContext, getDetailedState(),
278                    networkId == WifiConfiguration.INVALID_NETWORK_ID));
279        } else if (mConfig != null
280                && mConfig.hasNoInternetAccess()) {
281            summary.append(mContext.getString(R.string.wifi_no_internet));
282        } else if (mConfig != null && ((mConfig.status == WifiConfiguration.Status.DISABLED &&
283                mConfig.disableReason != WifiConfiguration.DISABLED_UNKNOWN_REASON)
284               || mConfig.autoJoinStatus
285                >= WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE)) {
286            if (mConfig.autoJoinStatus
287                    >= WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE) {
288                if (mConfig.disableReason == WifiConfiguration.DISABLED_DHCP_FAILURE) {
289                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
290                } else if (mConfig.disableReason == WifiConfiguration.DISABLED_AUTH_FAILURE) {
291                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
292                } else {
293                    summary.append(mContext.getString(R.string.wifi_disabled_wifi_failure));
294                }
295            } else {
296                switch (mConfig.disableReason) {
297                    case WifiConfiguration.DISABLED_AUTH_FAILURE:
298                        summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
299                        break;
300                    case WifiConfiguration.DISABLED_DHCP_FAILURE:
301                    case WifiConfiguration.DISABLED_DNS_FAILURE:
302                        summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
303                        break;
304                    case WifiConfiguration.DISABLED_UNKNOWN_REASON:
305                    case WifiConfiguration.DISABLED_ASSOCIATION_REJECT:
306                        summary.append(mContext.getString(R.string.wifi_disabled_generic));
307                        break;
308                }
309            }
310        } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
311            summary.append(mContext.getString(R.string.wifi_not_in_range));
312        } else { // In range, not disabled.
313            if (mConfig != null) { // Is saved network
314                summary.append(mContext.getString(R.string.wifi_remembered));
315            }
316        }
317
318        if (WifiTracker.sVerboseLogging > 0) {
319            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
320            // verbose WiFi Logging is only turned on thru developers settings
321            if (mInfo != null && mNetworkInfo != null) { // This is the active connection
322                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
323            }
324            summary.append(" " + getVisibilityStatus());
325            if (mConfig != null && mConfig.autoJoinStatus > 0) {
326                summary.append(" (" + mConfig.autoJoinStatus);
327                if (mConfig.blackListTimestamp > 0) {
328                    long now = System.currentTimeMillis();
329                    long diff = (now - mConfig.blackListTimestamp)/1000;
330                    long sec = diff%60; //seconds
331                    long min = (diff/60)%60; //minutes
332                    long hour = (min/60)%60; //hours
333                    summary.append(", ");
334                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
335                    summary.append( Long.toString(min) + "m ");
336                    summary.append( Long.toString(sec) + "s ");
337                }
338                summary.append(")");
339            }
340            if (mConfig != null && mConfig.numIpConfigFailures > 0) {
341                summary.append(" ipf=").append(mConfig.numIpConfigFailures);
342            }
343            if (mConfig != null && mConfig.numConnectionFailures > 0) {
344                summary.append(" cf=").append(mConfig.numConnectionFailures);
345            }
346            if (mConfig != null && mConfig.numAuthFailures > 0) {
347                summary.append(" authf=").append(mConfig.numAuthFailures);
348            }
349            if (mConfig != null && mConfig.numNoInternetAccessReports > 0) {
350                summary.append(" noInt=").append(mConfig.numNoInternetAccessReports);
351            }
352        }
353        return summary.toString();
354    }
355
356    /**
357     * Returns the visibility status of the WifiConfiguration.
358     *
359     * @return autojoin debugging information
360     * TODO: use a string formatter
361     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
362     * For instance [-40,5/-30,2]
363     */
364    private String getVisibilityStatus() {
365        StringBuilder visibility = new StringBuilder();
366        StringBuilder scans24GHz = null;
367        StringBuilder scans5GHz = null;
368        String bssid = null;
369
370        long now = System.currentTimeMillis();
371
372        if (mInfo != null) {
373            bssid = mInfo.getBSSID();
374            if (bssid != null) {
375                visibility.append(" ").append(bssid);
376            }
377            visibility.append(" rssi=").append(mInfo.getRssi());
378            visibility.append(" ");
379            visibility.append(" score=").append(mInfo.score);
380            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
381            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
382            visibility.append(String.format("%.1f ", mInfo.txBadRate));
383            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
384        }
385
386        if (mScanResultCache != null) {
387            int rssi5 = WifiConfiguration.INVALID_RSSI;
388            int rssi24 = WifiConfiguration.INVALID_RSSI;
389            int num5 = 0;
390            int num24 = 0;
391            int numBlackListed = 0;
392            int n24 = 0; // Number scan results we included in the string
393            int n5 = 0; // Number scan results we included in the string
394            Map<String, ScanResult> list = mScanResultCache.snapshot();
395            // TODO: sort list by RSSI or age
396            for (ScanResult result : list.values()) {
397                if (result.seen == 0)
398                    continue;
399
400                if (result.autoJoinStatus != ScanResult.ENABLED) numBlackListed++;
401
402                if (result.frequency >= LOWER_FREQ_5GHZ
403                        && result.frequency <= HIGHER_FREQ_5GHZ) {
404                    // Strictly speaking: [4915, 5825]
405                    // number of known BSSID on 5GHz band
406                    num5 = num5 + 1;
407                } else if (result.frequency >= LOWER_FREQ_24GHZ
408                        && result.frequency <= HIGHER_FREQ_24GHZ) {
409                    // Strictly speaking: [2412, 2482]
410                    // number of known BSSID on 2.4Ghz band
411                    num24 = num24 + 1;
412                }
413
414                // Ignore results seen, older than 20 seconds
415                if (now - result.seen > VISIBILITY_OUTDATED_AGE_IN_MILLI) continue;
416
417                if (result.frequency >= LOWER_FREQ_5GHZ
418                        && result.frequency <= HIGHER_FREQ_5GHZ) {
419                    if (result.level > rssi5) {
420                        rssi5 = result.level;
421                    }
422                    if (n5 < 4) {
423                        if (scans5GHz == null) scans5GHz = new StringBuilder();
424                        scans5GHz.append(" \n{").append(result.BSSID);
425                        if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
426                        scans5GHz.append("=").append(result.frequency);
427                        scans5GHz.append(",").append(result.level);
428                        if (result.autoJoinStatus != 0) {
429                            scans5GHz.append(",st=").append(result.autoJoinStatus);
430                        }
431                        if (result.numIpConfigFailures != 0) {
432                            scans5GHz.append(",ipf=").append(result.numIpConfigFailures);
433                        }
434                        scans5GHz.append("}");
435                        n5++;
436                    }
437                } else if (result.frequency >= LOWER_FREQ_24GHZ
438                        && result.frequency <= HIGHER_FREQ_24GHZ) {
439                    if (result.level > rssi24) {
440                        rssi24 = result.level;
441                    }
442                    if (n24 < 4) {
443                        if (scans24GHz == null) scans24GHz = new StringBuilder();
444                        scans24GHz.append(" \n{").append(result.BSSID);
445                        if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
446                        scans24GHz.append("=").append(result.frequency);
447                        scans24GHz.append(",").append(result.level);
448                        if (result.autoJoinStatus != 0) {
449                            scans24GHz.append(",st=").append(result.autoJoinStatus);
450                        }
451                        if (result.numIpConfigFailures != 0) {
452                            scans24GHz.append(",ipf=").append(result.numIpConfigFailures);
453                        }
454                        scans24GHz.append("}");
455                        n24++;
456                    }
457                }
458            }
459            visibility.append(" [");
460            if (num24 > 0) {
461                visibility.append("(").append(num24).append(")");
462                if (n24 <= 4) {
463                    if (scans24GHz != null) {
464                        visibility.append(scans24GHz.toString());
465                    }
466                } else {
467                    visibility.append("max=").append(rssi24);
468                    if (scans24GHz != null) {
469                        visibility.append(",").append(scans24GHz.toString());
470                    }
471                }
472            }
473            visibility.append(";");
474            if (num5 > 0) {
475                visibility.append("(").append(num5).append(")");
476                if (n5 <= 4) {
477                    if (scans5GHz != null) {
478                        visibility.append(scans5GHz.toString());
479                    }
480                } else {
481                    visibility.append("max=").append(rssi5);
482                    if (scans5GHz != null) {
483                        visibility.append(",").append(scans5GHz.toString());
484                    }
485                }
486            }
487            if (numBlackListed > 0)
488                visibility.append("!").append(numBlackListed);
489            visibility.append("]");
490        } else {
491            if (mRssi != Integer.MAX_VALUE) {
492                visibility.append(" rssi=");
493                visibility.append(mRssi);
494                if (mScanResult != null) {
495                    visibility.append(", f=");
496                    visibility.append(mScanResult.frequency);
497                }
498            }
499        }
500
501        return visibility.toString();
502    }
503
504    /**
505     * Return whether this is the active connection.
506     * For ephemeral connections (networkId is invalid), this returns false if the network is
507     * disconnected.
508     */
509    public boolean isActive() {
510        return mNetworkInfo != null &&
511                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
512                 mNetworkInfo.getState() != State.DISCONNECTED);
513    }
514
515    public boolean isConnectable() {
516        return getLevel() != -1 && getDetailedState() == null;
517    }
518
519    public boolean isEphemeral() {
520        return !isSaved() && mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
521    }
522
523    /** Return whether the given {@link WifiInfo} is for this access point. */
524    private boolean isInfoForThisAccessPoint(WifiInfo info) {
525        if (networkId != WifiConfiguration.INVALID_NETWORK_ID) {
526            return networkId == info.getNetworkId();
527        } else {
528            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
529            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
530            // TODO: Handle hex string SSIDs.
531            return ssid.equals(removeDoubleQuotes(info.getSSID()));
532        }
533    }
534
535    public boolean isSaved() {
536        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
537    }
538
539    public Object getTag() {
540        return mTag;
541    }
542
543    public void setTag(Object tag) {
544        mTag = tag;
545    }
546
547    /**
548     * Generate and save a default wifiConfiguration with common values.
549     * Can only be called for unsecured networks.
550     */
551    public void generateOpenNetworkConfig() {
552        if (security != SECURITY_NONE)
553            throw new IllegalStateException();
554        if (mConfig != null)
555            return;
556        mConfig = new WifiConfiguration();
557        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
558        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
559    }
560
561    void loadConfig(WifiConfiguration config) {
562        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
563        security = getSecurity(config);
564        networkId = config.networkId;
565        mConfig = config;
566    }
567
568    private void loadResult(ScanResult result) {
569        ssid = result.SSID;
570        security = getSecurity(result);
571        if (security == SECURITY_PSK)
572            pskType = getPskType(result);
573        mRssi = result.level;
574        mScanResult = result;
575        if (result.seen > mSeen) {
576            mSeen = result.seen;
577        }
578    }
579
580    public void saveWifiState(Bundle savedState) {
581        savedState.putParcelable(KEY_CONFIG, mConfig);
582        savedState.putParcelable(KEY_SCANRESULT, mScanResult);
583        savedState.putParcelable(KEY_WIFIINFO, mInfo);
584        if (mNetworkInfo != null) {
585            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
586        }
587    }
588
589    public void setListener(AccessPointListener listener) {
590        mAccessPointListener = listener;
591    }
592
593    boolean update(ScanResult result) {
594        if (result.seen > mSeen) {
595            mSeen = result.seen;
596        }
597        if (WifiTracker.sVerboseLogging > 0) {
598            if (mScanResultCache == null) {
599                mScanResultCache = new LruCache<String, ScanResult>(32);
600            }
601            mScanResultCache.put(result.BSSID, result);
602        }
603
604        if (ssid.equals(result.SSID) && security == getSecurity(result)) {
605            if (WifiManager.compareSignalLevel(result.level, mRssi) > 0) {
606                int oldLevel = getLevel();
607                mRssi = result.level;
608                if (getLevel() != oldLevel && mAccessPointListener != null) {
609                    mAccessPointListener.onLevelChanged(this);
610                }
611            }
612            // This flag only comes from scans, is not easily saved in config
613            if (security == SECURITY_PSK) {
614                pskType = getPskType(result);
615            }
616            mScanResult = result;
617            if (mAccessPointListener != null) {
618                mAccessPointListener.onAccessPointChanged(this);
619            }
620            return true;
621        }
622        return false;
623    }
624
625    boolean update(WifiInfo info, NetworkInfo networkInfo) {
626        boolean reorder = false;
627        if (info != null && isInfoForThisAccessPoint(info)) {
628            reorder = (mInfo == null);
629            mRssi = info.getRssi();
630            mInfo = info;
631            mNetworkInfo = networkInfo;
632            if (mAccessPointListener != null) {
633                mAccessPointListener.onAccessPointChanged(this);
634            }
635        } else if (mInfo != null) {
636            reorder = true;
637            mInfo = null;
638            mNetworkInfo = null;
639            if (mAccessPointListener != null) {
640                mAccessPointListener.onAccessPointChanged(this);
641            }
642        }
643        return reorder;
644    }
645
646    public static String getSummary(Context context, String ssid, DetailedState state,
647            boolean isEphemeral) {
648        if (state == DetailedState.CONNECTED && isEphemeral && ssid == null) {
649            // Special case for connected + ephemeral networks.
650            return context.getString(R.string.connected_via_wfa);
651        }
652
653        String[] formats = context.getResources().getStringArray((ssid == null)
654                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
655        int index = state.ordinal();
656
657        if (index >= formats.length || formats[index].length() == 0) {
658            return null;
659        }
660        return String.format(formats[index], ssid);
661    }
662
663    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
664        return getSummary(context, null, state, isEphemeral);
665    }
666
667    public static String convertToQuotedString(String string) {
668        return "\"" + string + "\"";
669    }
670
671    private static int getPskType(ScanResult result) {
672        boolean wpa = result.capabilities.contains("WPA-PSK");
673        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
674        if (wpa2 && wpa) {
675            return PSK_WPA_WPA2;
676        } else if (wpa2) {
677            return PSK_WPA2;
678        } else if (wpa) {
679            return PSK_WPA;
680        } else {
681            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
682            return PSK_UNKNOWN;
683        }
684    }
685
686    private static int getSecurity(ScanResult result) {
687        if (result.capabilities.contains("WEP")) {
688            return SECURITY_WEP;
689        } else if (result.capabilities.contains("PSK")) {
690            return SECURITY_PSK;
691        } else if (result.capabilities.contains("EAP")) {
692            return SECURITY_EAP;
693        }
694        return SECURITY_NONE;
695    }
696
697    static int getSecurity(WifiConfiguration config) {
698        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
699            return SECURITY_PSK;
700        }
701        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
702                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
703            return SECURITY_EAP;
704        }
705        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
706    }
707
708    public static String securityToString(int security, int pskType) {
709        if (security == SECURITY_WEP) {
710            return "WEP";
711        } else if (security == SECURITY_PSK) {
712            if (pskType == PSK_WPA) {
713                return "WPA";
714            } else if (pskType == PSK_WPA2) {
715                return "WPA2";
716            } else if (pskType == PSK_WPA_WPA2) {
717                return "WPA_WPA2";
718            }
719            return "PSK";
720        } else if (security == SECURITY_EAP) {
721            return "EAP";
722        }
723        return "NONE";
724    }
725
726    static String removeDoubleQuotes(String string) {
727        int length = string.length();
728        if ((length > 1) && (string.charAt(0) == '"')
729                && (string.charAt(length - 1) == '"')) {
730            return string.substring(1, length - 1);
731        }
732        return string;
733    }
734
735    public interface AccessPointListener {
736        void onAccessPointChanged(AccessPoint accessPoint);
737        void onLevelChanged(AccessPoint accessPoint);
738    }
739}
740