summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/WakeupController.java
blob: 1b5ccd3e3ceca3a264803ae8300ce1e64e34c041 (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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
 * Copyright 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.server.wifi;

import static com.android.server.wifi.WifiController.CMD_WIFI_TOGGLED;

import android.content.Context;
import android.database.ContentObserver;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiNetworkSuggestion;
import android.net.wifi.WifiScanner;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.provider.Settings;
import android.util.Log;

import com.android.internal.annotations.VisibleForTesting;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * WakeupController is responsible managing Auto Wifi.
 *
 * <p>It determines if and when to re-enable wifi after it has been turned off by the user.
 */
public class WakeupController {

    private static final String TAG = "WakeupController";

    private static final boolean USE_PLATFORM_WIFI_WAKE = true;

    private final Context mContext;
    private final Handler mHandler;
    private final FrameworkFacade mFrameworkFacade;
    private final ContentObserver mContentObserver;
    private final WakeupLock mWakeupLock;
    private final WakeupEvaluator mWakeupEvaluator;
    private final WakeupOnboarding mWakeupOnboarding;
    private final WifiConfigManager mWifiConfigManager;
    private final WifiNetworkSuggestionsManager mWifiNetworkSuggestionsManager;
    private final WifiInjector mWifiInjector;
    private final WakeupConfigStoreData mWakeupConfigStoreData;
    private final WifiWakeMetrics mWifiWakeMetrics;
    private final Clock mClock;

    private final WifiScanner.ScanListener mScanListener = new WifiScanner.ScanListener() {
        @Override
        public void onPeriodChanged(int periodInMs) {
            // no-op
        }

        @Override
        public void onResults(WifiScanner.ScanData[] results) {
            // We treat any full band scans (with DFS or not) as "full".
            boolean isFullBandScanResults =
                    results[0].getBandScanned() == WifiScanner.WIFI_BAND_BOTH_WITH_DFS
                            || results[0].getBandScanned() == WifiScanner.WIFI_BAND_BOTH;
            if (results.length == 1 && isFullBandScanResults) {
                handleScanResults(filterDfsScanResults(Arrays.asList(results[0].getResults())));
            }
        }

        @Override
        public void onFullResult(ScanResult fullScanResult) {
            // no-op
        }

        @Override
        public void onSuccess() {
            // no-op
        }

        @Override
        public void onFailure(int reason, String description) {
            Log.e(TAG, "ScanListener onFailure: " + reason + ": " + description);
        }
    };

    /** Whether this feature is enabled in Settings. */
    private boolean mWifiWakeupEnabled;

    /** Whether the WakeupController is currently active. */
    private boolean mIsActive = false;

    /** The number of scans that have been handled by the controller since last {@link #reset()}. */
    private int mNumScansHandled = 0;

    /** Whether Wifi verbose logging is enabled. */
    private boolean mVerboseLoggingEnabled;

    /**
     * The timestamp of when the Wifi network was last disconnected (either device disconnected
     * from the network or Wifi was turned off entirely).
     * Note: mLastDisconnectTimestampMillis and mLastDisconnectInfo must always be updated together.
     */
    private long mLastDisconnectTimestampMillis;

    /**
     * The SSID of the last Wifi network the device was connected to (either device disconnected
     * from the network or Wifi was turned off entirely).
     * Note: mLastDisconnectTimestampMillis and mLastDisconnectInfo must always be updated together.
     */
    private ScanResultMatchInfo mLastDisconnectInfo;

    public WakeupController(
            Context context,
            Looper looper,
            WakeupLock wakeupLock,
            WakeupEvaluator wakeupEvaluator,
            WakeupOnboarding wakeupOnboarding,
            WifiConfigManager wifiConfigManager,
            WifiConfigStore wifiConfigStore,
            WifiNetworkSuggestionsManager wifiNetworkSuggestionsManager,
            WifiWakeMetrics wifiWakeMetrics,
            WifiInjector wifiInjector,
            FrameworkFacade frameworkFacade,
            Clock clock) {
        mContext = context;
        mHandler = new Handler(looper);
        mWakeupLock = wakeupLock;
        mWakeupEvaluator = wakeupEvaluator;
        mWakeupOnboarding = wakeupOnboarding;
        mWifiConfigManager = wifiConfigManager;
        mWifiNetworkSuggestionsManager = wifiNetworkSuggestionsManager;
        mWifiWakeMetrics = wifiWakeMetrics;
        mFrameworkFacade = frameworkFacade;
        mWifiInjector = wifiInjector;
        mContentObserver = new ContentObserver(mHandler) {
            @Override
            public void onChange(boolean selfChange) {
                readWifiWakeupEnabledFromSettings();
                mWakeupOnboarding.setOnboarded();
            }
        };
        mFrameworkFacade.registerContentObserver(mContext, Settings.Global.getUriFor(
                Settings.Global.WIFI_WAKEUP_ENABLED), true, mContentObserver);
        readWifiWakeupEnabledFromSettings();

        // registering the store data here has the effect of reading the persisted value of the
        // data sources after system boot finishes
        mWakeupConfigStoreData = new WakeupConfigStoreData(
                new IsActiveDataSource(),
                mWakeupOnboarding.getIsOnboadedDataSource(),
                mWakeupOnboarding.getNotificationsDataSource(),
                mWakeupLock.getDataSource());
        wifiConfigStore.registerStoreData(mWakeupConfigStoreData);
        mClock = clock;
        mLastDisconnectTimestampMillis = 0;
        mLastDisconnectInfo = null;
    }

    private void readWifiWakeupEnabledFromSettings() {
        mWifiWakeupEnabled = mFrameworkFacade.getIntegerSetting(
                mContext, Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1;
        Log.d(TAG, "WifiWake " + (mWifiWakeupEnabled ? "enabled" : "disabled"));
    }

    private void setActive(boolean isActive) {
        if (mIsActive != isActive) {
            Log.d(TAG, "Setting active to " + isActive);
            mIsActive = isActive;
            mWifiConfigManager.saveToStore(false /* forceWrite */);
        }
    }

    /**
     * Saves the SSID of the last Wifi network that was disconnected. Should only be called before
     * WakeupController is active.
     */
    public void setLastDisconnectInfo(ScanResultMatchInfo scanResultMatchInfo) {
        if (mIsActive) {
            Log.e(TAG, "Unexpected setLastDisconnectInfo when WakeupController is active!");
            return;
        }
        if (scanResultMatchInfo == null) {
            Log.e(TAG, "Unexpected setLastDisconnectInfo(null)");
            return;
        }
        mLastDisconnectTimestampMillis = mClock.getElapsedSinceBootMillis();
        mLastDisconnectInfo = scanResultMatchInfo;
        if (mVerboseLoggingEnabled) {
            Log.d(TAG, "mLastDisconnectInfo set to " + scanResultMatchInfo);
        }
    }

    /**
     * If Wifi was disabled within LAST_DISCONNECT_TIMEOUT_MILLIS of losing a Wifi connection,
     * add that Wifi connection to the Wakeup Lock as if Wifi was disabled while connected to that
     * connection.
     * Often times, networks with poor signal intermittently connect and disconnect, causing the
     * user to manually turn off Wifi. If the Wifi was turned off during the disconnected phase of
     * the intermittent connection, then that connection normally would not be added to the Wakeup
     * Lock. This constant defines the timeout after disconnecting, in milliseconds, within which
     * if Wifi was disabled, the network would still be added to the wakeup lock.
     */
    @VisibleForTesting
    static final long LAST_DISCONNECT_TIMEOUT_MILLIS = 5 * 1000;

    /**
     * Starts listening for incoming scans.
     *
     * <p>Should only be called upon entering ScanMode. WakeupController registers its listener with
     * the WifiScanner. If the WakeupController is already active, then it returns early. Otherwise
     * it performs its initialization steps and sets {@link #mIsActive} to true.
     */
    public void start() {
        Log.d(TAG, "start()");
        mWifiInjector.getWifiScanner().registerScanListener(mScanListener);

        // If already active, we don't want to restart the session, so return early.
        if (mIsActive) {
            mWifiWakeMetrics.recordIgnoredStart();
            return;
        }
        setActive(true);

        // ensure feature is enabled and store data has been read before performing work
        if (isEnabled()) {
            mWakeupOnboarding.maybeShowNotification();

            List<ScanResult> scanResults =
                    filterDfsScanResults(mWifiInjector.getWifiScanner().getSingleScanResults());
            Set<ScanResultMatchInfo> matchInfos = toMatchInfos(scanResults);
            matchInfos.retainAll(getGoodSavedNetworksAndSuggestions());

            // ensure that the last disconnected network is added to the wakeup lock, since we don't
            // want to automatically reconnect to the same network that the user manually
            // disconnected from
            long now = mClock.getElapsedSinceBootMillis();
            if (mLastDisconnectInfo != null && ((now - mLastDisconnectTimestampMillis)
                    <= LAST_DISCONNECT_TIMEOUT_MILLIS)) {
                matchInfos.add(mLastDisconnectInfo);
                if (mVerboseLoggingEnabled) {
                    Log.d(TAG, "Added last connected network to lock: " + mLastDisconnectInfo);
                }
            }

            if (mVerboseLoggingEnabled) {
                Log.d(TAG, "Saved networks in most recent scan:" + matchInfos);
            }

            mWifiWakeMetrics.recordStartEvent(matchInfos.size());
            mWakeupLock.setLock(matchInfos);
            // TODO(b/77291248): request low latency scan here
        }
    }

    /**
     * Stops listening for scans.
     *
     * <p>Should only be called upon leaving ScanMode. It deregisters the listener from
     * WifiScanner.
     */
    public void stop() {
        Log.d(TAG, "stop()");
        mLastDisconnectTimestampMillis = 0;
        mLastDisconnectInfo = null;
        mWifiInjector.getWifiScanner().deregisterScanListener(mScanListener);
        mWakeupOnboarding.onStop();
    }

    /** Resets the WakeupController, setting {@link #mIsActive} to false. */
    public void reset() {
        Log.d(TAG, "reset()");
        mWifiWakeMetrics.recordResetEvent(mNumScansHandled);
        mNumScansHandled = 0;
        setActive(false);
    }

    /** Sets verbose logging flag based on verbose level. */
    public void enableVerboseLogging(int verbose) {
        mVerboseLoggingEnabled = verbose > 0;
        mWakeupLock.enableVerboseLogging(mVerboseLoggingEnabled);
    }

    /** Returns a list of ScanResults with DFS channels removed. */
    private List<ScanResult> filterDfsScanResults(Collection<ScanResult> scanResults) {
        int[] dfsChannels = mWifiInjector.getWifiNative()
                .getChannelsForBand(WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY);
        if (dfsChannels == null) {
            dfsChannels = new int[0];
        }

        final Set<Integer> dfsChannelSet = Arrays.stream(dfsChannels).boxed()
                .collect(Collectors.toSet());

        return scanResults.stream()
                .filter(scanResult -> !dfsChannelSet.contains(scanResult.frequency))
                .collect(Collectors.toList());
    }

    /** Returns a filtered set of saved networks from WifiConfigManager & suggestions
     * from WifiNetworkSuggestionsManager. */
    private Set<ScanResultMatchInfo> getGoodSavedNetworksAndSuggestions() {
        List<WifiConfiguration> savedNetworks = mWifiConfigManager.getSavedNetworks(
                Process.WIFI_UID);

        Set<ScanResultMatchInfo> goodNetworks = new HashSet<>(savedNetworks.size());
        for (WifiConfiguration config : savedNetworks) {
            if (isWideAreaNetwork(config)
                    || config.hasNoInternetAccess()
                    || config.noInternetAccessExpected
                    || !config.getNetworkSelectionStatus().getHasEverConnected()) {
                continue;
            }
            goodNetworks.add(ScanResultMatchInfo.fromWifiConfiguration(config));
        }

        Set<WifiNetworkSuggestion> networkSuggestions =
                mWifiNetworkSuggestionsManager.getAllNetworkSuggestions();
        for (WifiNetworkSuggestion suggestion : networkSuggestions) {
            // TODO(b/127799111): Do we need to filter the list similar to saved networks above?
            goodNetworks.add(
                    ScanResultMatchInfo.fromWifiConfiguration(suggestion.wifiConfiguration));
        }
        return goodNetworks;
    }

    //TODO(b/69271702) implement WAN filtering
    private static boolean isWideAreaNetwork(WifiConfiguration config) {
        return false;
    }

    /**
     * Handles incoming scan results.
     *
     * <p>The controller updates the WakeupLock with the incoming scan results. If WakeupLock is not
     * yet fully initialized, it adds the current scanResults to the lock and returns. If WakeupLock
     * is initialized but not empty, the controller updates the lock with the current scan. If it is
     * both initialized and empty, it evaluates scan results for a match with saved networks. If a
     * match exists, it enables wifi.
     *
     * <p>The feature must be enabled and the store data must be loaded in order for the controller
     * to handle scan results.
     *
     * @param scanResults The scan results with which to update the controller
     */
    private void handleScanResults(Collection<ScanResult> scanResults) {
        if (!isEnabled()) {
            Log.d(TAG, "Attempted to handleScanResults while not enabled");
            return;
        }

        // only count scan as handled if isEnabled
        mNumScansHandled++;
        if (mVerboseLoggingEnabled) {
            Log.d(TAG, "Incoming scan #" + mNumScansHandled);
        }

        // need to show notification here in case user turns phone on while wifi is off
        mWakeupOnboarding.maybeShowNotification();

        // filter out unknown networks
        Set<ScanResultMatchInfo> goodNetworks = getGoodSavedNetworksAndSuggestions();
        Set<ScanResultMatchInfo> matchInfos = toMatchInfos(scanResults);
        matchInfos.retainAll(goodNetworks);

        mWakeupLock.update(matchInfos);
        if (!mWakeupLock.isUnlocked()) {
            return;
        }

        ScanResult network = mWakeupEvaluator.findViableNetwork(scanResults, goodNetworks);

        if (network != null) {
            Log.d(TAG, "Enabling wifi for network: " + network.SSID);
            enableWifi();
        }
    }

    /**
     * Converts ScanResults to ScanResultMatchInfos.
     */
    private static Set<ScanResultMatchInfo> toMatchInfos(Collection<ScanResult> scanResults) {
        return scanResults.stream()
                .map(ScanResultMatchInfo::fromScanResult)
                .collect(Collectors.toSet());
    }

    /**
     * Enables wifi.
     *
     * <p>This method ignores all checks and assumes that {@link WifiController} is currently
     * in ScanModeState.
     */
    private void enableWifi() {
        if (USE_PLATFORM_WIFI_WAKE) {
            // TODO(b/72180295): ensure that there is no race condition with WifiServiceImpl here
            if (mWifiInjector.getWifiSettingsStore().handleWifiToggled(true /* wifiEnabled */)) {
                mWifiInjector.getWifiController().sendMessage(CMD_WIFI_TOGGLED);
                mWifiWakeMetrics.recordWakeupEvent(mNumScansHandled);
            }
        }
    }

    /**
     * Whether the feature is currently enabled.
     *
     * <p>This method checks both the Settings value and the store data to ensure that it has been
     * read.
     */
    @VisibleForTesting
    boolean isEnabled() {
        return mWifiWakeupEnabled && mWakeupConfigStoreData.hasBeenRead();
    }

    /** Dumps wakeup controller state. */
    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("Dump of WakeupController");
        pw.println("USE_PLATFORM_WIFI_WAKE: " + USE_PLATFORM_WIFI_WAKE);
        pw.println("mWifiWakeupEnabled: " + mWifiWakeupEnabled);
        pw.println("isOnboarded: " + mWakeupOnboarding.isOnboarded());
        pw.println("configStore hasBeenRead: " + mWakeupConfigStoreData.hasBeenRead());
        pw.println("mIsActive: " + mIsActive);
        pw.println("mNumScansHandled: " + mNumScansHandled);

        mWakeupLock.dump(fd, pw, args);
    }

    private class IsActiveDataSource implements WakeupConfigStoreData.DataSource<Boolean> {

        @Override
        public Boolean getData() {
            return mIsActive;
        }

        @Override
        public void setData(Boolean data) {
            mIsActive = data;
        }
    }
}