forked from tripflex/WifiWizard2
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
WifiWizard2.java
2143 lines (1768 loc) · 65.5 KB
/
WifiWizard2.java
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
/*
* Copyright 2018 Myles McNamara
*
* 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 wifiwizard2;
import org.apache.cordova.*;
import java.util.List;
import java.util.concurrent.Future;
import java.lang.InterruptedException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.pm.PackageManager;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.SupplicantState;
import android.net.ConnectivityManager;
import android.location.LocationManager;
import android.provider.Settings;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.os.Build;
import java.net.URL;
import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.HttpURLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import android.net.wifi.WifiNetworkSpecifier;
import android.net.wifi.WifiNetworkSuggestion;
public class WifiWizard2 extends CordovaPlugin {
private static final String TAG = "WifiWizard2";
private static final int API_VERSION = Build.VERSION.SDK_INT;
private static final String SPECIFIER_NETWORK = "specifierConnection"; //>=29
private static final String SUGGEST_NETWORK = "suggestConnection"; //>=29
private static final String ADD_NETWORK = "add";
private static final String REMOVE_NETWORK = "remove";
private static final String CONNECT_NETWORK = "connect";
private static final String DISCONNECT_NETWORK = "disconnectNetwork";
private static final String DISCONNECT = "disconnect";
private static final String LIST_NETWORKS = "listNetworks";
private static final String START_SCAN = "startScan";
private static final String GET_SCAN_RESULTS = "getScanResults";
private static final String GET_CONNECTED_SSID = "getConnectedSSID";
private static final String GET_CONNECTED_BSSID = "getConnectedBSSID";
private static final String GET_CONNECTED_NETWORKID = "getConnectedNetworkID";
private static final String IS_WIFI_ENABLED = "isWifiEnabled";
private static final String SET_WIFI_ENABLED = "setWifiEnabled";
private static final String SCAN = "scan";
private static final String ENABLE_NETWORK = "enable";
private static final String DISABLE_NETWORK = "disable";
private static final String GET_SSID_NET_ID = "getSSIDNetworkID";
private static final String REASSOCIATE = "reassociate";
private static final String RECONNECT = "reconnect";
private static final String REQUEST_FINE_LOCATION = "requestFineLocation";
private static final String GET_WIFI_IP_ADDRESS = "getWifiIP";
private static final String GET_WIFI_ROUTER_IP_ADDRESS = "getWifiRouterIP";
private static final String CAN_PING_WIFI_ROUTER = "canPingWifiRouter";
private static final String CAN_CONNECT_TO_ROUTER = "canConnectToRouter";
private static final String CAN_CONNECT_TO_INTERNET = "canConnectToInternet";
private static final String IS_CONNECTED_TO_INTERNET = "isConnectedToInternet";
private static final String GET_WIFI_IP_INFO = "getWifiIPInfo";
private static final String IS_LOCATION_ENABLED = "isLocationEnabled";
private static final String SWITCH_TO_LOCATION_SETTINGS = "switchToLocationSettings";
private static final int SCAN_RESULTS_CODE = 0; // Permissions request code for getScanResults()
private static final int SCAN_CODE = 1; // Permissions request code for scan()
private static final int LOCATION_REQUEST_CODE = 2; // Permissions request code
private static final int WIFI_SERVICE_INFO_CODE = 3;
private static final String ACCESS_FINE_LOCATION = android.Manifest.permission.ACCESS_FINE_LOCATION;
private static int LAST_NET_ID = -1;
// This is for when SSID or BSSID is requested but permissions have not been granted for location
// we store whether or not BSSID was requested, to recall the getWifiServiceInfo fn after permissions are granted
private static boolean bssidRequested = false;
private WifiManager wifiManager;
private CallbackContext callbackContext;
private JSONArray passedData;
public static LocationManager locationManager;
private ConnectivityManager connectivityManager;
private ConnectivityManager.NetworkCallback networkCallback;
// Store AP, previous, and desired wifi info
private AP previous, desired;
private final BroadcastReceiver networkChangedReceiver = new NetworkChangedReceiver();
private static final IntentFilter NETWORK_STATE_CHANGED_FILTER = new IntentFilter();
static {
NETWORK_STATE_CHANGED_FILTER.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
}
/**
* WEP has two kinds of password, a hex value that specifies the key or a character string used to
* generate the real hex. This checks what kind of password has been supplied. The checks
* correspond to WEP40, WEP104 & WEP232
*/
private static boolean getHexKey(String s) {
if (s == null) {
return false;
}
int len = s.length();
if (len != 10 && len != 26 && len != 58) {
return false;
}
for (int i = 0; i < len; ++i) {
char c = s.charAt(i);
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
return false;
}
}
return true;
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.wifiManager = (WifiManager) cordova.getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
this.connectivityManager = (ConnectivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
this.locationManager = (LocationManager) cordova.getActivity().getSystemService(Context.LOCATION_SERVICE);
}
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext)
throws JSONException {
this.callbackContext = callbackContext;
this.passedData = data;
//>= 29
if(action.equals(SPECIFIER_NETWORK))
{
this.specifierConnection(callbackContext, data);
return true;
}
// Actions that do not require WiFi to be enabled
if (action.equals(IS_LOCATION_ENABLED)) {
this.isLocationEnabled(callbackContext);
return true;
} else if (action.equals(IS_WIFI_ENABLED)) {
this.isWifiEnabled(callbackContext);
return true;
} else if (action.equals(SWITCH_TO_LOCATION_SETTINGS)) {
this.switchToLocationSettings();
callbackContext.success();
return true;
} else if (action.equals(SET_WIFI_ENABLED)) {
this.setWifiEnabled(callbackContext, data);
return true;
} else if (action.equals(REQUEST_FINE_LOCATION)) {
this.requestLocationPermission(LOCATION_REQUEST_CODE);
return true;
} else if (action.equals(GET_WIFI_ROUTER_IP_ADDRESS)) {
String ip = getWiFiRouterIP();
if ( ip == null || ip.equals("0.0.0.0")) {
callbackContext.error("NO_VALID_ROUTER_IP_FOUND");
return true;
} else {
callbackContext.success(ip);
return true;
}
} else if (action.equals(GET_WIFI_IP_ADDRESS) || action.equals(GET_WIFI_IP_INFO)) {
String[] ipInfo = getWiFiIPAddress();
String ip = ipInfo[0];
String subnet = ipInfo[1];
if (ip == null || ip.equals("0.0.0.0")) {
callbackContext.error("NO_VALID_IP_IDENTIFIED");
return true;
}
// Return only IP address
if( action.equals( GET_WIFI_IP_ADDRESS ) ){
callbackContext.success(ip);
return true;
}
// Return Wifi IP Info (subnet and IP as JSON object)
JSONObject result = new JSONObject();
result.put("ip", ip);
result.put("subnet", subnet);
callbackContext.success(result);
return true;
}
boolean wifiIsEnabled = verifyWifiEnabled();
if (!wifiIsEnabled) {
callbackContext.error("WIFI_NOT_ENABLED");
return true; // Even though enable wifi failed, we still return true and handle error in callback
}
// Actions that DO require WiFi to be enabled
if (action.equals(ADD_NETWORK)) {
this.add(callbackContext, data);
} else if (action.equals(IS_CONNECTED_TO_INTERNET)) {
this.canConnectToInternet(callbackContext, true);
} else if (action.equals(CAN_CONNECT_TO_INTERNET)) {
this.canConnectToInternet(callbackContext, false);
} else if (action.equals(CAN_PING_WIFI_ROUTER)) {
this.canConnectToRouter(callbackContext, true);
} else if (action.equals(CAN_CONNECT_TO_ROUTER)) {
this.canConnectToRouter(callbackContext, false);
} else if (action.equals(ENABLE_NETWORK)) {
this.enable(callbackContext, data);
} else if (action.equals(DISABLE_NETWORK)) {
this.disable(callbackContext, data);
} else if (action.equals(GET_SSID_NET_ID)) {
this.getSSIDNetworkID(callbackContext, data);
} else if (action.equals(REASSOCIATE)) {
this.reassociate(callbackContext);
} else if (action.equals(RECONNECT)) {
this.reconnect(callbackContext);
} else if (action.equals(REMOVE_NETWORK)) {
this.remove(callbackContext, data);
} else if (action.equals(CONNECT_NETWORK)) {
this.connect(callbackContext, data);
} else if (action.equals(DISCONNECT_NETWORK)) {
this.disconnectNetwork(callbackContext, data);
} else if (action.equals(LIST_NETWORKS)) {
this.listNetworks(callbackContext);
} else if (action.equals(DISCONNECT)) {
this.disconnect(callbackContext);
} else if (action.equals(GET_CONNECTED_NETWORKID)) {
this.getConnectedNetworkID(callbackContext);
} else if (action.equals(SPECIFIER_NETWORK)) { // API >= 29
this.specifierConnection(callbackContext, data);
return true;
} else if (action.equals(SUGGEST_NETWORK)) { // API >= 29
this.suggestConnection(callbackContext, data);
return true;
} else {
// Check if location is globally enabled (and API 32 or newer)
if ( !locationIsEnabled() && API_VERSION >= 23 ) {
callbackContext.error("LOCATION_NOT_ENABLED");
return true; // We still return true and handle error in JS
}
// Actions that require LOCATION to be enabled
if (action.equals(SCAN)) {
this.scan(callbackContext, data);
} else if (action.equals(START_SCAN)) {
this.startScan(callbackContext);
} else if (action.equals(GET_SCAN_RESULTS)) {
this.getScanResults(callbackContext, data);
} else if (action.equals(GET_CONNECTED_SSID)) {
this.getConnectedSSID(callbackContext);
} else if (action.equals(GET_CONNECTED_BSSID)) {
this.getConnectedBSSID(callbackContext);
} else {
callbackContext.error("Incorrect action parameter: " + action);
// The ONLY time to return FALSE is when action does not exist that was called
// Returning false results in an INVALID_ACTION error, which translates to an error callback invoked on the JavaScript side
// All other errors should be handled with the fail callback (callbackContext.error)
// @see https://cordova.apache.org/docs/en/latest/guide/platforms/android/plugin.html
return false;
}
}
return true;
}
/**
* Scans networks and sends the list back on the success callback
*
* @param callbackContext A Cordova callback context
* @param data JSONArray with [0] == JSONObject
* @return true
*/
private boolean scan(final CallbackContext callbackContext, final JSONArray data) {
Log.v(TAG, "Entering startScan");
final ScanSyncContext syncContext = new ScanSyncContext();
final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Entering onReceive");
synchronized (syncContext) {
if (syncContext.finished) {
Log.v(TAG, "In onReceive, already finished");
return;
}
syncContext.finished = true;
context.unregisterReceiver(this);
}
Log.v(TAG, "In onReceive, success");
getScanResults(callbackContext, data);
}
};
final Context context = cordova.getActivity().getApplicationContext();
Log.v(TAG, "Submitting timeout to threadpool");
cordova.getThreadPool().submit(new Runnable() {
public void run() {
Log.v(TAG, "Entering timeout");
final int TEN_SECONDS = 10000;
try {
Thread.sleep(TEN_SECONDS);
} catch (InterruptedException e) {
Log.e(TAG, "Received InterruptedException e, " + e);
// keep going into error
}
Log.v(TAG, "Thread sleep done");
synchronized (syncContext) {
if (syncContext.finished) {
Log.v(TAG, "In timeout, already finished");
return;
}
syncContext.finished = true;
context.unregisterReceiver(receiver);
}
Log.v(TAG, "In timeout, error");
callbackContext.error("TIMEOUT_WAITING_FOR_SCAN");
}
});
Log.v(TAG, "Registering broadcastReceiver");
context.registerReceiver(
receiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
);
if (!wifiManager.startScan()) {
Log.v(TAG, "Scan failed");
callbackContext.error("SCAN_FAILED");
return false;
}
Log.v(TAG, "Starting wifi scan");
return true;
}
/**
* This methods adds a network to the list of available WiFi networks. If the network already
* exists, then it updates it.
*
* @return true if add successful, false if add fails
* @params callbackContext A Cordova callback context.
* @params data JSON Array with [0] == SSID, [1] == password
*/
private boolean add(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard2: add entered.");
// Initialize the WifiConfiguration object
WifiConfiguration wifi = new WifiConfiguration();
try {
// data's order for ANY object is
// 0: SSID
// 1: authentication algorithm,
// 2: authentication information
// 3: whether or not the SSID is hidden
String newSSID = data.getString(0);
String authType = data.getString(1);
String newPass = data.getString(2);
boolean isHiddenSSID = data.getBoolean(3);
wifi.hiddenSSID = isHiddenSSID;
if (authType.equals("WPA") || authType.equals("WPA2")) {
/**
* WPA Data format:
* 0: ssid
* 1: auth
* 2: password
* 3: isHiddenSSID
*/
wifi.SSID = newSSID;
wifi.preSharedKey = newPass;
wifi.status = WifiConfiguration.Status.ENABLED;
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifi.networkId = ssidToNetworkId(newSSID);
} else if (authType.equals("WEP")) {
/**
* WEP Data format:
* 0: ssid
* 1: auth
* 2: password
* 3: isHiddenSSID
*/
wifi.SSID = newSSID;
if (getHexKey(newPass)) {
wifi.wepKeys[0] = newPass;
} else {
wifi.wepKeys[0] = "\"" + newPass + "\"";
}
wifi.wepTxKeyIndex = 0;
wifi.status = WifiConfiguration.Status.ENABLED;
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifi.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifi.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifi.networkId = ssidToNetworkId(newSSID);
} else if (authType.equals("NONE")) {
/**
* OPEN Network data format:
* 0: ssid
* 1: auth
* 2: <not used>
* 3: isHiddenSSID
*/
wifi.SSID = newSSID;
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifi.networkId = ssidToNetworkId(newSSID);
} else {
Log.d(TAG, "Wifi Authentication Type Not Supported.");
callbackContext.error("AUTH_TYPE_NOT_SUPPORTED");
return false;
}
// Set network to highest priority (deprecated in API >= 26)
if( API_VERSION < 26 ){
wifi.priority = getMaxWifiPriority(wifiManager) + 1;
}
// After processing authentication types, add or update network
if (wifi.networkId == -1) { // -1 means SSID configuration does not exist yet
int newNetId = wifiManager.addNetwork(wifi);
if( newNetId > -1 ){
callbackContext.success( newNetId );
} else {
callbackContext.error( "ERROR_ADDING_NETWORK" );
}
} else {
int updatedNetID = wifiManager.updateNetwork(wifi);
if( updatedNetID > -1 ){
callbackContext.success( updatedNetID );
} else {
callbackContext.error( "ERROR_UPDATING_NETWORK" );
}
}
// WifiManager configurations are presistent for API 26+
if (API_VERSION < 26) {
wifiManager.saveConfiguration(); // Call saveConfiguration for older < 26 API
}
return true;
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
}
/**
* This method connects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
*/
private void enable(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard2: enable entered.");
if (!validateData(data)) {
callbackContext.error("ENABLE_INVALID_DATA");
Log.d(TAG, "WifiWizard2: enable invalid data.");
return;
}
String ssidToEnable = "";
String bindAll = "false";
String waitForConnection = "false";
try {
ssidToEnable = data.getString(0);
bindAll = data.getString(1);
waitForConnection = data.getString(2);
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return;
}
int networkIdToEnable = ssidToNetworkId(ssidToEnable);
try {
if (networkIdToEnable > -1) {
Log.d(TAG, "Valid networkIdToEnable: attempting connection");
// Bind all requests to WiFi network (only necessary for Lollipop+ - API 21+)
if( bindAll.equals("true") ){
registerBindALL(networkIdToEnable);
}
if( wifiManager.enableNetwork(networkIdToEnable, true) ){
if( waitForConnection.equals("true") ){
callbackContext.success("NETWORK_ENABLED");
return;
} else {
new ConnectAsync().execute(callbackContext, networkIdToEnable);
return;
}
} else {
callbackContext.error("ERROR_ENABLING_NETWORK");
return;
}
} else {
callbackContext.error("UNABLE_TO_ENABLE");
return;
}
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return;
}
}
/**
* This method disables a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean disable(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard2: disable entered.");
if (!validateData(data)) {
callbackContext.error("DISABLE_INVALID_DATA");
Log.d(TAG, "WifiWizard2: disable invalid data");
return false;
}
String ssidToDisable = "";
try {
ssidToDisable = data.getString(0);
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToDisconnect = ssidToNetworkId(ssidToDisable);
try {
if (networkIdToDisconnect > 0) {
if( wifiManager.disableNetwork(networkIdToDisconnect) ){
maybeResetBindALL();
callbackContext.success("Network " + ssidToDisable + " disabled!");
} else {
callbackContext.error("UNABLE_TO_DISABLE");
}
return true;
} else {
callbackContext.error("DISABLE_NETWORK_NOT_FOUND");
Log.d(TAG, "WifiWizard2: Network not found to disable.");
return false;
}
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
}
/**
* This method removes a network from the list of configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to remove
* @return true if network removed, false if failed
*/
private boolean remove(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard2: remove entered.");
if (!validateData(data)) {
callbackContext.error("REMOVE_INVALID_DATA");
Log.d(TAG, "WifiWizard2: remove data invalid");
return false;
}
// TODO: Verify the type of data!
try {
String ssidToDisconnect = data.getString(0);
int networkIdToRemove = ssidToNetworkId(ssidToDisconnect);
if (networkIdToRemove > -1) {
if( wifiManager.removeNetwork(networkIdToRemove) ){
// Configurations persist by default in API 26+
if (API_VERSION < 26) {
wifiManager.saveConfiguration();
}
callbackContext.success("NETWORK_REMOVED");
} else {
callbackContext.error( "UNABLE_TO_REMOVE" );
}
return true;
} else {
callbackContext.error("REMOVE_NETWORK_NOT_FOUND");
Log.d(TAG, "WifiWizard2: Network not found, can't remove.");
return false;
}
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
}
/**
* This method connects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
*/
private void connect(CallbackContext callbackContext, JSONArray data) {
Log.v(TAG, "WifiWizard2: connect entered.");
if (!validateData(data)) {
callbackContext.error("CONNECT_INVALID_DATA");
Log.d(TAG, "WifiWizard2: connect invalid data.");
return;
}
String ssidToConnect = "";
String bindAll = "false";
try {
ssidToConnect = data.getString(0);
bindAll = data.getString(1);
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return;
}
int networkIdToConnect = ssidToNetworkId(ssidToConnect);
if (networkIdToConnect > -1) {
// We disable the network before connecting, because if this was the last connection before
// a disconnect(), this will not reconnect.
Log.d(TAG, "Valid networkIdToConnect: attempting connection");
// Bind all requests to WiFi network (only necessary for Lollipop+ - API 21+)
if( bindAll.equals("true") ){
registerBindALL(networkIdToConnect);
}
if (API_VERSION >= 26) {
// wifiManager.disconnect();
} else {
wifiManager.disableNetwork(networkIdToConnect);
}
wifiManager.enableNetwork(networkIdToConnect, true);
if (API_VERSION >= 26) {
// wifiManager.reassociate();
}
new ConnectAsync().execute(callbackContext, networkIdToConnect);
return;
} else {
callbackContext.error("INVALID_NETWORK_ID_TO_CONNECT");
return;
}
}
/**
* Wait for connection before returning error or success
*
* This method will wait up to 60 seconds for WiFi connection to specified network ID be in COMPLETED state, otherwise will return error.
*
* @param callbackContext
* @param networkIdToConnect
* @return
*/
private class ConnectAsync extends AsyncTask<Object, Void, String[]> {
CallbackContext callbackContext;
@Override
protected void onPostExecute(String[] results) {
String error = results[0];
String success = results[1];
if (error != null) {
this.callbackContext.error(error);
} else {
this.callbackContext.success(success);
}
}
@Override
protected String[] doInBackground(Object... params) {
this.callbackContext = (CallbackContext) params[0];
int networkIdToConnect = (Integer) params[1];
final int TIMES_TO_RETRY = 15;
for (int i = 0; i < TIMES_TO_RETRY; i++) {
WifiInfo info = wifiManager.getConnectionInfo();
NetworkInfo.DetailedState connectionState = info
.getDetailedStateOf(info.getSupplicantState());
boolean isConnected =
// need to ensure we're on correct network because sometimes this code is
// reached before the initial network has disconnected
info.getNetworkId() == networkIdToConnect && (
connectionState == NetworkInfo.DetailedState.CONNECTED ||
// Android seems to sometimes get stuck in OBTAINING_IPADDR after it has received one
(connectionState == NetworkInfo.DetailedState.OBTAINING_IPADDR
&& info.getIpAddress() != 0)
);
if (isConnected) {
return new String[]{ null, "NETWORK_CONNECTION_COMPLETED" };
}
Log.d(TAG, "WifiWizard: Got " + connectionState.name() + " on " + (i + 1) + " out of " + TIMES_TO_RETRY);
final int ONE_SECOND = 1000;
try {
Thread.sleep(ONE_SECOND);
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
return new String[]{ "INTERRUPT_EXCEPT_WHILE_CONNECTING", null };
}
}
Log.d(TAG, "WifiWizard: Network failed to finish connecting within the timeout");
return new String[]{ "CONNECT_FAILED_TIMEOUT", null };
}
}
/**
* This method disconnects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard2: disconnectNetwork entered.");
if (!validateData(data)) {
callbackContext.error("DISCONNECT_NET_INVALID_DATA");
Log.d(TAG, "WifiWizard2: disconnectNetwork invalid data");
return false;
}
String ssidToDisconnect = "";
// TODO: Verify type of data here!
try {
ssidToDisconnect = data.getString(0);
} catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect);
if (networkIdToDisconnect > 0) {
if( wifiManager.disableNetwork(networkIdToDisconnect) ){
maybeResetBindALL();
// We also remove the configuration from the device (use "disable" to keep config)
if( wifiManager.removeNetwork(networkIdToDisconnect) ){
callbackContext.success("Network " + ssidToDisconnect + " disconnected and removed!");
} else {
callbackContext.error("DISCONNECT_NET_REMOVE_ERROR");
Log.d(TAG, "WifiWizard2: Unable to remove network!");
return false;
}
} else {
callbackContext.error("DISCONNECT_NET_DISABLE_ERROR");
Log.d(TAG, "WifiWizard2: Unable to disable network!");
return false;
}
return true;
} else {
callbackContext.error("DISCONNECT_NET_ID_NOT_FOUND");
Log.d(TAG, "WifiWizard2: Network not found to disconnect.");
return false;
}
}
/**
* This method disconnects the currently connected network.
*
* @param callbackContext A Cordova callback context
* @return true if network disconnected, false if failed
*/
private boolean disconnect(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard2: disconnect entered.");
if (wifiManager.disconnect()) {
maybeResetBindALL();
callbackContext.success("Disconnected from current network");
return true;
} else {
callbackContext.error("ERROR_DISCONNECT");
return false;
}
}
/**
* Reconnect Network
* <p>
* Reconnect to the currently active access point, if we are currently disconnected. This may
* result in the asynchronous delivery of state change events.
*/
private boolean reconnect(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard2: reconnect entered.");
if (wifiManager.reconnect()) {
callbackContext.success("Reconnected network");
return true;
} else {
callbackContext.error("ERROR_RECONNECT");
return false;
}
}
/**
* Reassociate Network
* <p>
* Reconnect to the currently active access point, even if we are already connected. This may
* result in the asynchronous delivery of state change events.
*/
private boolean reassociate(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard2: reassociate entered.");
if (wifiManager.reassociate()) {
callbackContext.success("Reassociated network");
return true;
} else {
callbackContext.error("ERROR_REASSOCIATE");
return false;
}
}
/**
* This method uses the callbackContext.success method to send a JSONArray of the currently
* configured networks.
*
* @param callbackContext A Cordova callback context
* @return true if network disconnected, false if failed
*/
private boolean listNetworks(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard2: listNetworks entered.");
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
JSONArray returnList = new JSONArray();
for (WifiConfiguration wifi : wifiList) {
returnList.put(wifi.SSID);
}
callbackContext.success(returnList);
return true;
}
/**
* This method uses the callbackContext.success method to send a JSONArray of the scanned
* networks.
*
* @param callbackContext A Cordova callback context
* @param data JSONArray with [0] == JSONObject
* @return true
*/
private boolean getScanResults(CallbackContext callbackContext, JSONArray data) {
if (cordova.hasPermission(ACCESS_FINE_LOCATION)) {
List<ScanResult> scanResults = wifiManager.getScanResults();
JSONArray returnList = new JSONArray();
Integer numLevels = null;
if (!validateData(data)) {
callbackContext.error("GET_SCAN_RESULTS_INVALID_DATA");
Log.d(TAG, "WifiWizard2: getScanResults invalid data");
return false;
} else if (!data.isNull(0)) {
try {
JSONObject options = data.getJSONObject(0);
if (options.has("numLevels")) {
Integer levels = options.optInt("numLevels");
if (levels > 0) {
numLevels = levels;