summaryrefslogtreecommitdiff
path: root/src/com/android/networkrecommendation/wakeup/WifiWakeupController.java
blob: a9aa61fcfebc4c7f9151cc41311f68f696e70377 (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
/*
 * 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.networkrecommendation.wakeup;

import static com.android.networkrecommendation.Constants.TAG;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import com.android.networkrecommendation.config.G;
import com.android.networkrecommendation.config.Preferences;
import com.android.networkrecommendation.config.WideAreaNetworks;
import com.android.networkrecommendation.scoring.util.HashUtil;
import com.android.networkrecommendation.util.Blog;
import com.android.networkrecommendation.util.RoboCompatUtil;
import com.android.networkrecommendation.util.WifiConfigurationUtil;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Handles enabling Wi-Fi for the Wi-Fi Wakeup feature.
 *
 * <p>This class enables Wi-Fi when the user is near a network that would would autojoined if Wi-Fi
 * were enabled. When a user disables Wi-Fi, Wi-Fi Wakeup will not enable Wi-Fi until the user's
 * context has changed. For saved networks, this context change is defined by the user leaving the
 * range of the saved SSIDs that were in range when the user disabled Wi-Fi.
 *
 * @hide
 */
public class WifiWakeupController {
    /** Number of scans to ensure that a previously in range AP is now out of range. */
    private static final int NUM_SCANS_TO_CONFIRM_AP_LOSS = 3;

    private final Context mContext;
    private final ContentResolver mContentResolver;
    private final WifiManager mWifiManager;
    private final PowerManager mPowerManager;
    private final WifiWakeupNetworkSelector mWifiWakeupNetworkSelector;
    private final Handler mHandler;
    private final WifiWakeupHelper mWifiWakeupHelper;
    private final AtomicBoolean mStarted;
    @VisibleForTesting final ContentObserver mContentObserver;

    private final Map<String, WifiConfiguration> mSavedNetworks = new ArrayMap<>();
    private final Set<String> mSavedSsidsInLastScan = new ArraySet<>();
    private final Set<String> mSavedSsids = new ArraySet<>();
    private final Map<String, Integer> mSavedSsidsOnDisable = new ArrayMap<>();
    private final SavedNetworkCounts mSavedNetworkCounts = new SavedNetworkCounts();
    private int mWifiState;
    private int mWifiApState;
    private boolean mWifiWakeupEnabled;
    private boolean mAirplaneModeEnabled;
    private boolean mAutopilotEnabledWifi;
    private boolean mPowerSaverModeOn;

    public WifiWakeupController(
            Context context,
            ContentResolver contentResolver,
            Handler handler,
            WifiManager wifiManager,
            PowerManager powerManager,
            WifiWakeupNetworkSelector wifiWakeupNetworkSelector,
            WifiWakeupHelper wifiWakeupHelper) {
        mContext = context;
        mContentResolver = contentResolver;
        mHandler = handler;
        mWifiWakeupHelper = wifiWakeupHelper;
        mStarted = new AtomicBoolean(false);
        mWifiManager = wifiManager;
        mPowerManager = powerManager;
        mWifiWakeupNetworkSelector = wifiWakeupNetworkSelector;
        mContentObserver =
                new ContentObserver(mHandler) {
                    @Override
                    public void onChange(boolean selfChange) {
                        mWifiWakeupEnabled =
                                Settings.Global.getInt(
                                                mContentResolver,
                                                Settings.Global.WIFI_WAKEUP_ENABLED,
                                                0)
                                        == 1;
                        mAirplaneModeEnabled =
                                Settings.Global.getInt(
                                                mContentResolver,
                                                Settings.Global.AIRPLANE_MODE_ON,
                                                0)
                                        == 1;
                    }
                };
    }

    private final BroadcastReceiver mBroadcastReceiver =
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    try {
                        if (WifiManager.WIFI_AP_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                            handleWifiApStateChanged();
                        } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(
                                intent.getAction())) {
                            handleWifiStateChanged(false);
                        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(
                                intent.getAction())) {
                            handleScanResultsAvailable();
                        } else if (WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(
                                intent.getAction())) {
                            handleConfiguredNetworksChanged();
                        } else if (PowerManager.ACTION_POWER_SAVE_MODE_CHANGED.equals(
                                intent.getAction())) {
                            handlePowerSaverModeChanged();
                        }
                    } catch (RuntimeException re) {
                        // TODO(b/35044022) Remove try/catch after a couple of releases when we are confident
                        // this is not going to throw.
                        Blog.e(TAG, re, "RuntimeException in broadcast receiver.");
                    }
                }
            };

    /** Starts {@link WifiWakeupController}. */
    public void start() {
        if (!mStarted.compareAndSet(false, true)) {
            return;
        }
        Blog.d(TAG, "Starting WifiWakeupController.");

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
        filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        // TODO(b/33695273): conditionally register this receiver based on wifi enabled setting
        mContext.registerReceiver(mBroadcastReceiver, filter, null, mHandler);
        mContentResolver.registerContentObserver(
                Settings.Global.getUriFor(Settings.Global.WIFI_WAKEUP_ENABLED),
                true,
                mContentObserver);
        mContentResolver.registerContentObserver(
                Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON),
                true,
                mContentObserver);
        mContentObserver.onChange(true);
        handlePowerSaverModeChanged();
        handleWifiApStateChanged();
        handleConfiguredNetworksChanged();
        handleWifiStateChanged(true);
        handleScanResultsAvailable();
    }

    /** Stops {@link WifiWakeupController}. */
    public void stop() {
        if (!mStarted.compareAndSet(true, false)) {
            return;
        }
        Blog.d(TAG, "Stopping WifiWakeupController.");
        mContext.unregisterReceiver(mBroadcastReceiver);
        mContentResolver.unregisterContentObserver(mContentObserver);
    }

    private void handlePowerSaverModeChanged() {
        mPowerSaverModeOn = mPowerManager.isPowerSaveMode();
        Blog.v(TAG, "handlePowerSaverModeChanged: %b", mPowerSaverModeOn);
    }

    private void handleWifiApStateChanged() {
        mWifiApState = mWifiManager.getWifiApState();
        Blog.v(TAG, "handleWifiApStateChanged: %d", mWifiApState);
    }

    private void handleConfiguredNetworksChanged() {
        List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks();
        if (wifiConfigurations == null) {
            return;
        }
        Blog.v(TAG, "handleConfiguredNetworksChanged: %d", wifiConfigurations.size());

        mSavedNetworkCounts.clear();
        mSavedNetworkCounts.total = wifiConfigurations.size();
        mSavedNetworks.clear();
        mSavedSsids.clear();
        for (int i = 0; i < wifiConfigurations.size(); i++) {
            WifiConfiguration wifiConfiguration = wifiConfigurations.get(i);
            if (wifiConfiguration.status != WifiConfiguration.Status.ENABLED
                    && wifiConfiguration.status != WifiConfiguration.Status.CURRENT) {
                continue; // Ignore networks that are not connected or enabled.
            }
            mSavedNetworkCounts.enabled++;
            if (RoboCompatUtil.getInstance().hasNoInternetAccess(wifiConfiguration)) {
                mSavedNetworkCounts.noInternetAccess++;
                continue; // Ignore networks that do not have verified internet access.
            }
            if (RoboCompatUtil.getInstance().isNoInternetAccessExpected(wifiConfiguration)) {
                mSavedNetworkCounts.noInternetAccessExpected++;
                continue; // Ignore networks that are expected not to have internet access.
            }
            String ssid = WifiConfigurationUtil.removeDoubleQuotes(wifiConfiguration);
            if (TextUtils.isEmpty(ssid)) {
                continue;
            }
            if (WideAreaNetworks.contains(ssid)) {
                mSavedNetworkCounts.blacklisted++;
                continue; // Ignore wide area networks.
            }
            mSavedNetworks.put(ssid, wifiConfiguration);
            mSavedSsids.add(ssid);

            if (WifiConfigurationUtil.isConfigForOpenNetwork(wifiConfiguration)) {
                mSavedNetworkCounts.open++;
            }
            if (RoboCompatUtil.getInstance().useExternalScores(wifiConfiguration)) {
                mSavedNetworkCounts.useExternalScores++;
            }
        }
        mSavedSsidsInLastScan.retainAll(mSavedSsids);
    }

    private void handleWifiStateChanged(boolean calledOnStart) {
        mWifiState = mWifiManager.getWifiState();
        Blog.v(TAG, "handleWifiStateChanged: %d", mWifiState);

        switch (mWifiState) {
            case WifiManager.WIFI_STATE_ENABLED:
                mSavedSsidsOnDisable.clear();
                if (!mAutopilotEnabledWifi) {}
                break;
            case WifiManager.WIFI_STATE_DISABLED:
                if (calledOnStart) {
                    readDisabledSsidsFromSharedPreferences();
                } else {
                    for (String ssid : mSavedSsidsInLastScan) {
                        mSavedSsidsOnDisable.put(ssid, NUM_SCANS_TO_CONFIRM_AP_LOSS);
                    }
                    writeDisabledSsidsToSharedPreferences();
                }
                Blog.d(TAG, "Disabled ssid set: %s", mSavedSsidsOnDisable);

                mAutopilotEnabledWifi = false;
                break;
            default: // Only handle ENABLED and DISABLED states
        }
    }

    private void readDisabledSsidsFromSharedPreferences() {
        Set<String> ssidsOnDisable = Preferences.savedSsidsOnDisable.get();
        for (String ssid : mSavedSsids) {
            if (ssidsOnDisable.contains(HashUtil.getSsidHash(ssid))) {
                mSavedSsidsOnDisable.put(ssid, NUM_SCANS_TO_CONFIRM_AP_LOSS);
            }
        }
    }

    private void writeDisabledSsidsToSharedPreferences() {
        Set<String> ssids = new ArraySet<>();
        for (String ssid : mSavedSsidsOnDisable.keySet()) {
            ssids.add(HashUtil.getSsidHash(ssid));
        }
        Preferences.savedSsidsOnDisable.put(ssids);
    }

    private void handleScanResultsAvailable() {
        if (!mWifiWakeupEnabled) {
            return;
        }
        List<ScanResult> scanResults = mWifiManager.getScanResults();
        if (scanResults == null) {
            return;
        }
        Blog.v(TAG, "handleScanResultsAvailable: %d", scanResults.size());

        mSavedSsidsInLastScan.clear();
        for (int i = 0; i < scanResults.size(); i++) {
            String ssid = scanResults.get(i).SSID;
            if (mSavedSsids.contains(ssid)) {
                mSavedSsidsInLastScan.add(ssid);
            }
        }

        if (mAirplaneModeEnabled
                || mWifiState != WifiManager.WIFI_STATE_DISABLED
                || mWifiApState != WifiManager.WIFI_AP_STATE_DISABLED
                || mPowerSaverModeOn) {
            return;
        }

        // Update mSavedSsidsOnDisable to remove ssids that the user has moved away from.
        for (Map.Entry<String, Integer> entry : mSavedSsidsOnDisable.entrySet()) {
            if (mSavedSsidsInLastScan.contains(entry.getKey())) {
                mSavedSsidsOnDisable.put(entry.getKey(), NUM_SCANS_TO_CONFIRM_AP_LOSS);
            } else {
                if (entry.getValue() > 1) {
                    mSavedSsidsOnDisable.put(entry.getKey(), entry.getValue() - 1);
                } else {
                    mSavedSsidsOnDisable.remove(entry.getKey());
                }
            }
        }

        if (!mSavedSsidsOnDisable.isEmpty()) {
            Blog.d(
                    TAG,
                    "Scan results contain ssids from the disabled set: %s",
                    mSavedSsidsOnDisable);
            return;
        }

        if (mSavedSsidsInLastScan.isEmpty()) {
            Blog.v(TAG, "Scan results do not contain any saved ssids.");
            return;
        }

        WifiConfiguration selectedNetwork =
                mWifiWakeupNetworkSelector.selectNetwork(mSavedNetworks, scanResults);
        if (selectedNetwork != null) {
            Blog.d(
                    TAG,
                    "Enabling wifi for ssid: %s",
                    Blog.pii(selectedNetwork.SSID, G.Netrec.enableSensitiveLogging.get()));

            mAutopilotEnabledWifi = true;
            mWifiManager.setWifiEnabled(true /* enabled */);
            mWifiWakeupHelper.startWifiSession(selectedNetwork);
        }
    }

    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("mStarted " + mStarted.get());
        pw.println("mWifiWakeupEnabled: " + mWifiWakeupEnabled);
        pw.println("mSavedSsids: " + mSavedSsids);
        pw.println("mSavedSsidsInLastScan: " + mSavedSsidsInLastScan);
        pw.println("mSavedSsidsOnDisable: " + mSavedSsidsOnDisable);
    }

    /** Class to track counts for saved networks for logging. */
    private static class SavedNetworkCounts {
        int total;
        int open;
        int enabled;
        int noInternetAccess;
        int noInternetAccessExpected;
        int useExternalScores;
        int blacklisted;

        void clear() {
            total = 0;
            open = 0;
            enabled = 0;
            noInternetAccess = 0;
            noInternetAccessExpected = 0;
            useExternalScores = 0;
            blacklisted = 0;
        }
    }
}