summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/statusbar/policy/HotspotControllerImpl.java
blob: a4821e0e9299725ab92decc9f62ca8c0793d0d0f (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
/*
 * Copyright (C) 2014 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.systemui.statusbar.policy;

import static android.net.TetheringManager.TETHERING_WIFI;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.TetheringManager;
import android.net.TetheringManager.TetheringRequest;
import android.net.wifi.WifiClient;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.HandlerExecutor;
import android.os.UserManager;
import android.util.Log;

import androidx.annotation.NonNull;

import com.android.internal.util.ConcurrentUtils;
import com.android.systemui.R;
import com.android.systemui.dagger.SysUISingleton;
import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.dump.DumpManager;
import com.android.systemui.settings.UserTracker;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Controller used to retrieve information related to a hotspot.
 */
@SysUISingleton
public class HotspotControllerImpl implements HotspotController, WifiManager.SoftApCallback {

    private static final String TAG = "HotspotController";
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);

    private final ArrayList<Callback> mCallbacks = new ArrayList<>();
    private final TetheringManager mTetheringManager;
    private final WifiManager mWifiManager;
    private final Handler mMainHandler;
    private final Context mContext;
    private final UserTracker mUserTracker;

    private int mHotspotState;
    private volatile int mNumConnectedDevices;
    // Assume tethering is available until told otherwise
    private volatile boolean mIsTetheringSupported = true;
    private final boolean mIsTetheringSupportedConfig;
    private volatile boolean mHasTetherableWifiRegexs = true;
    private boolean mWaitingForTerminalState;

    private TetheringManager.TetheringEventCallback mTetheringCallback =
            new TetheringManager.TetheringEventCallback() {
                @Override
                public void onTetheringSupported(boolean supported) {
                    if (mIsTetheringSupported != supported) {
                        mIsTetheringSupported = supported;
                        fireHotspotAvailabilityChanged();
                    }
                }

                @Override
                public void onTetherableInterfaceRegexpsChanged(
                        TetheringManager.TetheringInterfaceRegexps reg) {
                    final boolean newValue = reg.getTetherableWifiRegexs().size() != 0;
                    if (mHasTetherableWifiRegexs != newValue) {
                        mHasTetherableWifiRegexs = newValue;
                        fireHotspotAvailabilityChanged();
                    }
                }
            };

    /**
     * Controller used to retrieve information related to a hotspot.
     */
    @Inject
    public HotspotControllerImpl(
            Context context,
            UserTracker userTracker,
            @Main Handler mainHandler,
            @Background Handler backgroundHandler,
            DumpManager dumpManager) {
        mContext = context;
        mUserTracker = userTracker;
        mTetheringManager = context.getSystemService(TetheringManager.class);
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mMainHandler = mainHandler;
        mIsTetheringSupportedConfig = context.getResources()
                .getBoolean(R.bool.config_show_wifi_tethering);
        if (mIsTetheringSupportedConfig) {
            mTetheringManager.registerTetheringEventCallback(
                    new HandlerExecutor(backgroundHandler), mTetheringCallback);
        }
        dumpManager.registerDumpable(getClass().getSimpleName(), this);
    }

    /**
     * Whether hotspot is currently supported.
     *
     * This may return {@code true} immediately on creation of the controller, but may be updated
     * later as capabilities are collected from System Server.
     *
     * Callbacks from this controllers will notify if the state changes.
     *
     * @return {@code true} if hotspot is supported (or we haven't been told it's not)
     * @see #addCallback
     */
    @Override
    public boolean isHotspotSupported() {
        return mIsTetheringSupportedConfig && mIsTetheringSupported && mHasTetherableWifiRegexs
                && UserManager.get(mContext).isUserAdmin(mUserTracker.getUserId());
    }

    public void dump(PrintWriter pw, String[] args) {
        pw.println("HotspotController state:");
        pw.print("  available="); pw.println(isHotspotSupported());
        pw.print("  mHotspotState="); pw.println(stateToString(mHotspotState));
        pw.print("  mNumConnectedDevices="); pw.println(mNumConnectedDevices);
        pw.print("  mWaitingForTerminalState="); pw.println(mWaitingForTerminalState);
    }

    private static String stateToString(int hotspotState) {
        switch (hotspotState) {
            case WifiManager.WIFI_AP_STATE_DISABLED:
                return "DISABLED";
            case WifiManager.WIFI_AP_STATE_DISABLING:
                return "DISABLING";
            case WifiManager.WIFI_AP_STATE_ENABLED:
                return "ENABLED";
            case WifiManager.WIFI_AP_STATE_ENABLING:
                return "ENABLING";
            case WifiManager.WIFI_AP_STATE_FAILED:
                return "FAILED";
        }
        return null;
    }

    /**
     * Adds {@code callback} to the controller. The controller will update the callback on state
     * changes. It will immediately trigger the callback added to notify current state.
     */
    @Override
    public void addCallback(@NonNull Callback callback) {
        synchronized (mCallbacks) {
            if (callback == null || mCallbacks.contains(callback)) return;
            if (DEBUG) Log.d(TAG, "addCallback " + callback);
            mCallbacks.add(callback);
            if (mWifiManager != null) {
                if (mCallbacks.size() == 1) {
                    mWifiManager.registerSoftApCallback(new HandlerExecutor(mMainHandler), this);
                } else {
                    // mWifiManager#registerSoftApCallback triggers a call to onNumClientsChanged
                    // on the Main Handler. In order to always update the callback on added, we
                    // make this call when adding callbacks after the first.
                    mMainHandler.post(() ->
                            callback.onHotspotChanged(isHotspotEnabled(), mNumConnectedDevices));
                }
            }
        }
    }

    @Override
    public void removeCallback(@NonNull Callback callback) {
        if (callback == null) return;
        if (DEBUG) Log.d(TAG, "removeCallback " + callback);
        synchronized (mCallbacks) {
            mCallbacks.remove(callback);
            if (mCallbacks.isEmpty() && mWifiManager != null) {
                mWifiManager.unregisterSoftApCallback(this);
            }
        }
    }

    @Override
    public boolean isHotspotEnabled() {
        return mHotspotState == WifiManager.WIFI_AP_STATE_ENABLED;
    }

    @Override
    public boolean isHotspotTransient() {
        return mWaitingForTerminalState || (mHotspotState == WifiManager.WIFI_AP_STATE_ENABLING);
    }

    @Override
    public void setHotspotEnabled(boolean enabled) {
        if (mWaitingForTerminalState) {
            if (DEBUG) Log.d(TAG, "Ignoring setHotspotEnabled; waiting for terminal state.");
            return;
        }
        if (enabled) {
            mWaitingForTerminalState = true;
            if (DEBUG) Log.d(TAG, "Starting tethering");
            mTetheringManager.startTethering(new TetheringRequest.Builder(
                    TETHERING_WIFI).setShouldShowEntitlementUi(false).build(),
                    ConcurrentUtils.DIRECT_EXECUTOR,
                    new TetheringManager.StartTetheringCallback() {
                        @Override
                        public void onTetheringFailed(final int result) {
                            if (DEBUG) Log.d(TAG, "onTetheringFailed");
                            maybeResetSoftApState();
                            fireHotspotChangedCallback();
                        }
                    });
        } else {
            mTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
        }
    }

    @Override
    public int getNumConnectedDevices() {
        return mNumConnectedDevices;
    }

    /**
     * Sends a hotspot changed callback.
     * Be careful when calling over multiple threads, especially if one of them is the main thread
     * (as it can be blocked).
     */
    private void fireHotspotChangedCallback() {
        List<Callback> list;
        synchronized (mCallbacks) {
            list = new ArrayList<>(mCallbacks);
        }
        for (Callback callback : list) {
            callback.onHotspotChanged(isHotspotEnabled(), mNumConnectedDevices);
        }
    }

    /**
     * Sends a hotspot available changed callback.
     */
    private void fireHotspotAvailabilityChanged() {
        List<Callback> list;
        synchronized (mCallbacks) {
            list = new ArrayList<>(mCallbacks);
        }
        for (Callback callback : list) {
            callback.onHotspotAvailabilityChanged(isHotspotSupported());
        }
    }

    @Override
    public void onStateChanged(int state, int failureReason) {
        // Update internal hotspot state for tracking before using any enabled/callback methods.
        mHotspotState = state;

        maybeResetSoftApState();
        if (!isHotspotEnabled()) {
            // Reset num devices if the hotspot is no longer enabled so we don't get ghost
            // counters.
            mNumConnectedDevices = 0;
        }

        fireHotspotChangedCallback();
    }

    private void maybeResetSoftApState() {
        if (!mWaitingForTerminalState) {
            return; // Only reset soft AP state if enabled from this controller.
        }
        switch (mHotspotState) {
            case WifiManager.WIFI_AP_STATE_FAILED:
                // TODO(b/110697252): must be called to reset soft ap state after failure
                mTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
                // Fall through
            case WifiManager.WIFI_AP_STATE_ENABLED:
            case WifiManager.WIFI_AP_STATE_DISABLED:
                mWaitingForTerminalState = false;
                break;
            case WifiManager.WIFI_AP_STATE_ENABLING:
            case WifiManager.WIFI_AP_STATE_DISABLING:
            default:
                break;
        }
    }

    @Override
    public void onConnectedClientsChanged(List<WifiClient> clients) {
        mNumConnectedDevices = clients.size();
        fireHotspotChangedCallback();
    }
}