summaryrefslogtreecommitdiff
path: root/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.java
blob: a04d038ed4231d4392e7ff872c7587060d7df46f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settingslib.wifi;

import static android.net.wifi.WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLED;
import static android.net.wifi.WifiConfiguration.NetworkSelectionStatus.getMaxNetworkSelectionDisableReason;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.os.SystemClock;

import androidx.annotation.VisibleForTesting;

import com.android.settingslib.R;

import java.util.Map;

public class WifiUtils {

    private static final int INVALID_RSSI = -127;

    /**
     * The intent action shows network details settings to allow configuration of Wi-Fi.
     * <p>
     * In some cases, a matching Activity may not exist, so ensure you
     * safeguard against this.
     * <p>
     * Input: The calling package should put the chosen
     * com.android.wifitrackerlib.WifiEntry#getKey() to a string extra in the request bundle into
     * the {@link #KEY_CHOSEN_WIFIENTRY_KEY}.
     * <p>
     * Output: Nothing.
     */
    public static final String ACTION_WIFI_DETAILS_SETTINGS =
            "android.settings.WIFI_DETAILS_SETTINGS";
    public static final String KEY_CHOSEN_WIFIENTRY_KEY = "key_chosen_wifientry_key";
    public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";

    static final int[] WIFI_PIE = {
            com.android.internal.R.drawable.ic_wifi_signal_0,
            com.android.internal.R.drawable.ic_wifi_signal_1,
            com.android.internal.R.drawable.ic_wifi_signal_2,
            com.android.internal.R.drawable.ic_wifi_signal_3,
            com.android.internal.R.drawable.ic_wifi_signal_4
    };

    static final int[] NO_INTERNET_WIFI_PIE = {
            R.drawable.ic_no_internet_wifi_signal_0,
            R.drawable.ic_no_internet_wifi_signal_1,
            R.drawable.ic_no_internet_wifi_signal_2,
            R.drawable.ic_no_internet_wifi_signal_3,
            R.drawable.ic_no_internet_wifi_signal_4
    };

    static final int[] WIFI_4_PIE = {
            com.android.internal.R.drawable.ic_wifi_4_signal_0,
            com.android.internal.R.drawable.ic_wifi_4_signal_1,
            com.android.internal.R.drawable.ic_wifi_4_signal_2,
            com.android.internal.R.drawable.ic_wifi_4_signal_3,
            com.android.internal.R.drawable.ic_wifi_4_signal_4
    };

    static final int[] WIFI_5_PIE = {
            com.android.internal.R.drawable.ic_wifi_5_signal_0,
            com.android.internal.R.drawable.ic_wifi_5_signal_1,
            com.android.internal.R.drawable.ic_wifi_5_signal_2,
            com.android.internal.R.drawable.ic_wifi_5_signal_3,
            com.android.internal.R.drawable.ic_wifi_5_signal_4
    };

    static final int[] WIFI_6_PIE = {
            com.android.internal.R.drawable.ic_wifi_6_signal_0,
            com.android.internal.R.drawable.ic_wifi_6_signal_1,
            com.android.internal.R.drawable.ic_wifi_6_signal_2,
            com.android.internal.R.drawable.ic_wifi_6_signal_3,
            com.android.internal.R.drawable.ic_wifi_6_signal_4
    };

    public static String buildLoggingSummary(AccessPoint accessPoint, WifiConfiguration config) {
        final StringBuilder summary = new StringBuilder();
        final WifiInfo info = accessPoint.getInfo();
        // Add RSSI/band information for this config, what was seen up to 6 seconds ago
        // verbose WiFi Logging is only turned on thru developers settings
        if (accessPoint.isActive() && info != null) {
            summary.append(" f=" + Integer.toString(info.getFrequency()));
        }
        summary.append(" " + getVisibilityStatus(accessPoint));
        if (config != null
                && (config.getNetworkSelectionStatus().getNetworkSelectionStatus()
                        != NETWORK_SELECTION_ENABLED)) {
            summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
            if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
                long now = System.currentTimeMillis();
                long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
                long sec = diff % 60; //seconds
                long min = (diff / 60) % 60; //minutes
                long hour = (min / 60) % 60; //hours
                summary.append(", ");
                if (hour > 0) summary.append(Long.toString(hour) + "h ");
                summary.append(Long.toString(min) + "m ");
                summary.append(Long.toString(sec) + "s ");
            }
            summary.append(")");
        }

        if (config != null) {
            NetworkSelectionStatus networkStatus = config.getNetworkSelectionStatus();
            for (int reason = 0; reason <= getMaxNetworkSelectionDisableReason(); reason++) {
                if (networkStatus.getDisableReasonCounter(reason) != 0) {
                    summary.append(" ")
                            .append(NetworkSelectionStatus
                                    .getNetworkSelectionDisableReasonString(reason))
                            .append("=")
                            .append(networkStatus.getDisableReasonCounter(reason));
                }
            }
        }

