summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/WifiController.java
blob: 0b0445d92a968ce0ca648659c772ffcd87e06522 (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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/*
 * Copyright (C) 2013 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 android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;

import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;

/**
 * WifiController is the class used to manage wifi state for various operating
 * modes (normal, airplane, wifi hotspot, etc.).
 */
public class WifiController extends StateMachine {
    private static final String TAG = "WifiController";
    private static final boolean DBG = false;
    private Context mContext;
    private boolean mFirstUserSignOnSeen = false;

    /**
     * See {@link Settings.Global#WIFI_REENABLE_DELAY_MS}.  This is the default value if a
     * Settings.Global value is not present.  This is the minimum time after wifi is disabled
     * we'll act on an enable.  Enable requests received before this delay will be deferred.
     */
    private static final long DEFAULT_REENABLE_DELAY_MS = 500;

    // finding that delayed messages can sometimes be delivered earlier than expected
    // probably rounding errors.  add a margin to prevent problems
    private static final long DEFER_MARGIN_MS = 5;

    NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");

    /* References to values tracked in WifiService */
    private final ClientModeImpl mClientModeImpl;
    private final Looper mClientModeImplLooper;
    private final ActiveModeWarden mActiveModeWarden;
    private final WifiSettingsStore mSettingsStore;

    private long mReEnableDelayMillis;

    private FrameworkFacade mFacade;

    private static final int BASE = Protocol.BASE_WIFI_CONTROLLER;

    static final int CMD_EMERGENCY_MODE_CHANGED                 = BASE + 1;
    static final int CMD_SCAN_ALWAYS_MODE_CHANGED               = BASE + 7;
    static final int CMD_WIFI_TOGGLED                           = BASE + 8;
    static final int CMD_AIRPLANE_TOGGLED                       = BASE + 9;
    static final int CMD_SET_AP                                 = BASE + 10;
    static final int CMD_DEFERRED_TOGGLE                        = BASE + 11;
    static final int CMD_AP_START_FAILURE                       = BASE + 13;
    static final int CMD_EMERGENCY_CALL_STATE_CHANGED           = BASE + 14;
    static final int CMD_AP_STOPPED                             = BASE + 15;
    static final int CMD_STA_START_FAILURE                      = BASE + 16;
    // Command used to trigger a wifi stack restart when in active mode
    static final int CMD_RECOVERY_RESTART_WIFI                  = BASE + 17;
    // Internal command used to complete wifi stack restart
    private static final int CMD_RECOVERY_RESTART_WIFI_CONTINUE = BASE + 18;
    // Command to disable wifi when SelfRecovery is throttled or otherwise not doing full recovery
    static final int CMD_RECOVERY_DISABLE_WIFI                  = BASE + 19;
    static final int CMD_STA_STOPPED                            = BASE + 20;
    static final int CMD_SCANNING_STOPPED                       = BASE + 21;

    private DefaultState mDefaultState = new DefaultState();
    private StaEnabledState mStaEnabledState = new StaEnabledState();
    private StaDisabledState mStaDisabledState = new StaDisabledState();
    private StaDisabledWithScanState mStaDisabledWithScanState = new StaDisabledWithScanState();
    private EcmState mEcmState = new EcmState();

    private ScanOnlyModeManager.Listener mScanOnlyModeCallback = new ScanOnlyCallback();
    private ClientModeManager.Listener mClientModeCallback = new ClientModeCallback();

    WifiController(Context context, ClientModeImpl clientModeImpl, Looper clientModeImplLooper,
                   WifiSettingsStore wss, Looper wifiServiceLooper, FrameworkFacade f,
                   ActiveModeWarden amw) {
        super(TAG, wifiServiceLooper);
        mFacade = f;
        mContext = context;
        mClientModeImpl = clientModeImpl;
        mClientModeImplLooper = clientModeImplLooper;
        mActiveModeWarden = amw;
        mSettingsStore = wss;

        // CHECKSTYLE:OFF IndentationCheck
        addState(mDefaultState);
            addState(mStaDisabledState, mDefaultState);
            addState(mStaEnabledState, mDefaultState);
            addState(mStaDisabledWithScanState, mDefaultState);
            addState(mEcmState, mDefaultState);
        // CHECKSTYLE:ON IndentationCheck

        boolean isAirplaneModeOn = mSettingsStore.isAirplaneModeOn();
        boolean isWifiEnabled = mSettingsStore.isWifiToggleEnabled();
        boolean isScanningAlwaysAvailable = mSettingsStore.isScanAlwaysAvailable();
        boolean isLocationModeActive =
                mSettingsStore.getLocationModeSetting(mContext)
                        == Settings.Secure.LOCATION_MODE_OFF;

        log("isAirplaneModeOn = " + isAirplaneModeOn
                + ", isWifiEnabled = " + isWifiEnabled
                + ", isScanningAvailable = " + isScanningAlwaysAvailable
                + ", isLocationModeActive = " + isLocationModeActive);

        if (checkScanOnlyModeAvailable()) {
            setInitialState(mStaDisabledWithScanState);
        } else {
            setInitialState(mStaDisabledState);
        }

        setLogRecSize(100);
        setLogOnlyTransitions(false);

        // register for state updates via callbacks (vs the intents registered below)
        mActiveModeWarden.registerScanOnlyCallback(mScanOnlyModeCallback);
        mActiveModeWarden.registerClientModeCallback(mClientModeCallback);

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(LocationManager.MODE_CHANGED_ACTION);
        mContext.registerReceiver(
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();
                        if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                            mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
                                    WifiManager.EXTRA_NETWORK_INFO);
                        } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
                            int state = intent.getIntExtra(
                                    WifiManager.EXTRA_WIFI_AP_STATE,
                                    WifiManager.WIFI_AP_STATE_FAILED);
                            if (state == WifiManager.WIFI_AP_STATE_FAILED) {
                                Log.e(TAG, "SoftAP start failed");
                                sendMessage(CMD_AP_START_FAILURE);
                            } else if (state == WifiManager.WIFI_AP_STATE_DISABLED) {
                                sendMessage(CMD_AP_STOPPED);
                            }
                        } else if (action.equals(LocationManager.MODE_CHANGED_ACTION)) {
                            // Location mode has been toggled...  trigger with the scan change
                            // update to make sure we are in the correct mode
                            sendMessage(CMD_SCAN_ALWAYS_MODE_CHANGED);
                        }
                    }
                },
                new IntentFilter(filter));

        readWifiReEnableDelay();
    }

    private boolean checkScanOnlyModeAvailable() {
        // first check if Location service is disabled, if so return false
        if (mSettingsStore.getLocationModeSetting(mContext)
                == Settings.Secure.LOCATION_MODE_OFF) {
            return false;
        }
        return mSettingsStore.isScanAlwaysAvailable();
    }

    /**
     * Listener used to receive scan mode updates - really needed for disabled updates to trigger
     * mode changes.
     */
    private class ScanOnlyCallback implements ScanOnlyModeManager.Listener {
        @Override
        public void onStateChanged(int state) {
            if (state == WifiManager.WIFI_STATE_UNKNOWN) {
                Log.d(TAG, "ScanOnlyMode unexpected failure: state unknown");
            } else if (state == WifiManager.WIFI_STATE_DISABLED) {
                Log.d(TAG, "ScanOnlyMode stopped");
                sendMessage(CMD_SCANNING_STOPPED);
            } else if (state == WifiManager.WIFI_STATE_ENABLED) {
                // scan mode is ready to go
                Log.d(TAG, "scan mode active");
            } else {
                Log.d(TAG, "unexpected state update: " + state);
            }
        }
    }

    /**
     * Listener used to receive client mode updates
     */
    private class ClientModeCallback implements ClientModeManager.Listener {
        @Override
        public void onStateChanged(int state) {
            if (state == WifiManager.WIFI_STATE_UNKNOWN) {
                logd("ClientMode unexpected failure: state unknown");
                sendMessage(CMD_STA_START_FAILURE);
            } else if (state == WifiManager.WIFI_STATE_DISABLED) {
                logd("ClientMode stopped");
                sendMessage(CMD_STA_STOPPED);
            } else if (state == WifiManager.WIFI_STATE_ENABLED) {
                // scan mode is ready to go
                logd("client mode active");
            } else {
                logd("unexpected state update: " + state);
            }
        }
    }

    private void readWifiReEnableDelay() {
        mReEnableDelayMillis = mFacade.getLongSetting(mContext,
                Settings.Global.WIFI_REENABLE_DELAY_MS, DEFAULT_REENABLE_DELAY_MS);
    }

    class DefaultState extends State {
        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case CMD_SCAN_ALWAYS_MODE_CHANGED:
                case CMD_WIFI_TOGGLED:
                case CMD_AP_START_FAILURE:
                case CMD_SCANNING_STOPPED:
                case CMD_STA_STOPPED:
                case CMD_STA_START_FAILURE:
                case CMD_RECOVERY_RESTART_WIFI_CONTINUE:
                    break;
                case CMD_RECOVERY_DISABLE_WIFI:
                    log("Recovery has been throttled, disable wifi");
                    mActiveModeWarden.shutdownWifi();
                    transitionTo(mStaDisabledState);
                    break;
                case CMD_RECOVERY_RESTART_WIFI:
                    deferMessage(obtainMessage(CMD_RECOVERY_RESTART_WIFI_CONTINUE));
                    mActiveModeWarden.shutdownWifi();
                    transitionTo(mStaDisabledState);
                    break;
                case CMD_DEFERRED_TOGGLE:
                    log("DEFERRED_TOGGLE ignored due to state change");
                    break;
                case CMD_SET_AP:
                    // note: CMD_SET_AP is handled/dropped in ECM mode - will not start here
                    if (msg.arg1 == 1) {
                        SoftApModeConfiguration config = (SoftApModeConfiguration) msg.obj;
                        mActiveModeWarden.enterSoftAPMode((SoftApModeConfiguration) msg.obj);
                    } else {
                        mActiveModeWarden.stopSoftAPMode();
                    }
                    break;
                case CMD_AIRPLANE_TOGGLED:
                    if (mSettingsStore.isAirplaneModeOn()) {
                        log("Airplane mode toggled, shutdown all modes");
                        mActiveModeWarden.shutdownWifi();
                        transitionTo(mStaDisabledState);
                    } else {
                        log("Airplane mode disabled, determine next state");
                        if (mSettingsStore.isWifiToggleEnabled()) {
                            transitionTo(mStaEnabledState);
                        } else if (checkScanOnlyModeAvailable()) {
                            transitionTo(mStaDisabledWithScanState);
                        }
                        // wifi should remain disabled, do not need to transition
                    }
                    break;
                case CMD_EMERGENCY_CALL_STATE_CHANGED:
                case CMD_EMERGENCY_MODE_CHANGED:
                    if (msg.arg1 == 1) {
                        transitionTo(mEcmState);
                    }
                    break;
                case CMD_AP_STOPPED:
                    log("SoftAp mode disabled, determine next state");
                    if (mSettingsStore.isWifiToggleEnabled()) {
                        transitionTo(mStaEnabledState);
                    } else if (checkScanOnlyModeAvailable()) {
                        transitionTo(mStaDisabledWithScanState);
                    }
                    // wifi should remain disabled, do not need to transition
                    break;
                default:
                    throw new RuntimeException("WifiController.handleMessage " + msg.what);
            }
            return HANDLED;
        }

    }

    class StaDisabledState extends State {
        private int mDeferredEnableSerialNumber = 0;
        private boolean mHaveDeferredEnable = false;
        private long mDisabledTimestamp;

        @Override
        public void enter() {
            mActiveModeWarden.disableWifi();
            // Supplicant can't restart right away, so note the time we switched off
            mDisabledTimestamp = SystemClock.elapsedRealtime();
            mDeferredEnableSerialNumber++;
            mHaveDeferredEnable = false;
        }
        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case CMD_WIFI_TOGGLED:
                    if (mSettingsStore.isWifiToggleEnabled()) {
                        if (doDeferEnable(msg)) {
                            if (mHaveDeferredEnable) {
                                //  have 2 toggles now, inc serial number and ignore both
                                mDeferredEnableSerialNumber++;
                            }
                            mHaveDeferredEnable = !mHaveDeferredEnable;
                            break;
                        }
                        transitionTo(mStaEnabledState);
                    } else if (checkScanOnlyModeAvailable()) {
                        // only go to scan mode if we aren't in airplane mode
                        if (mSettingsStore.isAirplaneModeOn()) {
                            transitionTo(mStaDisabledWithScanState);
                        }
                    }
                    break;
                case CMD_SCAN_ALWAYS_MODE_CHANGED:
                    if (checkScanOnlyModeAvailable()) {
                        transitionTo(mStaDisabledWithScanState);
                        break;
                    }
                    break;
                case CMD_SET_AP:
                    if (msg.arg1 == 1) {
                        // remember that we were disabled, but pass the command up to start softap
                        mSettingsStore.setWifiSavedState(WifiSettingsStore.WIFI_DISABLED);
                    }
                    return NOT_HANDLED;
                case CMD_DEFERRED_TOGGLE:
                    if (msg.arg1 != mDeferredEnableSerialNumber) {
                        log("DEFERRED_TOGGLE ignored due to serial mismatch");
                        break;
                    }
                    log("DEFERRED_TOGGLE handled");
                    sendMessage((Message)(msg.obj));
                    break;
                case CMD_RECOVERY_RESTART_WIFI_CONTINUE:
                    if (mSettingsStore.isWifiToggleEnabled()) {
                        // wifi is currently disabled but the toggle is on, must have had an
                        // interface down before the recovery triggered
                        transitionTo(mStaEnabledState);
                        break;
                    } else if (checkScanOnlyModeAvailable()) {
                        transitionTo(mStaDisabledWithScanState);
                        break;
                    }
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }

        private boolean doDeferEnable(Message msg) {
            long delaySoFar = SystemClock.elapsedRealtime() - mDisabledTimestamp;
            if (delaySoFar >= mReEnableDelayMillis) {
                return false;
            }

            log("WifiController msg " + msg + " deferred for " +
                    (mReEnableDelayMillis - delaySoFar) + "ms");

            // need to defer this action.
            Message deferredMsg = obtainMessage(CMD_DEFERRED_TOGGLE);
            deferredMsg.obj = Message.obtain(msg);
            deferredMsg.arg1 = ++mDeferredEnableSerialNumber;
            sendMessageDelayed(deferredMsg, mReEnableDelayMillis - delaySoFar + DEFER_MARGIN_MS);
            return true;
        }

    }

    class StaEnabledState extends State {
        @Override
        public void enter() {
            log("StaEnabledState.enter()");
            mActiveModeWarden.enterClientMode();
        }

        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case CMD_WIFI_TOGGLED:
                    if (! mSettingsStore.isWifiToggleEnabled()) {
                        if (checkScanOnlyModeAvailable()) {
                            transitionTo(mStaDisabledWithScanState);
                        } else {
                            transitionTo(mStaDisabledState);
                        }
                    }
                    break;
                case CMD_AIRPLANE_TOGGLED:
                    // airplane mode toggled on is handled in the default state
                    if (mSettingsStore.isAirplaneModeOn()) {
                        return NOT_HANDLED;
                    } else {
                        // when airplane mode is toggled off, but wifi is on, we can keep it on
                        log("airplane mode toggled - and airplane mode is off.  return handled");
                        return HANDLED;
                    }
                case CMD_STA_START_FAILURE:
                    if (!checkScanOnlyModeAvailable()) {
                        transitionTo(mStaDisabledState);
                    } else {
                        transitionTo(mStaDisabledWithScanState);
                    }
                    break;
                case CMD_SET_AP:
                    if (msg.arg1 == 1) {
                        // remember that we were enabled, but pass the command up to start softap
                        mSettingsStore.setWifiSavedState(WifiSettingsStore.WIFI_ENABLED);
                    }
                    return NOT_HANDLED;
                case CMD_AP_START_FAILURE:
                case CMD_AP_STOPPED:
                    // already in a wifi mode, no need to check where we should go with softap
                    // stopped
                    break;
                case CMD_STA_STOPPED:
                    // Client mode stopped.  head to Disabled to wait for next command
                    transitionTo(mStaDisabledState);
                    break;
                case CMD_RECOVERY_RESTART_WIFI:
                    final String bugTitle;
                    final String bugDetail;
                    if (msg.arg1 < SelfRecovery.REASON_STRINGS.length && msg.arg1 >= 0) {
                        bugDetail = SelfRecovery.REASON_STRINGS[msg.arg1];
                        bugTitle = "Wi-Fi BugReport: " + bugDetail;
                    } else {
                        bugDetail = "";
                        bugTitle = "Wi-Fi BugReport";
                    }
                    if (msg.arg1 != SelfRecovery.REASON_LAST_RESORT_WATCHDOG) {
                        (new Handler(mClientModeImplLooper)).post(() -> {
                            mClientModeImpl.takeBugReport(bugTitle, bugDetail);
                        });
                    }
                    // after the bug report trigger, more handling needs to be done
                    return NOT_HANDLED;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class StaDisabledWithScanState extends State {
        private int mDeferredEnableSerialNumber = 0;
        private boolean mHaveDeferredEnable = false;
        private long mDisabledTimestamp;

        @Override
        public void enter() {
            // now trigger the actual mode switch in ActiveModeWarden
            mActiveModeWarden.enterScanOnlyMode();

            // TODO b/71559473: remove the defered enable after mode management changes are complete
            // Supplicant can't restart right away, so not the time we switched off
            mDisabledTimestamp = SystemClock.elapsedRealtime();
            mDeferredEnableSerialNumber++;
            mHaveDeferredEnable = false;
        }

        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case CMD_WIFI_TOGGLED:
                    if (mSettingsStore.isWifiToggleEnabled()) {
                        if (doDeferEnable(msg)) {
                            if (mHaveDeferredEnable) {
                                // have 2 toggles now, inc serial number and ignore both
                                mDeferredEnableSerialNumber++;
                            }
                            mHaveDeferredEnable = !mHaveDeferredEnable;
                            break;
                        }
                        transitionTo(mStaEnabledState);
                    }
                    break;
                case CMD_SCAN_ALWAYS_MODE_CHANGED:
                    if (!checkScanOnlyModeAvailable()) {
                        log("StaDisabledWithScanState: scan no longer available");
                        transitionTo(mStaDisabledState);
                    }
                    break;
                case CMD_SET_AP:
                    if (msg.arg1 == 1) {
                        // remember that we were disabled, but pass the command up to start softap
                        mSettingsStore.setWifiSavedState(WifiSettingsStore.WIFI_DISABLED);
                    }
                    return NOT_HANDLED;
                case CMD_DEFERRED_TOGGLE:
                    if (msg.arg1 != mDeferredEnableSerialNumber) {
                        log("DEFERRED_TOGGLE ignored due to serial mismatch");
                        break;
                    }
                    logd("DEFERRED_TOGGLE handled");
                    sendMessage((Message)(msg.obj));
                    break;
                case CMD_AP_START_FAILURE:
                case CMD_AP_STOPPED:
                    // already in a wifi mode, no need to check where we should go with softap
                    // stopped
                    break;
                case CMD_SCANNING_STOPPED:
                    // stopped due to interface destruction - return to disabled and wait
                    log("WifiController: SCANNING_STOPPED when in scan mode -> StaDisabled");
                    transitionTo(mStaDisabledState);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }

        private boolean doDeferEnable(Message msg) {
            long delaySoFar = SystemClock.elapsedRealtime() - mDisabledTimestamp;
            if (delaySoFar >= mReEnableDelayMillis) {
                return false;
            }

            log("WifiController msg " + msg + " deferred for " +
                    (mReEnableDelayMillis - delaySoFar) + "ms");

            // need to defer this action.
            Message deferredMsg = obtainMessage(CMD_DEFERRED_TOGGLE);
            deferredMsg.obj = Message.obtain(msg);
            deferredMsg.arg1 = ++mDeferredEnableSerialNumber;
            sendMessageDelayed(deferredMsg, mReEnableDelayMillis - delaySoFar + DEFER_MARGIN_MS);
            return true;
        }

    }

    /**
     * Determine the next state based on the current settings (e.g. saved
     * wifi state).
     */
    private State getNextWifiState() {
        if (mSettingsStore.getWifiSavedState() == WifiSettingsStore.WIFI_ENABLED) {
            return mStaEnabledState;
        }

        if (checkScanOnlyModeAvailable()) {
            return mStaDisabledWithScanState;
        }

        return mStaDisabledState;
    }

    class EcmState extends State {
        // we can enter EcmState either because an emergency call started or because
        // emergency callback mode started. This count keeps track of how many such
        // events happened; so we can exit after all are undone

        private int mEcmEntryCount;
        @Override
        public void enter() {
            mActiveModeWarden.stopSoftAPMode();
            boolean configWiFiDisableInECBM =
                    mFacade.getConfigWiFiDisableInECBM(mContext);
            log("WifiController msg getConfigWiFiDisableInECBM "
                    + configWiFiDisableInECBM);
            if (configWiFiDisableInECBM) {
                mActiveModeWarden.shutdownWifi();
            }
            mEcmEntryCount = 1;
        }

        /**
         * Handles messages received while in EcmMode.
         */
        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case CMD_EMERGENCY_CALL_STATE_CHANGED:
                    if (msg.arg1 == 1) {
                        // nothing to do - just says emergency call started
                        mEcmEntryCount++;
                    } else if (msg.arg1 == 0) {
                        // emergency call ended
                        decrementCountAndReturnToAppropriateState();
                    }
                    return HANDLED;
                case CMD_EMERGENCY_MODE_CHANGED:
                    if (msg.arg1 == 1) {
                        // Transitioned into emergency callback mode
                        mEcmEntryCount++;
                    } else if (msg.arg1 == 0) {
                        // out of emergency callback mode
                        decrementCountAndReturnToAppropriateState();
                    }
                    return HANDLED;
                case CMD_RECOVERY_RESTART_WIFI:
                case CMD_RECOVERY_DISABLE_WIFI:
                    // do not want to restart wifi if we are in emergency mode
                    return HANDLED;
                case CMD_AP_STOPPED:
                case CMD_SCANNING_STOPPED:
                case CMD_STA_STOPPED:
                    // do not want to trigger a mode switch if we are in emergency mode
                    return HANDLED;
                case CMD_SET_AP:
                    // do not want to start softap if we are in emergency mode
                    return HANDLED;
                default:
                    return NOT_HANDLED;
            }
        }

        private void decrementCountAndReturnToAppropriateState() {
            boolean exitEcm = false;

            if (mEcmEntryCount == 0) {
                loge("mEcmEntryCount is 0; exiting Ecm");
                exitEcm = true;
            } else if (--mEcmEntryCount == 0) {
                exitEcm = true;
            }

            if (exitEcm) {
                if (mSettingsStore.isWifiToggleEnabled()) {
                    transitionTo(mStaEnabledState);
                } else if (checkScanOnlyModeAvailable()) {
                    transitionTo(mStaDisabledWithScanState);
                } else {
                    transitionTo(mStaDisabledState);
                }
            }
        }
    }
}