summaryrefslogtreecommitdiffstats
path: root/wifi/java/android/net/wifi/p2p/WifiP2pService.java
blob: fb2c1347a68a009dc465f7c2582c571f2c03713f (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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
/*
 * Copyright (C) 2011 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 android.net.wifi.p2p;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.IConnectivityManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfoInternal;
import android.net.DhcpStateMachine;
import android.net.InterfaceConfiguration;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkInfo;
import android.net.NetworkUtils;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiMonitor;
import android.net.wifi.WifiNative;
import android.net.wifi.WifiStateMachine;
import android.net.wifi.Wps;
import android.net.wifi.Wps.Setup;
import android.net.wifi.p2p.WifiP2pDevice.Status;
import android.os.Binder;
import android.os.IBinder;
import android.os.INetworkManagementService;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Messenger;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.provider.Settings;
import android.util.Slog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import com.android.internal.R;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * WifiP2pService inclues a state machine to perform Wi-Fi p2p operations. Applications
 * communicate with this service to issue device discovery and connectivity requests
 * through the WifiP2pManager interface. The state machine communicates with the wifi
 * driver through wpa_supplicant and handles the event responses through WifiMonitor.
 *
 * Note that the term Wifi when used without a p2p suffix refers to the client mode
 * of Wifi operation
 * @hide
 */
public class WifiP2pService extends IWifiP2pManager.Stub {
    private static final String TAG = "WifiP2pService";
    private static final boolean DBG = true;
    private static final String NETWORKTYPE = "WIFI_P2P";

    private Context mContext;
    private String mInterface;
    private Notification mNotification;

    INetworkManagementService mNwService;
    private DhcpStateMachine mDhcpStateMachine;

    //Tracked to notify the user about wifi client/hotspot being shut down
    //during p2p bring up
    private int mWifiState = WifiManager.WIFI_STATE_DISABLED;
    private int mWifiApState = WifiManager.WIFI_AP_STATE_DISABLED;

    private P2pStateMachine mP2pStateMachine;
    private AsyncChannel mReplyChannel = new AsyncChannel();
    private AsyncChannel mWifiChannel;

    /* Two minutes comes from the wpa_supplicant setting */
    private static final int GROUP_NEGOTIATION_WAIT_TIME_MS = 120 * 1000;
    private static int mGroupNegotiationTimeoutIndex = 0;

    /**
     * Delay between restarts upon failure to setup connection with supplicant
     */
    private static final int P2P_RESTART_INTERVAL_MSECS = 5000;

    /**
     * Number of times we attempt to restart p2p
     */
    private static final int P2P_RESTART_TRIES = 5;

    private int mP2pRestartCount = 0;

    private static final int BASE = Protocol.BASE_WIFI_P2P_SERVICE;

    /* Message sent to WifiStateMachine to indicate p2p enable is pending */
    public static final int P2P_ENABLE_PENDING              =   BASE + 1;
    /* Message sent to WifiStateMachine to indicate Wi-Fi client/hotspot operation can proceed */
    public static final int WIFI_ENABLE_PROCEED             =   BASE + 2;

    /* Delayed message to timeout of group negotiation */
    public static final int GROUP_NEGOTIATION_TIMED_OUT     =   BASE + 3;

    /* User accepted to disable Wi-Fi in order to enable p2p */
    private static final int WIFI_DISABLE_USER_ACCEPT       =   BASE + 4;
    /* User rejected to disable Wi-Fi in order to enable p2p */
    private static final int WIFI_DISABLE_USER_REJECT       =   BASE + 5;

    /* Airplane mode changed */
    private static final int AIRPLANE_MODE_CHANGED          =   BASE + 6;
    /* Emergency callback mode */
    private static final int EMERGENCY_CALLBACK_MODE        =   BASE + 7;

    private final boolean mP2pSupported;
    private final String mDeviceType;
    private String mDeviceName;
    private String mDeviceAddress;

    /* When a group has been explicitly created by an app, we persist the group
     * even after all clients have been disconnected until an explicit remove
     * is invoked */
    private boolean mPersistGroup;

    private NetworkInfo mNetworkInfo;

    /* Is chosen as a unique range to avoid conflict with
       the range defined in Tethering.java */
    private static final String[] DHCP_RANGE = {"192.168.49.2", "192.168.49.254"};
    private static final String SERVER_ADDRESS = "192.168.49.1";

    public WifiP2pService(Context context) {
        mContext = context;

        mInterface = SystemProperties.get("wifi.interface", "wlan0");
        mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0, NETWORKTYPE, "");

        mP2pSupported = mContext.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_WIFI_DIRECT);

        mDeviceType = mContext.getResources().getString(
                com.android.internal.R.string.config_wifi_p2p_device_type);
        mDeviceName = getDefaultDeviceName();

        mP2pStateMachine = new P2pStateMachine(TAG, mP2pSupported);
        mP2pStateMachine.start();

        // broadcasts
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        filter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
        filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
        mContext.registerReceiver(new WifiStateReceiver(), filter);

    }

    public void connectivityServiceReady() {
        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
        mNwService = INetworkManagementService.Stub.asInterface(b);
    }

    private class WifiStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                        WifiManager.WIFI_STATE_DISABLED);
            } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
                mWifiApState = intent.getIntExtra(WifiManager.EXTRA_WIFI_AP_STATE,
                        WifiManager.WIFI_AP_STATE_DISABLED);
            } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
                mP2pStateMachine.sendMessage(AIRPLANE_MODE_CHANGED);
            } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
                if (intent.getBooleanExtra("phoneinECMState", false) == true) {
                    mP2pStateMachine.sendMessage(EMERGENCY_CALLBACK_MODE);
                }
            }
        }
    }

    private void enforceAccessPermission() {
        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
                "WifiP2pService");
    }

    private void enforceChangePermission() {
        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
                "WifiP2pService");
    }

    /* We use the 4 digits of the ANDROID_ID to have a friendly
     * default that has low likelihood of collision with a peer */
    private String getDefaultDeviceName() {
        String id = Settings.Secure.getString(mContext.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        return "Android_" + id.substring(0,4);
    }

    /**
     * Get a reference to handler. This is used by a client to establish
     * an AsyncChannel communication with WifiP2pService
     */
    public Messenger getMessenger() {
        enforceAccessPermission();
        enforceChangePermission();
        return new Messenger(mP2pStateMachine.getHandler());
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
                != PackageManager.PERMISSION_GRANTED) {
            pw.println("Permission Denial: can't dump WifiP2pService from from pid="
                    + Binder.getCallingPid()
                    + ", uid=" + Binder.getCallingUid());
            return;
        }
    }


    /**
     * Handles interaction with WifiStateMachine
     */
    private class P2pStateMachine extends StateMachine {

        private DefaultState mDefaultState = new DefaultState();
        private P2pNotSupportedState mP2pNotSupportedState = new P2pNotSupportedState();
        private P2pDisablingState mP2pDisablingState = new P2pDisablingState();
        private P2pDisabledState mP2pDisabledState = new P2pDisabledState();
        private WaitForUserActionState mWaitForUserActionState = new WaitForUserActionState();
        private WaitForWifiDisableState mWaitForWifiDisableState = new WaitForWifiDisableState();
        private P2pEnablingState mP2pEnablingState = new P2pEnablingState();
        private P2pEnabledState mP2pEnabledState = new P2pEnabledState();
        // Inactive is when p2p is enabled with no connectivity
        private InactiveState mInactiveState = new InactiveState();
        private GroupNegotiationState mGroupNegotiationState = new GroupNegotiationState();
        private GroupCreatedState mGroupCreatedState = new GroupCreatedState();

        private WifiMonitor mWifiMonitor = new WifiMonitor(this);

        private WifiP2pDeviceList mPeers = new WifiP2pDeviceList();
        private WifiP2pInfo mWifiP2pInfo = new WifiP2pInfo();
        private WifiP2pGroup mGroup;

        // Saved WifiP2pConfig from GO negotiation request
        private WifiP2pConfig mSavedGoNegotiationConfig;

        // Saved WifiP2pConfig from connect request
        private WifiP2pConfig mSavedConnectConfig;

        // Saved WifiP2pGroup from invitation request
        private WifiP2pGroup mSavedP2pGroup;

        P2pStateMachine(String name, boolean p2pSupported) {
            super(name);

            addState(mDefaultState);
                addState(mP2pNotSupportedState, mDefaultState);
                addState(mP2pDisablingState, mDefaultState);
                addState(mP2pDisabledState, mDefaultState);
                    addState(mWaitForUserActionState, mP2pDisabledState);
                    addState(mWaitForWifiDisableState, mP2pDisabledState);
                addState(mP2pEnablingState, mDefaultState);
                addState(mP2pEnabledState, mDefaultState);
                    addState(mInactiveState, mP2pEnabledState);
                    addState(mGroupNegotiationState, mP2pEnabledState);
                    addState(mGroupCreatedState, mP2pEnabledState);

            if (p2pSupported) {
                setInitialState(mP2pDisabledState);
            } else {
                setInitialState(mP2pNotSupportedState);
            }
        }

    class DefaultState extends State {
        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
                    if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
                        if (DBG) logd("Full connection with WifiStateMachine established");
                        mWifiChannel = (AsyncChannel) message.obj;
                    } else {
                        loge("Full connection failure, error = " + message.arg1);
                        mWifiChannel = null;
                    }
                    break;

                case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
                    if (message.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
                        loge("Send failed, client connection lost");
                    } else {
                        loge("Client connection lost with reason: " + message.arg1);
                    }
                    mWifiChannel = null;
                    break;

                case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION:
                    AsyncChannel ac = new AsyncChannel();
                    ac.connect(mContext, getHandler(), message.replyTo);
                    break;
                case WifiStateMachine.WIFI_ENABLE_PENDING:
                    // Disable p2p operation before we can respond
                    sendMessage(WifiP2pManager.DISABLE_P2P);
                    deferMessage(message);
                    break;
                case WifiP2pManager.ENABLE_P2P:
                    replyToMessage(message, WifiP2pManager.ENABLE_P2P_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                case WifiP2pManager.DISABLE_P2P:
                    replyToMessage(message, WifiP2pManager.DISABLE_P2P_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                case WifiP2pManager.DISCOVER_PEERS:
                    replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                case WifiP2pManager.CONNECT:
                    replyToMessage(message, WifiP2pManager.CONNECT_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                case WifiP2pManager.CREATE_GROUP:
                    replyToMessage(message, WifiP2pManager.CREATE_GROUP_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                case WifiP2pManager.REMOVE_GROUP:
                    replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                case WifiP2pManager.REQUEST_PEERS:
                    replyToMessage(message, WifiP2pManager.RESPONSE_PEERS, mPeers);
                    break;
                case WifiP2pManager.REQUEST_CONNECTION_INFO:
                    replyToMessage(message, WifiP2pManager.RESPONSE_CONNECTION_INFO, mWifiP2pInfo);
                    break;
                case WifiP2pManager.REQUEST_GROUP_INFO:
                    replyToMessage(message, WifiP2pManager.RESPONSE_GROUP_INFO, mGroup);
                    break;
                case AIRPLANE_MODE_CHANGED:
                    if (isAirplaneModeOn()) sendMessage(WifiP2pManager.DISABLE_P2P);
                    break;
                case EMERGENCY_CALLBACK_MODE:
                    sendMessage(WifiP2pManager.DISABLE_P2P);
                    break;
                    // Ignore
                case WIFI_DISABLE_USER_ACCEPT:
                case WIFI_DISABLE_USER_REJECT:
                case GROUP_NEGOTIATION_TIMED_OUT:
                    break;
                default:
                    loge("Unhandled message " + message);
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class P2pNotSupportedState extends State {
        @Override
        public boolean processMessage(Message message) {
            switch (message.what) {
                // Allow Wi-Fi to proceed
                case WifiStateMachine.WIFI_ENABLE_PENDING:
                    replyToMessage(message, WIFI_ENABLE_PROCEED);
                    break;
                case WifiP2pManager.ENABLE_P2P:
                    replyToMessage(message, WifiP2pManager.ENABLE_P2P_FAILED,
                            WifiP2pManager.P2P_UNSUPPORTED);
                    break;
                case WifiP2pManager.DISABLE_P2P:
                    replyToMessage(message, WifiP2pManager.DISABLE_P2P_FAILED,
                            WifiP2pManager.P2P_UNSUPPORTED);
                    break;
                case WifiP2pManager.DISCOVER_PEERS:
                    replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED,
                            WifiP2pManager.P2P_UNSUPPORTED);
                    break;
                case WifiP2pManager.CONNECT:
                    replyToMessage(message, WifiP2pManager.CONNECT_FAILED,
                            WifiP2pManager.P2P_UNSUPPORTED);
                    break;
                case WifiP2pManager.CREATE_GROUP:
                    replyToMessage(message, WifiP2pManager.CREATE_GROUP_FAILED,
                            WifiP2pManager.P2P_UNSUPPORTED);
                    break;
                case WifiP2pManager.REMOVE_GROUP:
                    replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED,
                            WifiP2pManager.P2P_UNSUPPORTED);
                    break;
               default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class P2pDisablingState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            logd("stopping supplicant");
            if (!WifiNative.stopSupplicant()) {
                loge("Failed to stop supplicant, issue kill");
                WifiNative.killSupplicant();
            }
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.SUP_DISCONNECTION_EVENT:
                    logd("Supplicant connection lost");
                    WifiNative.closeSupplicantConnection();
                    transitionTo(mP2pDisabledState);
                    break;
                case WifiP2pManager.ENABLE_P2P:
                case WifiP2pManager.DISABLE_P2P:
                    deferMessage(message);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }


    class P2pDisabledState extends State {
       @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiP2pManager.ENABLE_P2P:
                    OnClickListener listener = new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == DialogInterface.BUTTON_POSITIVE) {
                                sendMessage(WIFI_DISABLE_USER_ACCEPT);
                            } else {
                                sendMessage(WIFI_DISABLE_USER_REJECT);
                            }
                        }
                    };

                    // Show a user request dialog if we know Wi-Fi client/hotspot is in operation
                    if (mWifiState != WifiManager.WIFI_STATE_DISABLED ||
                            mWifiApState != WifiManager.WIFI_AP_STATE_DISABLED) {
                        Resources r = Resources.getSystem();
                        AlertDialog dialog = new AlertDialog.Builder(mContext)
                            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
                            .setMessage(r.getString(R.string.wifi_p2p_turnon_message))
                            .setPositiveButton(r.getString(R.string.ok), listener)
                            .setNegativeButton(r.getString(R.string.cancel), listener)
                            .create();
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                        dialog.show();
                        transitionTo(mWaitForUserActionState);
                    } else {
                        mWifiChannel.sendMessage(P2P_ENABLE_PENDING);
                        transitionTo(mWaitForWifiDisableState);
                    }
                    replyToMessage(message, WifiP2pManager.ENABLE_P2P_SUCCEEDED);
                    break;
                case WifiP2pManager.DISABLE_P2P:
                    replyToMessage(message, WifiP2pManager.DISABLE_P2P_SUCCEEDED);
                    break;
                case WifiStateMachine.WIFI_ENABLE_PENDING:
                    replyToMessage(message, WIFI_ENABLE_PROCEED);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class WaitForUserActionState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WIFI_DISABLE_USER_ACCEPT:
                    mWifiChannel.sendMessage(P2P_ENABLE_PENDING);
                    transitionTo(mWaitForWifiDisableState);
                    break;
                case WIFI_DISABLE_USER_REJECT:
                    logd("User rejected enabling p2p");
                    sendP2pStateChangedBroadcast(false);
                    transitionTo(mP2pDisabledState);
                    break;
                case WifiP2pManager.ENABLE_P2P:
                case WifiP2pManager.DISABLE_P2P:
                    deferMessage(message);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class WaitForWifiDisableState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiStateMachine.P2P_ENABLE_PROCEED:
                    try {
                        mNwService.wifiFirmwareReload(mInterface, "P2P");
                    } catch (Exception e) {
                        loge("Failed to reload p2p firmware " + e);
                        // continue
                    }

                    //A runtime crash can leave the interface up and
                    //this affects p2p when supplicant starts up.
                    //Ensure interface is down before a supplicant start.
                    try {
                        mNwService.setInterfaceDown(mInterface);
                    } catch (Exception e) {
                        if (DBG) Slog.w(TAG, "Unable to bring down wlan interface: " + e);
                    }

                    if (WifiNative.startP2pSupplicant()) {
                        mWifiMonitor.startMonitoring();
                        transitionTo(mP2pEnablingState);
                    } else {
                        notifyP2pEnableFailure();
                        transitionTo(mP2pDisabledState);
                    }
                    break;
                case WifiP2pManager.ENABLE_P2P:
                case WifiP2pManager.DISABLE_P2P:
                    deferMessage(message);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class P2pEnablingState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.SUP_CONNECTION_EVENT:
                    logd("P2p start successful");
                    transitionTo(mInactiveState);
                    break;
                case WifiMonitor.SUP_DISCONNECTION_EVENT:
                    if (++mP2pRestartCount <= P2P_RESTART_TRIES) {
                        loge("Failed to start p2p, retry");
                        WifiNative.killSupplicant();
                        sendMessageDelayed(WifiP2pManager.ENABLE_P2P, P2P_RESTART_INTERVAL_MSECS);
                    } else {
                        loge("Failed " + mP2pRestartCount + " times to start p2p, quit ");
                        mP2pRestartCount = 0;
                    }
                    transitionTo(mP2pDisabledState);
                    break;
                case WifiP2pManager.ENABLE_P2P:
                case WifiP2pManager.DISABLE_P2P:
                    deferMessage(message);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class P2pEnabledState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            sendP2pStateChangedBroadcast(true);
            mNetworkInfo.setIsAvailable(true);
            initializeP2pSettings();
            showNotification();
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiP2pManager.ENABLE_P2P:
                    replyToMessage(message, WifiP2pManager.ENABLE_P2P_SUCCEEDED);
                    break;
                case WifiP2pManager.DISABLE_P2P:
                    if (mPeers.clear()) sendP2pPeersChangedBroadcast();
                    replyToMessage(message, WifiP2pManager.DISABLE_P2P_SUCCEEDED);
                    transitionTo(mP2pDisablingState);
                    break;
                case WifiP2pManager.DISCOVER_PEERS:
                    int timeout = message.arg1;
                    if (WifiNative.p2pFind(timeout)) {
                        replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_SUCCEEDED);
                    } else {
                        replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED,
                                WifiP2pManager.ERROR);
                    }
                    break;
                case WifiMonitor.P2P_DEVICE_FOUND_EVENT:
                    WifiP2pDevice device = (WifiP2pDevice) message.obj;
                    if (mDeviceAddress.equals(device.deviceAddress)) break;
                    mPeers.update(device);
                    sendP2pPeersChangedBroadcast();
                    break;
                case WifiMonitor.P2P_DEVICE_LOST_EVENT:
                    device = (WifiP2pDevice) message.obj;
                    if (mPeers.remove(device)) sendP2pPeersChangedBroadcast();
                    break;
                case WifiP2pManager.CONNECT:
                    if (DBG) logd(getName() + " sending connect");
                    mSavedConnectConfig = (WifiP2pConfig) message.obj;
                    mPersistGroup = false;
                    int netId = configuredNetworkId(mSavedConnectConfig.deviceAddress);
                    if (netId >= 0) {
                        //TODO: if failure, remove config and do a regular p2pConnect()
                        WifiNative.p2pReinvoke(netId, mSavedConnectConfig.deviceAddress);
                    } else {
                        boolean join = false;
                        if (isGroupOwner(mSavedConnectConfig.deviceAddress)) join = true;
                        String pin = WifiNative.p2pConnect(mSavedConnectConfig, join);
                        try {
                            Integer.parseInt(pin);
                            notifyWpsPin(pin, mSavedConnectConfig.deviceAddress);
                        } catch (NumberFormatException ignore) {
                            // do nothing if p2pConnect did not return a pin
                        }
                    }
                    updateDeviceStatus(mSavedConnectConfig.deviceAddress, Status.INVITED);
                    sendP2pPeersChangedBroadcast();
                    replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED);
                    transitionTo(mGroupNegotiationState);
                    break;
                case WifiMonitor.SUP_DISCONNECTION_EVENT:  /* Supplicant died */
                    loge("Connection lost, restart p2p");
                    WifiNative.killSupplicant();
                    WifiNative.closeSupplicantConnection();
                    if (mPeers.clear()) sendP2pPeersChangedBroadcast();
                    transitionTo(mP2pDisabledState);
                    sendMessageDelayed(WifiP2pManager.ENABLE_P2P, P2P_RESTART_INTERVAL_MSECS);
                    break;
                case WifiMonitor.P2P_GROUP_STARTED_EVENT:
                    mGroup = (WifiP2pGroup) message.obj;
                    if (DBG) logd(getName() + " group started");
                    if (mGroup.isGroupOwner()) {
                        startDhcpServer(mGroup.getInterface());
                    } else {
                        mDhcpStateMachine = DhcpStateMachine.makeDhcpStateMachine(mContext,
                                P2pStateMachine.this, mGroup.getInterface());
                        mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_START_DHCP);
                        WifiP2pDevice groupOwner = mGroup.getOwner();
                        updateDeviceStatus(groupOwner.deviceAddress, Status.CONNECTED);
                        sendP2pPeersChangedBroadcast();
                    }
                    transitionTo(mGroupCreatedState);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }

        @Override
        public void exit() {
            sendP2pStateChangedBroadcast(false);
            mNetworkInfo.setIsAvailable(false);
            clearNotification();
        }
    }

    class InactiveState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            //Start listening every time we get inactive
            WifiNative.p2pListen();
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.P2P_GO_NEGOTIATION_REQUEST_EVENT:
                    mSavedGoNegotiationConfig = (WifiP2pConfig) message.obj;
                    notifyP2pGoNegotationRequest(mSavedGoNegotiationConfig);
                    break;
                case WifiP2pManager.CREATE_GROUP:
                    mPersistGroup = true;
                    if (WifiNative.p2pGroupAdd()) {
                        replyToMessage(message, WifiP2pManager.CREATE_GROUP_SUCCEEDED);
                    } else {
                        replyToMessage(message, WifiP2pManager.CREATE_GROUP_FAILED,
                                WifiP2pManager.ERROR);
                    }
                    transitionTo(mGroupNegotiationState);
                    break;
                case WifiMonitor.P2P_INVITATION_RECEIVED_EVENT:
                    WifiP2pGroup group = (WifiP2pGroup) message.obj;
                    notifyP2pInvitationReceived(group);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class GroupNegotiationState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            sendMessageDelayed(obtainMessage(GROUP_NEGOTIATION_TIMED_OUT,
                    ++mGroupNegotiationTimeoutIndex, 0), GROUP_NEGOTIATION_WAIT_TIME_MS);
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                // We ignore these right now, since we get a GROUP_STARTED notification
                // afterwards
                case WifiMonitor.P2P_GO_NEGOTIATION_SUCCESS_EVENT:
                case WifiMonitor.P2P_GROUP_FORMATION_SUCCESS_EVENT:
                    if (DBG) logd(getName() + " go success");
                    break;
                case WifiMonitor.P2P_GO_NEGOTIATION_FAILURE_EVENT:
                case WifiMonitor.P2P_GROUP_FORMATION_FAILURE_EVENT:
                    if (DBG) logd(getName() + " go failure");
                    updateDeviceStatus(mSavedConnectConfig.deviceAddress, Status.FAILED);
                    mSavedConnectConfig = null;
                    sendP2pPeersChangedBroadcast();
                    transitionTo(mInactiveState);
                    break;
                case GROUP_NEGOTIATION_TIMED_OUT:
                    if (mGroupNegotiationTimeoutIndex == message.arg1) {
                        if (DBG) logd("Group negotiation timed out");
                        updateDeviceStatus(mSavedConnectConfig.deviceAddress, Status.FAILED);
                        mSavedConnectConfig = null;
                        sendP2pPeersChangedBroadcast();
                        transitionTo(mInactiveState);
                    }
                    break;
                case WifiP2pManager.DISCOVER_PEERS:
                    /* Discovery will break negotiation */
                    replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED,
                            WifiP2pManager.BUSY);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }
    }

    class GroupCreatedState extends State {
        @Override
        public void enter() {
            if (DBG) logd(getName());
            mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);

            //DHCP server has already been started if I am a group owner
            if (mGroup.isGroupOwner()) {
                setWifiP2pInfoOnGroupFormation(SERVER_ADDRESS);
                sendP2pConnectionChangedBroadcast();
            }
        }

        @Override
        public boolean processMessage(Message message) {
            if (DBG) logd(getName() + message.toString());
            switch (message.what) {
                case WifiMonitor.AP_STA_CONNECTED_EVENT:
                    //After a GO setup, STA connected event comes with interface address
                    String interfaceAddress = (String) message.obj;
                    String deviceAddress = getDeviceAddress(interfaceAddress);
                    if (deviceAddress != null) {
                        mGroup.addClient(deviceAddress);
                        updateDeviceStatus(deviceAddress, Status.CONNECTED);
                        if (DBG) logd(getName() + " ap sta connected");
                        sendP2pPeersChangedBroadcast();
                    } else {
                        loge("Connect on unknown device address : " + interfaceAddress);
                    }
                    break;
                case WifiMonitor.AP_STA_DISCONNECTED_EVENT:
                    interfaceAddress = (String) message.obj;
                    deviceAddress = getDeviceAddress(interfaceAddress);
                    if (deviceAddress != null) {
                        updateDeviceStatus(deviceAddress, Status.AVAILABLE);
                        if (mGroup.removeClient(deviceAddress)) {
                            if (DBG) logd("Removed client " + deviceAddress);
                            if (!mPersistGroup && mGroup.isClientListEmpty()) {
                                Slog.d(TAG, "Client list empty, remove non-persistent p2p group");
                                WifiNative.p2pGroupRemove(mGroup.getInterface());
                            }
                        } else {
                            if (DBG) logd("Failed to remove client " + deviceAddress);
                            for (WifiP2pDevice c : mGroup.getClientList()) {
                                if (DBG) logd("client " + c.deviceAddress);
                            }
                        }
                        sendP2pPeersChangedBroadcast();
                        if (DBG) loge(getName() + " ap sta disconnected");
                    } else {
                        loge("Disconnect on unknown device address : " + interfaceAddress);
                    }
                    break;
                case DhcpStateMachine.CMD_POST_DHCP_ACTION:
                    DhcpInfoInternal dhcpInfo = (DhcpInfoInternal) message.obj;
                    if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS &&
                            dhcpInfo != null) {
                        if (DBG) logd("DhcpInfo: " + dhcpInfo);
                        setWifiP2pInfoOnGroupFormation(dhcpInfo.serverAddress);
                        sendP2pConnectionChangedBroadcast();
                    } else {
                        WifiNative.p2pGroupRemove(mGroup.getInterface());
                    }
                    break;
                case WifiP2pManager.REMOVE_GROUP:
                    if (DBG) loge(getName() + " remove group");
                    if (WifiNative.p2pGroupRemove(mGroup.getInterface())) {
                        replyToMessage(message, WifiP2pManager.REMOVE_GROUP_SUCCEEDED);
                    } else {
                        replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED,
                                WifiP2pManager.ERROR);
                    }
                    break;
                case WifiMonitor.P2P_GROUP_REMOVED_EVENT:
                    if (DBG) loge(getName() + " group removed");
                    Collection <WifiP2pDevice> devices = mGroup.getClientList();
                    boolean changed = false;
                    for (WifiP2pDevice d : mPeers.getDeviceList()) {
                        if (devices.contains(d) || mGroup.getOwner().equals(d)) {
                            d.status = Status.AVAILABLE;
                            changed = true;
                        }
                    }

                    if (mGroup.isGroupOwner()) {
                        stopDhcpServer();
                    } else {
                        if (DBG) logd("stop DHCP client");
                        mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_STOP_DHCP);
                        mDhcpStateMachine.quit();
                        mDhcpStateMachine = null;
                    }

                    mGroup = null;
                    if (changed) sendP2pPeersChangedBroadcast();
                    transitionTo(mInactiveState);
                    break;
                case WifiMonitor.P2P_DEVICE_LOST_EVENT:
                    WifiP2pDevice device = (WifiP2pDevice) message.obj;
                    if (device.equals(mGroup.getOwner())) {
                        logd("Lost the group owner, killing p2p connection");
                        WifiNative.p2pGroupRemove(mGroup.getInterface());
                    } else if (mGroup.removeClient(device)) {
                        if (!mPersistGroup && mGroup.isClientListEmpty()) {
                            Slog.d(TAG, "Client list empty, removing a non-persistent p2p group");
                            WifiNative.p2pGroupRemove(mGroup.getInterface());
                        }
                    }
                    return NOT_HANDLED; // Do the regular device lost handling
                case WifiP2pManager.DISABLE_P2P:
                    sendMessage(WifiP2pManager.REMOVE_GROUP);
                    deferMessage(message);
                    break;
                case WifiP2pManager.CONNECT:
                    WifiP2pConfig config = (WifiP2pConfig) message.obj;
                    logd("Inviting device : " + config.deviceAddress);
                    if (WifiNative.p2pInvite(mGroup, config.deviceAddress)) {
                        updateDeviceStatus(config.deviceAddress, Status.INVITED);
                        sendP2pPeersChangedBroadcast();
                        replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED);
                    } else {
                        replyToMessage(message, WifiP2pManager.CONNECT_FAILED,
                                WifiP2pManager.ERROR);
                    }
                    // TODO: figure out updating the status to declined when invitation is rejected
                    break;
                case WifiMonitor.P2P_INVITATION_RESULT_EVENT:
                    logd("===> INVITATION RESULT EVENT : " + message.obj);
                    break;
                case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT:
                    notifyP2pProvDiscPbcRequest((WifiP2pDevice) message.obj);
                    break;
                case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT:
                    notifyP2pProvDiscPinRequest((WifiP2pDevice) message.obj);
                    break;
                case WifiMonitor.P2P_GROUP_STARTED_EVENT:
                    Slog.e(TAG, "Duplicate group creation event notice, ignore");
                    break;
                case WifiP2pManager.WPS_PBC:
                    WifiNative.wpsPbc();
                    break;
                case WifiP2pManager.WPS_PIN:
                    WifiNative.wpsPin((String) message.obj);
                    break;
                default:
                    return NOT_HANDLED;
            }
            return HANDLED;
        }

        public void exit() {
            setWifiP2pInfoOnGroupTermination();
            mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
            sendP2pConnectionChangedBroadcast();
        }
    }

    private void sendP2pStateChangedBroadcast(boolean enabled) {
        final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
        if (enabled) {
            intent.putExtra(WifiP2pManager.EXTRA_WIFI_STATE,
                    WifiP2pManager.WIFI_P2P_STATE_ENABLED);
        } else {
            intent.putExtra(WifiP2pManager.EXTRA_WIFI_STATE,
                    WifiP2pManager.WIFI_P2P_STATE_DISABLED);
        }
        mContext.sendStickyBroadcast(intent);
    }

    private void sendP2pPeersChangedBroadcast() {
        final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
        mContext.sendBroadcast(intent);
    }

    private void sendP2pConnectionChangedBroadcast() {
        if (DBG) logd("sending p2p connection changed broadcast");
        Intent intent = new Intent(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
        intent.putExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO, new WifiP2pInfo(mWifiP2pInfo));
        intent.putExtra(WifiP2pManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo));
        mContext.sendStickyBroadcast(intent);
    }

    private void startDhcpServer(String intf) {
        InterfaceConfiguration ifcg = null;
        try {
            ifcg = mNwService.getInterfaceConfig(intf);
            ifcg.addr = new LinkAddress(NetworkUtils.numericToInetAddress(
                        SERVER_ADDRESS), 24);
            ifcg.interfaceFlags = "[up]";
            mNwService.setInterfaceConfig(intf, ifcg);
            /* This starts the dnsmasq server */
            mNwService.startTethering(DHCP_RANGE);
        } catch (Exception e) {
            loge("Error configuring interface " + intf + ", :" + e);
            return;
        }

        logd("Started Dhcp server on " + intf);
   }

    private void stopDhcpServer() {
        try {
            mNwService.stopTethering();
        } catch (Exception e) {
            loge("Error stopping Dhcp server" + e);
            return;
        }

        logd("Stopped Dhcp server");
    }

    private void notifyP2pEnableFailure() {
        Resources r = Resources.getSystem();
        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
            .setMessage(r.getString(R.string.wifi_p2p_failed_message))
            .setPositiveButton(r.getString(R.string.ok), null)
            .create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void notifyWpsPin(String pin, String peerAddress) {
        Resources r = Resources.getSystem();
        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
            .setMessage(r.getString(R.string.wifi_p2p_pin_display_message, pin, peerAddress))
            .setPositiveButton(r.getString(R.string.ok), null)
            .create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void notifyP2pGoNegotationRequest(WifiP2pConfig config) {
        Resources r = Resources.getSystem();
        Wps wps = config.wps;
        final View textEntryView = LayoutInflater.from(mContext)
                .inflate(R.layout.wifi_p2p_go_negotiation_request_alert, null);
        final EditText pin = (EditText) textEntryView .findViewById(R.id.wifi_p2p_wps_pin);

        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
            .setView(textEntryView)
            .setPositiveButton(r.getString(R.string.ok), new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (DBG) logd(getName() + " connect " + pin.getText());

                            if (pin.getVisibility() == View.GONE) {
                                mSavedGoNegotiationConfig.wps.setup = Setup.PBC;
                            } else {
                                mSavedGoNegotiationConfig.wps.setup = Setup.KEYPAD;
                                mSavedGoNegotiationConfig.wps.pin = pin.getText().toString();
                            }
                            sendMessage(WifiP2pManager.CONNECT, mSavedGoNegotiationConfig);
                            mSavedGoNegotiationConfig = null;
                        }
                    })
            .setNegativeButton(r.getString(R.string.cancel), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (DBG) logd(getName() + " ignore connect");
                            mSavedGoNegotiationConfig = null;
                        }
                    })
            .create();

        if (wps.setup == Setup.PBC) {
            pin.setVisibility(View.GONE);
            dialog.setMessage(r.getString(R.string.wifi_p2p_pbc_go_negotiation_request_message,
                        config.deviceAddress));
        } else {
            dialog.setMessage(r.getString(R.string.wifi_p2p_pin_go_negotiation_request_message,
                        config.deviceAddress));
        }

        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void notifyP2pProvDiscPbcRequest(WifiP2pDevice peer) {
        Resources r = Resources.getSystem();
        final View textEntryView = LayoutInflater.from(mContext)
                .inflate(R.layout.wifi_p2p_go_negotiation_request_alert, null);
        final EditText pin = (EditText) textEntryView .findViewById(R.id.wifi_p2p_wps_pin);

        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
            .setView(textEntryView)
            .setPositiveButton(r.getString(R.string.ok), new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                                if (DBG) logd(getName() + " wps_pbc");
                                sendMessage(WifiP2pManager.WPS_PBC);
                        }
                    })
            .setNegativeButton(r.getString(R.string.cancel), null)
            .create();

        pin.setVisibility(View.GONE);
        dialog.setMessage(r.getString(R.string.wifi_p2p_pbc_go_negotiation_request_message,
                        peer.deviceAddress));

        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void notifyP2pProvDiscPinRequest(WifiP2pDevice peer) {
        Resources r = Resources.getSystem();
        final View textEntryView = LayoutInflater.from(mContext)
                .inflate(R.layout.wifi_p2p_go_negotiation_request_alert, null);
        final EditText pin = (EditText) textEntryView .findViewById(R.id.wifi_p2p_wps_pin);

        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
            .setView(textEntryView)
            .setPositiveButton(r.getString(R.string.ok), new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (DBG) logd(getName() + " wps_pin");
                        sendMessage(WifiP2pManager.WPS_PIN, pin.getText().toString());
                    }
                    })
            .setNegativeButton(r.getString(R.string.cancel), null)
            .create();

        dialog.setMessage(r.getString(R.string.wifi_p2p_pin_go_negotiation_request_message,
                        peer.deviceAddress));

        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void notifyP2pInvitationReceived(WifiP2pGroup group) {
        mSavedP2pGroup = group;
        Resources r = Resources.getSystem();
        final View textEntryView = LayoutInflater.from(mContext)
                .inflate(R.layout.wifi_p2p_go_negotiation_request_alert, null);
        final EditText pin = (EditText) textEntryView .findViewById(R.id.wifi_p2p_wps_pin);

        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
            .setView(textEntryView)
            .setPositiveButton(r.getString(R.string.ok), new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                                WifiP2pConfig config = new WifiP2pConfig();
                                config.deviceAddress = mSavedP2pGroup.getOwner().deviceAddress;
                                if (DBG) logd(getName() + " connect to invited group");
                                sendMessage(WifiP2pManager.CONNECT, config);
                                mSavedP2pGroup = null;
                        }
                    })
            .setNegativeButton(r.getString(R.string.cancel), null)
            .create();

        pin.setVisibility(View.GONE);
        dialog.setMessage(r.getString(R.string.wifi_p2p_pbc_go_negotiation_request_message,
                        group.getOwner().deviceAddress));

        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void updateDeviceStatus(String deviceAddress, Status status) {
        for (WifiP2pDevice d : mPeers.getDeviceList()) {
            if (d.deviceAddress.equals(deviceAddress)) {
                d.status = status;
            }
        }
    }

    private boolean isGroupOwner(String deviceAddress) {
        for (WifiP2pDevice d : mPeers.getDeviceList()) {
            if (d.deviceAddress.equals(deviceAddress)) {
                return d.isGroupOwner();
            }
        }
        return false;
    }

    //TODO: implement when wpa_supplicant is fixed
    private int configuredNetworkId(String deviceAddress) {
        return -1;
    }

    private void setWifiP2pInfoOnGroupFormation(String serverAddress) {
        mWifiP2pInfo.groupFormed = true;
        mWifiP2pInfo.isGroupOwner = mGroup.isGroupOwner();
        mWifiP2pInfo.groupOwnerAddress = NetworkUtils.numericToInetAddress(serverAddress);
    }

    private void setWifiP2pInfoOnGroupTermination() {
        mWifiP2pInfo.groupFormed = false;
        mWifiP2pInfo.isGroupOwner = false;
        mWifiP2pInfo.groupOwnerAddress = null;
    }

    private String getDeviceAddress(String interfaceAddress) {
        for (WifiP2pDevice d : mPeers.getDeviceList()) {
            if (interfaceAddress.equals(WifiNative.p2pGetInterfaceAddress(d.deviceAddress))) {
                return d.deviceAddress;
            }
        }
        return null;
    }

    private void initializeP2pSettings() {
        WifiNative.setPersistentReconnect(true);
        WifiNative.setDeviceName(mDeviceName);
        WifiNative.setDeviceType(mDeviceType);

        mDeviceAddress = WifiNative.p2pGetDeviceAddress();
        if (DBG) Slog.d(TAG, "DeviceAddress: " + mDeviceAddress);
    }

    //State machine initiated requests can have replyTo set to null indicating
    //there are no recepients, we ignore those reply actions
    private void replyToMessage(Message msg, int what) {
        if (msg.replyTo == null) return;
        mReplyChannel.replyToMessage(msg, what);
    }

    private void replyToMessage(Message msg, int what, int arg1) {
        if (msg.replyTo == null) return;
        mReplyChannel.replyToMessage(msg, what, arg1);
    }

    private void replyToMessage(Message msg, int what, Object obj) {
        if (msg.replyTo == null) return;
        mReplyChannel.replyToMessage(msg, what, obj);
    }

    private void logd(String s) {
        Slog.d(TAG, s);
    }

    private void loge(String s) {
        Slog.e(TAG, s);
    }

    private void showNotification() {
        NotificationManager notificationManager =
            (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager == null || mNotification != null) {
            return;
        }

        Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);

        Resources r = Resources.getSystem();
        CharSequence title = r.getText(R.string.wifi_p2p_enabled_notification_title);
        CharSequence message = r.getText(R.string.wifi_p2p_enabled_notification_message);

        mNotification = new Notification();
        mNotification.when = 0;
        //TODO: might change to be a seperate icon
        mNotification.icon = R.drawable.stat_sys_tether_wifi;
        mNotification.defaults &= ~Notification.DEFAULT_SOUND;
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        mNotification.tickerText = title;
        mNotification.setLatestEventInfo(mContext, title, message, pi);

        notificationManager.notify(mNotification.icon, mNotification);
    }

    private void clearNotification() {
        NotificationManager notificationManager =
            (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null && mNotification != null) {
            notificationManager.cancel(mNotification.icon);
            mNotification = null;
        }
    }

    private boolean isAirplaneSensitive() {
        String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
                Settings.System.AIRPLANE_MODE_RADIOS);
        return airplaneModeRadios == null
            || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
    }

    private boolean isAirplaneModeOn() {
        return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    }

    }
}