        return summary.toString();
    }

    /**
     * Returns the visibility status of the WifiConfiguration.
     *
     * @return autojoin debugging information
     * TODO: use a string formatter
     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
     * For instance [-40,5/-30,2]
     */
    @VisibleForTesting
    static String getVisibilityStatus(AccessPoint accessPoint) {
        final WifiInfo info = accessPoint.getInfo();
        StringBuilder visibility = new StringBuilder();
        StringBuilder scans24GHz = new StringBuilder();
        StringBuilder scans5GHz = new StringBuilder();
        StringBuilder scans60GHz = new StringBuilder();
        StringBuilder scans6GHz = new StringBuilder();
        String bssid = null;

        if (accessPoint.isActive() && info != null) {
            bssid = info.getBSSID();
            if (bssid != null) {
                visibility.append(" ").append(bssid);
            }
            visibility.append(" standard = ").append(info.getWifiStandard());
            visibility.append(" rssi=").append(info.getRssi());
            visibility.append(" ");
            visibility.append(" score=").append(info.getScore());
            if (accessPoint.getSpeed() != AccessPoint.Speed.NONE) {
                visibility.append(" speed=").append(accessPoint.getSpeedLabel());
            }
            visibility.append(String.format(" tx=%.1f,", info.getSuccessfulTxPacketsPerSecond()));
            visibility.append(String.format("%.1f,", info.getRetriedTxPacketsPerSecond()));
            visibility.append(String.format("%.1f ", info.getLostTxPacketsPerSecond()));
            visibility.append(String.format("rx=%.1f", info.getSuccessfulRxPacketsPerSecond()));
        }

        int maxRssi6 = INVALID_RSSI;
        int maxRssi5 = INVALID_RSSI;
        int maxRssi24 = INVALID_RSSI;
        int maxRssi60 = INVALID_RSSI;
        final int maxDisplayedScans = 4;
        int num6 = 0; // number of scanned BSSID on 6GHz band
        int num5 = 0; // number of scanned BSSID on 5GHz band
        int num24 = 0; // number of scanned BSSID on 2.4Ghz band
        int num60 = 0; // number of scanned BSSID on 60Ghz band
        int numBlockListed = 0;

        // TODO: sort list by RSSI or age
        long nowMs = SystemClock.elapsedRealtime();
        for (ScanResult result : accessPoint.getScanResults()) {
            if (result == null) {
                continue;
            }
            if (result.frequency >= AccessPoint.LOWER_FREQ_6GHZ
                    && result.frequency <= AccessPoint.HIGHER_FREQ_6GHZ) {
                num6++;

                if (result.level > maxRssi6) {
                    maxRssi6 = result.level;
                }
                if (num6 <= maxDisplayedScans) {
                    scans6GHz.append(
                            verboseScanResultSummary(accessPoint, result, bssid,
                                    nowMs));
                }
            } else if (result.frequency >= AccessPoint.LOWER_FREQ_5GHZ
                    && result.frequency <= AccessPoint.HIGHER_FREQ_5GHZ) {
                // Strictly speaking: [4915, 5825]
                num5++;

                if (result.level > maxRssi5) {
                    maxRssi5 = result.level;
                }
                if (num5 <= maxDisplayedScans) {
                    scans5GHz.append(
                            verboseScanResultSummary(accessPoint, result, bssid,
                                    nowMs));
                }
            } else if (result.frequency >= AccessPoint.LOWER_FREQ_24GHZ
                    && result.frequency <= AccessPoint.HIGHER_FREQ_24GHZ) {
                // Strictly speaking: [2412, 2482]
                num24++;

                if (result.level > maxRssi24) {
                    maxRssi24 = result.level;
                }
                if (num24 <= maxDisplayedScans) {
                    scans24GHz.append(
                            verboseScanResultSummary(accessPoint, result, bssid,
                                    nowMs));
                }
            } else if (result.frequency >= AccessPoint.LOWER_FREQ_60GHZ
                    && result.frequency <= AccessPoint.HIGHER_FREQ_60GHZ) {
                // Strictly speaking: [60000, 61000]
                num60++;

                if (result.level > maxRssi60) {
                    maxRssi60 = result.level;
                }
                if (num60 <= maxDisplayedScans) {
                    scans60GHz.append(
                            verboseScanResultSummary(accessPoint, result, bssid,
                                    nowMs));
                }
            }
        }
        visibility.append(" [");
        if (num24 > 0) {
            visibility.append("(").append(num24).append(")");
            if (num24 > maxDisplayedScans) {
                visibility.append("max=").append(maxRssi24).append(",");
            }
            visibility.append(scans24GHz.toString());
        }
        visibility.append(";");
        if (num5 > 0) {
            visibility.append("(").append(num5).append(")");
            if (num5 > maxDisplayedScans) {
                visibility.append("max=").append(maxRssi5).append(",");
            }
            visibility.append(scans5GHz.toString());
        }
        visibility.append(";");
        if (num60 > 0) {
            visibility.append("(").append(num60).append(")");
            if (num60 > maxDisplayedScans) {
                visibility.append("max=").append(maxRssi60).append(",");
            }
            visibility.append(scans60GHz.toString());
        }
        visibility.append(";");
        if (num6 > 0) {
            visibility.append("(").append(num6).append(")");
            if (num6 > maxDisplayedScans) {
                visibility.append("max=").append(maxRssi6).append(",");
            }
            visibility.append(scans6GHz.toString());
        }
        if (numBlockListed > 0) {
            visibility.append("!").append(numBlockListed);
        }
        visibility.append("]");

        return visibility.toString();
    }

    @VisibleForTesting
    /* package */ static String verboseScanResultSummary(AccessPoint accessPoint, ScanResult result,
            String bssid, long nowMs) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" \n{").append(result.BSSID);
        if (result.BSSID.equals(bssid)) {
            stringBuilder.append("*");
        }
        stringBuilder.append("=").append(result.frequency);
        stringBuilder.append(",").append(result.level);
        int speed = getSpecificApSpeed(result, accessPoint.getScoredNetworkCache());
        if (speed != AccessPoint.Speed.NONE) {
            stringBuilder.append(",")
                    .append(accessPoint.getSpeedLabel(speed));
        }
        int ageSeconds = (int) (nowMs - result.timestamp / 1000) / 1000;
        stringBuilder.append(",").append(ageSeconds).append("s");
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

    @AccessPoint.Speed
    private static int getSpecificApSpeed(ScanResult result,
            Map<String, TimestampedScoredNetwork> scoredNetworkCache) {
        TimestampedScoredNetwork timedScore = scoredNetworkCache.get(result.BSSID);
        if (timedScore == null) {
            return AccessPoint.Speed.NONE;
        }
        // For debugging purposes we may want to use mRssi rather than result.level as the average
        // speed wil be determined by mRssi
        return timedScore.getScore().calculateBadge(result.level);
    }

    public static String getMeteredLabel(Context context, WifiConfiguration config) {
        // meteredOverride is whether the user manually set the metered setting or not.
        // meteredHint is whether the network itself is telling us that it is metered
        if (config.meteredOverride == WifiConfiguration.METERED_OVERRIDE_METERED
                || (config.meteredHint && !isMeteredOverridden(config))) {
            return context.getString(R.string.wifi_metered_label);
        }
        return context.getString(R.string.wifi_unmetered_label);
    }

    /**
     * Returns the Internet icon resource for a given RSSI level.
     *
     * @param level The number of bars to show (0-4)
     * @param noInternet True if a connected Wi-Fi network cannot access the Internet
     * @throws IllegalArgumentException if an invalid RSSI level is given.
     */
    public static int getInternetIconResource(int level, boolean noInternet) {
        return getInternetIconResource(level, noInternet, 0 /* standard */, false /* isReady */);
    }

    /**
     * Returns the Internet icon resource for a given RSSI level.
     *
     * @param level The number of bars to show (0-4)
     * @param noInternet True if a connected Wi-Fi network cannot access the Internet
     * @throws IllegalArgumentException if an invalid RSSI level is given.
     */
    public static int getInternetIconResource(int level, boolean noInternet, int standard, boolean isReady) {
        if (level < 0 || level >= WIFI_PIE.length) {
            throw new IllegalArgumentException("No Wifi icon found for level: " + level);
        }
        if (noInternet) return NO_INTERNET_WIFI_PIE[level];
        switch (standard) {
            case 4:
                return WIFI_4_PIE[level];
            case 5:
                if (isReady) {
                    return WIFI_6_PIE[level];
                } else {
                    return WIFI_5_PIE[level];
                }
            case 6:
                return WIFI_6_PIE[level];
            default:
                return WIFI_PIE[level];
       }
    }

    /**
     * Wrapper the {@link #getInternetIconResource} for testing compatibility.
     */
    public static class InternetIconInjector {

        protected final Context mContext;

        public InternetIconInjector(Context context) {
            mContext = context;
        }

        /**
         * Returns the Internet icon for a given RSSI level.
         *
         * @param noInternet True if a connected Wi-Fi network cannot access the Internet
         * @param level The number of bars to show (0-4)
         */
        public Drawable getIcon(boolean noInternet, int level) {
            return mContext.getDrawable(WifiUtils.getInternetIconResource(level, noInternet));
        }
    }

    public static boolean isMeteredOverridden(WifiConfiguration config) {
        return config.meteredOverride != WifiConfiguration.METERED_OVERRIDE_NONE;
    }

    /**
     * Returns the Intent for Wi-Fi network details settings.
     *
     * @param key The Wi-Fi entry key
     */
    public static Intent getWifiDetailsSettingsIntent(String key) {
        final Intent intent = new Intent(ACTION_WIFI_DETAILS_SETTINGS);
        final Bundle bundle = new Bundle();
        bundle.putString(KEY_CHOSEN_WIFIENTRY_KEY, key);
        intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, bundle);
        return intent;
    }
}