From 6c79ea81cad6d7b80c494de22268d6e18ab46b3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Vytla=C4=8Dil?= Date: Thu, 15 Jul 2021 15:12:36 +0200 Subject: [PATCH 1/4] Update WifiWizard2.java Add function getMacAddress --- src/android/wifiwizard2/WifiWizard2.java | 1297 ++++++++++++---------- 1 file changed, 698 insertions(+), 599 deletions(-) diff --git a/src/android/wifiwizard2/WifiWizard2.java b/src/android/wifiwizard2/WifiWizard2.java index f3c57b8..685a8c4 100644 --- a/src/android/wifiwizard2/WifiWizard2.java +++ b/src/android/wifiwizard2/WifiWizard2.java @@ -17,7 +17,8 @@ import org.apache.cordova.*; import java.util.List; -import java.util.concurrent.Future; +import java.util.Collections; +import java.util.concurrent.Future; import java.lang.InterruptedException; import org.json.JSONArray; @@ -95,9 +96,9 @@ public class WifiWizard2 extends CordovaPlugin { private static final String RESET_BIND_ALL = "resetBindAll"; private static final String SET_BIND_ALL = "setBindAll"; private static final String GET_WIFI_IP_INFO = "getWifiIPInfo"; + private static final String GET_MAC_ADDRESS = "getMacAddress"; - 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 @@ -159,7 +160,7 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) { @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) - throws JSONException { + throws JSONException { this.callbackContext = callbackContext; this.passedData = data; @@ -177,8 +178,9 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo } else if (action.equals(GET_WIFI_ROUTER_IP_ADDRESS)) { String ip = getWiFiRouterIP(); + String macAddress = getMacAddress(); - if ( ip == null || ip.equals("0.0.0.0")) { + if (ip == null || ip.equals("0.0.0.0")) { callbackContext.error("NO_VALID_ROUTER_IP_FOUND"); return true; } else { @@ -196,7 +198,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo } // Return only IP address - if( action.equals( GET_WIFI_IP_ADDRESS ) ){ + if (action.equals(GET_WIFI_IP_ADDRESS)) { callbackContext.success(ip); return true; } @@ -206,81 +208,140 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result.put("ip", ip); result.put("subnet", subnet); + result.put("macAddress", macAddress); 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(SCAN)) { - this.scan(callbackContext, data); - } 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(START_SCAN)) { - this.startScan(callbackContext); - } else if (action.equals(GET_SCAN_RESULTS)) { - this.getScanResults(callbackContext, data); - } else if (action.equals(DISCONNECT)) { - this.disconnect(callbackContext); - } else if (action.equals(GET_CONNECTED_SSID)) { - this.getConnectedSSID(callbackContext); - } else if (action.equals(GET_CONNECTED_BSSID)) { - this.getConnectedBSSID(callbackContext); - } else if (action.equals(GET_CONNECTED_NETWORKID)) { - this.getConnectedNetworkID(callbackContext); - } else if (action.equals(RESET_BIND_ALL)) { - this.resetBindAll(callbackContext); - } else if (action.equals(SET_BIND_ALL)) { - this.setBindAll(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; - } + } else if(action.equals(GET_MAC_ADDRESS)) + { + String macAddress = getMacAddress(); + callbackContext.success(macAddress); 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(SCAN)) + + { + this.scan(callbackContext, data); + } 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(START_SCAN)) + + { + this.startScan(callbackContext); + } else if(action.equals(GET_SCAN_RESULTS)) + + { + this.getScanResults(callbackContext, data); + } else if(action.equals(DISCONNECT)) + + { + this.disconnect(callbackContext); + } else if(action.equals(GET_CONNECTED_SSID)) + + { + this.getConnectedSSID(callbackContext); + } else if(action.equals(GET_CONNECTED_BSSID)) + + { + this.getConnectedBSSID(callbackContext); + } else if(action.equals(GET_CONNECTED_NETWORKID)) + + { + this.getConnectedNetworkID(callbackContext); + } else if(action.equals(RESET_BIND_ALL)) + + { + this.resetBindAll(callbackContext); + } else if(action.equals(SET_BIND_ALL)) + + { + this.setBindAll(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 + * @param data JSONArray with [0] == JSONObject * @return true */ private boolean scan(final CallbackContext callbackContext, final JSONArray data) { @@ -343,8 +404,8 @@ public void run() { Log.v(TAG, "Registering broadcastReceiver"); context.registerReceiver( - receiver, - new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) + receiver, + new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) ); if (!wifiManager.startScan()) { @@ -386,13 +447,13 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { wifi.hiddenSSID = isHiddenSSID; if (authType.equals("WPA") || authType.equals("WPA2")) { - /** - * WPA Data format: - * 0: ssid - * 1: auth - * 2: password - * 3: isHiddenSSID - */ + /** + * WPA Data format: + * 0: ssid + * 1: auth + * 2: password + * 3: isHiddenSSID + */ wifi.SSID = newSSID; wifi.preSharedKey = newPass; @@ -408,13 +469,13 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { wifi.networkId = ssidToNetworkId(newSSID); } else if (authType.equals("WEP")) { - /** - * WEP Data format: - * 0: ssid - * 1: auth - * 2: password - * 3: isHiddenSSID - */ + /** + * WEP Data format: + * 0: ssid + * 1: auth + * 2: password + * 3: isHiddenSSID + */ wifi.SSID = newSSID; if (getHexKey(newPass)) { @@ -440,13 +501,13 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { wifi.networkId = ssidToNetworkId(newSSID); } else if (authType.equals("NONE")) { - /** - * OPEN Network data format: - * 0: ssid - * 1: auth - * 2: - * 3: isHiddenSSID - */ + /** + * OPEN Network data format: + * 0: ssid + * 1: auth + * 2: + * 3: isHiddenSSID + */ wifi.SSID = newSSID; wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifi.networkId = ssidToNetworkId(newSSID); @@ -460,11 +521,11 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { } // Set network to highest priority (deprecated in API >= 26) - if(API_VERSION < 26) { + if (API_VERSION < 26) { wifi.priority = getMaxWifiPriority(wifiManager) + 1; } - if(API_VERSION >= 29) { + if (API_VERSION >= 29) { this.networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { @@ -472,11 +533,12 @@ public void onAvailable(Network network) { Log.d(TAG, "WiFi connected"); callbackContext.success("WiFi connected"); } + @Override public void onUnavailable() { - super.onUnavailable(); - Log.d(TAG, "WiFi not available"); - callbackContext.error("WiFi not available"); + super.onUnavailable(); + Log.d(TAG, "WiFi not available"); + callbackContext.error("WiFi not available"); } }; @@ -498,21 +560,21 @@ public void onUnavailable() { cm.requestNetwork(nr, this.networkCallback, 15000); } else { // After processing authentication types, add or update network - if(wifi.networkId == -1) { // -1 means SSID configuration does not exist yet + if (wifi.networkId == -1) { // -1 means SSID configuration does not exist yet int newNetId = wifiManager.addNetwork(wifi); - if( newNetId > -1 ){ - callbackContext.success( newNetId ); + if (newNetId > -1) { + callbackContext.success(newNetId); } else { - callbackContext.error( "ERROR_ADDING_NETWORK" ); + callbackContext.error("ERROR_ADDING_NETWORK"); } } else { int updatedNetID = wifiManager.updateNetwork(wifi); - if(updatedNetID > -1) { - callbackContext.success( updatedNetID ); + if (updatedNetID > -1) { + callbackContext.success(updatedNetID); } else { callbackContext.error("ERROR_UPDATING_NETWORK"); } @@ -521,7 +583,7 @@ public void onUnavailable() { } // WifiManager configurations are presistent for API 26+ - if(API_VERSION < 26) { + if (API_VERSION < 26) { wifiManager.saveConfiguration(); // Call saveConfiguration for older < 26 API } @@ -539,7 +601,7 @@ public void onUnavailable() { * This method connects a network. * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @param data JSON Array, with [0] being SSID to connect */ private void enable(CallbackContext callbackContext, JSONArray data) { Log.d(TAG, "WifiWizard2: enable entered."); @@ -568,18 +630,18 @@ private void enable(CallbackContext callbackContext, JSONArray data) { try { - if(networkIdToEnable > -1) { + 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")) { + if (bindAll.equals("true")) { registerBindALL(networkIdToEnable); } - if(wifiManager.enableNetwork(networkIdToEnable, true)) { + if (wifiManager.enableNetwork(networkIdToEnable, true)) { - if( waitForConnection.equals("true") ){ + if (waitForConnection.equals("true")) { callbackContext.success("NETWORK_ENABLED"); return; } else { @@ -609,7 +671,7 @@ private void enable(CallbackContext callbackContext, JSONArray data) { * This method disables a network. * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @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) { @@ -636,7 +698,7 @@ private boolean disable(CallbackContext callbackContext, JSONArray data) { try { if (networkIdToDisconnect > 0) { - if(wifiManager.disableNetwork(networkIdToDisconnect)){ + if (wifiManager.disableNetwork(networkIdToDisconnect)) { maybeResetBindALL(); callbackContext.success("Network " + ssidToDisable + " disabled!"); } else { @@ -662,7 +724,7 @@ private boolean disable(CallbackContext callbackContext, JSONArray data) { * 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 + * @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) { @@ -682,19 +744,19 @@ private boolean remove(CallbackContext callbackContext, JSONArray data) { if (networkIdToRemove > -1) { - if( wifiManager.removeNetwork(networkIdToRemove) ){ + if (wifiManager.removeNetwork(networkIdToRemove)) { - // Configurations persist by default in API 26+ - if (API_VERSION < 26) { - wifiManager.saveConfiguration(); - } + // Configurations persist by default in API 26+ + if (API_VERSION < 26) { + wifiManager.saveConfiguration(); + } - callbackContext.success("NETWORK_REMOVED"); + callbackContext.success("NETWORK_REMOVED"); - } else { + } else { - callbackContext.error( "UNABLE_TO_REMOVE" ); - } + callbackContext.error("UNABLE_TO_REMOVE"); + } return true; } else { @@ -713,7 +775,7 @@ private boolean remove(CallbackContext callbackContext, JSONArray data) { * This method connects a network. * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @param data JSON Array, with [0] being SSID to connect */ private void connect(CallbackContext callbackContext, JSONArray data) { Log.d(TAG, "WifiWizard2: connect entered."); @@ -745,7 +807,7 @@ private void connect(CallbackContext callbackContext, JSONArray data) { Log.d(TAG, "Valid networkIdToConnect: attempting connection"); // Bind all requests to WiFi network (only necessary for Lollipop+ - API 21+) - if( bindAll.equals("true") ){ + if (bindAll.equals("true")) { registerBindALL(networkIdToConnect); } @@ -770,74 +832,76 @@ private void connect(CallbackContext callbackContext, JSONArray data) { } } - /** - * 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 { - 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]; +/** + * 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 { + CallbackContext callbackContext; - final int TIMES_TO_RETRY = 15; - for (int i = 0; i < TIMES_TO_RETRY; i++) { + @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); + } + } - WifiInfo info = wifiManager.getConnectionInfo(); - NetworkInfo.DetailedState connectionState = info - .getDetailedStateOf(info.getSupplicantState()); + @Override + protected String[] doInBackground(Object... params) { + this.callbackContext = (CallbackContext) params[0]; + int networkIdToConnect = (Integer) params[1]; - 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) - ); + final int TIMES_TO_RETRY = 15; + for (int i = 0; i < TIMES_TO_RETRY; i++) { - if (isConnected) { - return new String[]{ null, "NETWORK_CONNECTION_COMPLETED" }; - } + 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; + 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 }; - } + 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 }; } + 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 + * @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) { @@ -859,17 +923,17 @@ private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray dat return false; } - if(API_VERSION < 29){ - int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect); + if (API_VERSION < 29) { + int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect); - if(networkIdToDisconnect > 0) { + if (networkIdToDisconnect > 0) { - if(wifiManager.disableNetwork(networkIdToDisconnect)) { + if (wifiManager.disableNetwork(networkIdToDisconnect)) { maybeResetBindALL(); // We also remove the configuration from the device (use "disable" to keep config) - if( wifiManager.removeNetwork(networkIdToDisconnect) ){ + if (wifiManager.removeNetwork(networkIdToDisconnect)) { callbackContext.success("Network " + ssidToDisconnect + " disconnected and removed!"); } else { callbackContext.error("DISCONNECT_NET_REMOVE_ERROR"); @@ -884,23 +948,22 @@ private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray dat } return true; + } else { + callbackContext.error("DISCONNECT_NET_ID_NOT_FOUND"); + Log.d(TAG, "WifiWizard2: Network not found to disconnect."); + return false; + } } else { - callbackContext.error("DISCONNECT_NET_ID_NOT_FOUND"); - Log.d(TAG, "WifiWizard2: Network not found to disconnect."); - return false; - } - } else { - try{ - ConnectivityManager cm = (ConnectivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); - cm.unregisterNetworkCallback(this.networkCallback); - connectivityManager.bindProcessToNetwork(null); - return true; - } - catch(Exception e) { - callbackContext.error(e.getMessage()); - return false; - } + try { + ConnectivityManager cm = (ConnectivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); + cm.unregisterNetworkCallback(this.networkCallback); + connectivityManager.bindProcessToNetwork(null); + return true; + } catch (Exception e) { + callbackContext.error(e.getMessage()); + return false; } + } } /** @@ -985,7 +1048,7 @@ private boolean listNetworks(CallbackContext callbackContext) { * networks. * * @param callbackContext A Cordova callback context - * @param data JSONArray with [0] == JSONObject + * @param data JSONArray with [0] == JSONObject * @return true */ private boolean getScanResults(CallbackContext callbackContext, JSONArray data) { @@ -1076,7 +1139,7 @@ private boolean getScanResults(CallbackContext callbackContext, JSONArray data) } else { requestLocationPermission(SCAN_RESULTS_CODE); - return true; + return true; } } @@ -1126,7 +1189,7 @@ private int getConnectedNetId() { * Get Network ID from SSID * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @param data JSON Array, with [0] being SSID to connect * @return true if network connected, false if failed */ private boolean getSSIDNetworkID(CallbackContext callbackContext, JSONArray data) { @@ -1199,7 +1262,7 @@ private boolean getConnectedBSSID(CallbackContext callbackContext) { * @param basicIdentifier A flag to get BSSID if true or SSID if false. * @return true if SSID found, false if not. */ - private boolean getWifiServiceInfo(CallbackContext callbackContext, boolean basicIdentifier) { + private boolean getWifiServiceInfo(CallbackContext callbackContext, boolean basicIdentifier) { if (API_VERSION >= 23 && !cordova.hasPermission(ACCESS_FINE_LOCATION)) { //Android 9 (Pie) or newer requestLocationPermission(WIFI_SERVICE_INFO_CODE); bssidRequested = basicIdentifier; @@ -1211,511 +1274,543 @@ private boolean getWifiServiceInfo(CallbackContext callbackContext, boolean basi callbackContext.error("UNABLE_TO_READ_WIFI_INFO"); return false; } - + // Only return SSID or BSSID when actually connected to a network SupplicantState state = info.getSupplicantState(); if (!state.equals(SupplicantState.COMPLETED)) { callbackContext.error("CONNECTION_NOT_COMPLETED"); return false; } - + String serviceInfo; if (basicIdentifier) { serviceInfo = info.getBSSID(); } else { serviceInfo = info.getSSID(); } - + if (serviceInfo == null || serviceInfo.isEmpty() || serviceInfo == "0x") { callbackContext.error("WIFI_INFORMATION_EMPTY"); return false; } - + // http://developer.android.com/reference/android/net/wifi/WifiInfo.html#getSSID() if (serviceInfo.startsWith("\"") && serviceInfo.endsWith("\"")) { serviceInfo = serviceInfo.substring(1, serviceInfo.length() - 1); } - + callbackContext.success(serviceInfo); return true; } } /** - * This method retrieves the current WiFi status + * This method return mac address * - * @param callbackContext A Cordova callback context - * @return true if WiFi is enabled, fail will be called if not. + * @return mac address */ - private boolean isWifiEnabled(CallbackContext callbackContext) { - boolean isEnabled = wifiManager.isWifiEnabled(); - callbackContext.success(isEnabled ? "1" : "0"); - return isEnabled; + private String getMacAddress() { + try { + String interfaceName = "wlan0"; + List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); + for (NetworkInterface intf : interfaces) { + if (!intf.getName().equalsIgnoreCase(interfaceName)) { + continue; + } + + byte[] mac = intf.getHardwareAddress(); + if (mac == null) { + return ""; + } + + StringBuilder buf = new StringBuilder(); + for (byte aMac : mac) { + buf.append(String.format("%02X:", aMac)); + } + if (buf.length() > 0) { + buf.deleteCharAt(buf.length() - 1); + } + return buf.toString(); + } + } catch (Exception ex) { + } + return ""; } +} - /** - * This method takes a given String, searches the current list of configured WiFi networks, and - * returns the networkId for the network if the SSID matches. If not, it returns -1. - */ - private int ssidToNetworkId(String ssid) { +/** + * This method retrieves the current WiFi status + * + * @param callbackContext A Cordova callback context + * @return true if WiFi is enabled, fail will be called if not. + */ +private boolean isWifiEnabled(CallbackContext callbackContext){ + boolean isEnabled=wifiManager.isWifiEnabled(); + callbackContext.success(isEnabled?"1":"0"); + return isEnabled; + } - try { - - int maybeNetId = Integer.parseInt(ssid); - Log.d(TAG, "ssidToNetworkId passed SSID is integer, probably a Network ID: " + ssid); - return maybeNetId; +/** + * This method takes a given String, searches the current list of configured WiFi networks, and + * returns the networkId for the network if the SSID matches. If not, it returns -1. + */ +private int ssidToNetworkId(String ssid){ + + try{ + + int maybeNetId=Integer.parseInt(ssid); + Log.d(TAG,"ssidToNetworkId passed SSID is integer, probably a Network ID: "+ssid); + return maybeNetId; - } catch (NumberFormatException e) { + }catch(NumberFormatException e){ - List currentNetworks = wifiManager.getConfiguredNetworks(); - int networkId = -1; + List currentNetworks=wifiManager.getConfiguredNetworks(); + int networkId=-1; - // For each network in the list, compare the SSID with the given one - for (WifiConfiguration test : currentNetworks) { - if (test.SSID != null && test.SSID.equals(ssid)) { - networkId = test.networkId; + // For each network in the list, compare the SSID with the given one + for(WifiConfiguration test:currentNetworks){ + if(test.SSID!=null&&test.SSID.equals(ssid)){ + networkId=test.networkId; + } } - } - return networkId; + return networkId; - } - } + } + } - /** - * This method enables or disables the wifi - */ - private boolean setWifiEnabled(CallbackContext callbackContext, JSONArray data) { - if (!validateData(data)) { - callbackContext.error("SETWIFIENABLED_INVALID_DATA"); - Log.d(TAG, "WifiWizard2: setWifiEnabled invalid data"); - return false; - } +/** + * This method enables or disables the wifi + */ +private boolean setWifiEnabled(CallbackContext callbackContext,JSONArray data){ + if(!validateData(data)){ + callbackContext.error("SETWIFIENABLED_INVALID_DATA"); + Log.d(TAG,"WifiWizard2: setWifiEnabled invalid data"); + return false; + } - String status = ""; + String status=""; - try { - status = data.getString(0); - } catch (Exception e) { - callbackContext.error(e.getMessage()); - Log.d(TAG, e.getMessage()); - return false; - } + try{ + status=data.getString(0); + }catch(Exception e){ + callbackContext.error(e.getMessage()); + Log.d(TAG,e.getMessage()); + return false; + } - if (wifiManager.setWifiEnabled(status.equals("true"))) { - callbackContext.success(); - return true; - } else { - callbackContext.error("ERROR_SETWIFIENABLED"); - return false; - } - } + if(wifiManager.setWifiEnabled(status.equals("true"))){ + callbackContext.success(); + return true; + }else{ + callbackContext.error("ERROR_SETWIFIENABLED"); + return false; + } + } - /** - * This method will check if WiFi is enabled, and enable it if not, waiting up to 10 seconds for - * it to enable - * - * @return True if wifi is enabled, false if unable to enable wifi - */ - private boolean verifyWifiEnabled() { +/** + * This method will check if WiFi is enabled, and enable it if not, waiting up to 10 seconds for + * it to enable + * + * @return True if wifi is enabled, false if unable to enable wifi + */ +private boolean verifyWifiEnabled(){ - Log.d(TAG, "WifiWizard2: verifyWifiEnabled entered."); + Log.d(TAG,"WifiWizard2: verifyWifiEnabled entered."); - if (!wifiManager.isWifiEnabled()) { + if(!wifiManager.isWifiEnabled()){ - Log.i(TAG, "Enabling wi-fi..."); + Log.i(TAG,"Enabling wi-fi..."); - if (wifiManager.setWifiEnabled(true)) { - Log.i(TAG, "Wi-fi enabled"); - } else { - Log.e(TAG, "VERIFY_ERROR_ENABLE_WIFI"); + if(wifiManager.setWifiEnabled(true)){ + Log.i(TAG,"Wi-fi enabled"); + }else{ + Log.e(TAG,"VERIFY_ERROR_ENABLE_WIFI"); return false; - } + } - // This happens very quickly, but need to wait for it to enable. A little busy wait? - int count = 0; + // This happens very quickly, but need to wait for it to enable. A little busy wait? + int count=0; - while (!wifiManager.isWifiEnabled()) { - if (count >= 10) { - Log.i(TAG, "Took too long to enable wi-fi, quitting"); - return false; + while(!wifiManager.isWifiEnabled()){ + if(count>=10){ + Log.i(TAG,"Took too long to enable wi-fi, quitting"); + return false; } - Log.i(TAG, "Still waiting for wi-fi to enable..."); + Log.i(TAG,"Still waiting for wi-fi to enable..."); - try { - Thread.sleep(1000L); - } catch (InterruptedException ie) { - // continue + try{ + Thread.sleep(1000L); + }catch(InterruptedException ie){ + // continue } count++; - } + } - // If we make it this far, wifi should be enabled by now - return true; + // If we make it this far, wifi should be enabled by now + return true; - } else { + }else{ - return true; + return true; - } + } - } + } - /** - * Format and return WiFi IPv4 Address - * @return - */ - private String[] getWiFiIPAddress() { - WifiInfo wifiInfo = wifiManager.getConnectionInfo(); - int ip = wifiInfo.getIpAddress(); +/** + * Format and return WiFi IPv4 Address + * @return + */ +private String[]getWiFiIPAddress(){ + WifiInfo wifiInfo=wifiManager.getConnectionInfo(); + int ip=wifiInfo.getIpAddress(); - String ipString = formatIP(ip); - String subnet = ""; + String ipString=formatIP(ip); + String subnet=""; - try { - InetAddress inetAddress = InetAddress.getByName(ipString); - subnet = getIPv4Subnet(inetAddress); - } catch (Exception e) { - } + try{ + InetAddress inetAddress=InetAddress.getByName(ipString); + subnet=getIPv4Subnet(inetAddress); + }catch(Exception e){ + } - return new String[]{ipString, subnet}; - } + return new String[]{ipString,subnet}; + } - /** - * Get WiFi Router IP from DHCP - * @return - */ - private String getWiFiRouterIP() { - DhcpInfo dhcp = wifiManager.getDhcpInfo(); - int ip = dhcp.gateway; - return formatIP(ip); - } +/** + * Get WiFi Router IP from DHCP + * @return + */ +private String getWiFiRouterIP(){ + DhcpInfo dhcp=wifiManager.getDhcpInfo(); + int ip=dhcp.gateway; + return formatIP(ip); + } - /** - * Format IPv4 Address - * @param ip - * @return - */ - private String formatIP(int ip) { - return String.format( +/** + * Format IPv4 Address + * @param ip + * @return + */ +private String formatIP(int ip){ + return String.format( "%d.%d.%d.%d", - (ip & 0xff), - (ip >> 8 & 0xff), - (ip >> 16 & 0xff), - (ip >> 24 & 0xff) - ); - } + (ip&0xff), + (ip>>8&0xff), + (ip>>16&0xff), + (ip>>24&0xff) + ); + } - /** - * Get IPv4 Subnet - * @param inetAddress - * @return - */ - public static String getIPv4Subnet(InetAddress inetAddress) { - try { - NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress); - List intAddrs = ni.getInterfaceAddresses(); - for (InterfaceAddress ia : intAddrs) { - if (!ia.getAddress().isLoopbackAddress() && ia.getAddress() instanceof Inet4Address) { - return getIPv4SubnetFromNetPrefixLength(ia.getNetworkPrefixLength()).getHostAddress() - .toString(); +/** + * Get IPv4 Subnet + * @param inetAddress + * @return + */ +public static String getIPv4Subnet(InetAddress inetAddress){ + try{ + NetworkInterface ni=NetworkInterface.getByInetAddress(inetAddress); + List intAddrs=ni.getInterfaceAddresses(); + for(InterfaceAddress ia:intAddrs){ + if(!ia.getAddress().isLoopbackAddress()&&ia.getAddress()instanceof Inet4Address){ + return getIPv4SubnetFromNetPrefixLength(ia.getNetworkPrefixLength()).getHostAddress() + .toString(); + } + } + }catch(Exception e){ + } + return""; } - } - } catch (Exception e) { - } - return ""; - } - /** - * Get Subnet from Prefix Length - * @param netPrefixLength - * @return - */ - public static InetAddress getIPv4SubnetFromNetPrefixLength(int netPrefixLength) { - try { - int shift = (1 << 31); - for (int i = netPrefixLength - 1; i > 0; i--) { - shift = (shift >> 1); - } - String subnet = - Integer.toString((shift >> 24) & 255) + "." + Integer.toString((shift >> 16) & 255) + "." - + Integer.toString((shift >> 8) & 255) + "." + Integer.toString(shift & 255); - return InetAddress.getByName(subnet); - } catch (Exception e) { - } - return null; - } +/** + * Get Subnet from Prefix Length + * @param netPrefixLength + * @return + */ +public static InetAddress getIPv4SubnetFromNetPrefixLength(int netPrefixLength){ + try{ + int shift=(1<<31); + for(int i=netPrefixLength-1;i>0;i--){ + shift=(shift>>1); + } + String subnet= + Integer.toString((shift>>24)&255)+"."+Integer.toString((shift>>16)&255)+"." + +Integer.toString((shift>>8)&255)+"."+Integer.toString(shift&255); + return InetAddress.getByName(subnet); + }catch(Exception e){ + } + return null; + } - /** - * Validate JSON data - */ - private boolean validateData(JSONArray data) { - try { - if (data == null || data.get(0) == null) { +/** + * Validate JSON data + */ +private boolean validateData(JSONArray data){ + try{ + if(data==null||data.get(0)==null){ callbackContext.error("DATA_IS_NULL"); return false; - } - return true; - } catch (Exception e) { - callbackContext.error(e.getMessage()); - } - return false; - } + } + return true; + }catch(Exception e){ + callbackContext.error(e.getMessage()); + } + return false; + } - /** - * Request ACCESS_FINE_LOCATION Permission - * @param requestCode - */ - protected void requestLocationPermission(int requestCode) { - cordova.requestPermission(this, requestCode, ACCESS_FINE_LOCATION); - } +/** + * Request ACCESS_FINE_LOCATION Permission + * @param requestCode + */ +protected void requestLocationPermission(int requestCode){ + cordova.requestPermission(this,requestCode,ACCESS_FINE_LOCATION); + } - /** - * Handle Android Permission Requests - */ - public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) - throws JSONException { +/** + * Handle Android Permission Requests + */ +public void onRequestPermissionResult(int requestCode,String[]permissions,int[]grantResults) + throws JSONException{ - for (int r : grantResults) { - if (r == PackageManager.PERMISSION_DENIED) { - callbackContext.error( "PERMISSION_DENIED" ); + for(int r:grantResults){ + if(r==PackageManager.PERMISSION_DENIED){ + callbackContext.error("PERMISSION_DENIED"); return; - } - } + } + } - switch (requestCode) { - case SCAN_RESULTS_CODE: - getScanResults(callbackContext, passedData); // Call method again after permissions approved + switch(requestCode){ + case SCAN_RESULTS_CODE: + getScanResults(callbackContext,passedData); // Call method again after permissions approved break; - case SCAN_CODE: - scan(callbackContext, passedData); // Call method again after permissions approved + case SCAN_CODE: + scan(callbackContext,passedData); // Call method again after permissions approved break; - case LOCATION_REQUEST_CODE: + case LOCATION_REQUEST_CODE: callbackContext.success("PERMISSION_GRANTED"); break; - case WIFI_SERVICE_INFO_CODE: - getWifiServiceInfo(callbackContext, bssidRequested); + case WIFI_SERVICE_INFO_CODE: + getWifiServiceInfo(callbackContext,bssidRequested); break; - } - } + } + } - /** - * Figure out what the highest priority network in the network list is and return that priority - */ - private static int getMaxWifiPriority(final WifiManager wifiManager) { - final List configurations = wifiManager.getConfiguredNetworks(); - int maxPriority = 0; - for (WifiConfiguration config : configurations) { - if (config.priority > maxPriority) { - maxPriority = config.priority; - } - } +/** + * Figure out what the highest priority network in the network list is and return that priority + */ +private static int getMaxWifiPriority(final WifiManager wifiManager){ +final List configurations=wifiManager.getConfiguredNetworks(); + int maxPriority=0; + for(WifiConfiguration config:configurations){ + if(config.priority>maxPriority){ + maxPriority=config.priority; + } + } - Log.d(TAG, "WifiWizard: Found max WiFi priority of " - + maxPriority); + Log.d(TAG,"WifiWizard: Found max WiFi priority of " + +maxPriority); - return maxPriority; - } + return maxPriority; + } - /** - * Check if device is connected to Internet - */ - private boolean canConnectToInternet(CallbackContext callbackContext, boolean doPing) { +/** + * Check if device is connected to Internet + */ +private boolean canConnectToInternet(CallbackContext callbackContext,boolean doPing){ - try { + try{ - if ( hasInternetConnection(doPing) ) { + if(hasInternetConnection(doPing)){ // Send success as 1 to return true from Promise (handled in JS) callbackContext.success("1"); return true; - } else { + }else{ callbackContext.success("0"); return false; - } + } - } catch (Exception e) { - callbackContext.error(e.getMessage()); - Log.d(TAG, e.getMessage()); - return false; - } - } + }catch(Exception e){ + callbackContext.error(e.getMessage()); + Log.d(TAG,e.getMessage()); + return false; + } + } - /** - * Check if we can conenct to router via HTTP connection - * - * @param callbackContext - * @param doPing - * @return boolean - */ - private boolean canConnectToRouter(CallbackContext callbackContext, boolean doPing) { +/** + * Check if we can conenct to router via HTTP connection + * + * @param callbackContext + * @param doPing + * @return boolean + */ +private boolean canConnectToRouter(CallbackContext callbackContext,boolean doPing){ - try { + try{ - if (hasConnectionToRouter(doPing)) { + if(hasConnectionToRouter(doPing)){ // Send success as 1 to return true from Promise (handled in JS) callbackContext.success("1"); return true; - } else { + }else{ callbackContext.success("0"); return false; - } + } - } catch (Exception e) { - callbackContext.error(e.getMessage()); - Log.d(TAG, e.getMessage()); - return false; - } - } + }catch(Exception e){ + callbackContext.error(e.getMessage()); + Log.d(TAG,e.getMessage()); + return false; + } + } - /** - * Check if The Device Is Connected to Internet - * - * @return true if device connect to Internet or return false if not - */ - public boolean hasInternetConnection(boolean doPing) { - if (connectivityManager != null) { - NetworkInfo info = connectivityManager.getActiveNetworkInfo(); - if (info != null) { - if (info.isConnected()) { - if( doPing ){ - return pingCmd("8.8.8.8"); - } else { - return isHTTPreachable("http://www.google.com/"); - } +/** + * Check if The Device Is Connected to Internet + * + * @return true if device connect to Internet or return false if not + */ +public boolean hasInternetConnection(boolean doPing){ + if(connectivityManager!=null){ + NetworkInfo info=connectivityManager.getActiveNetworkInfo(); + if(info!=null){ + if(info.isConnected()){ + if(doPing){ + return pingCmd("8.8.8.8"); + }else{ + return isHTTPreachable("http://www.google.com/"); + } + } + } + } + return false; } - } - } - return false; - } - /** - * Check for connection to router by pinging router IP - * @return - */ - public boolean hasConnectionToRouter( boolean doPing ) { +/** + * Check for connection to router by pinging router IP + * @return + */ +public boolean hasConnectionToRouter(boolean doPing){ - String ip = getWiFiRouterIP(); + String ip=getWiFiRouterIP(); - if ( ip == null || ip.equals("0.0.0.0") || connectivityManager == null) { + if(ip==null||ip.equals("0.0.0.0")||connectivityManager==null){ - return false; + return false; - } else { + }else{ - NetworkInfo info = connectivityManager.getActiveNetworkInfo(); + NetworkInfo info=connectivityManager.getActiveNetworkInfo(); - if (info != null && info.isConnected()) { + if(info!=null&&info.isConnected()){ - if( doPing ){ - return pingCmd(ip); - } else { - return isHTTPreachable("http://" + ip + "/"); + if(doPing){ + return pingCmd(ip); + }else{ + return isHTTPreachable("http://"+ip+"/"); } - } else { + }else{ return false; - } + } - } + } - } + } - /** - * Check if HTTP connection to URL is reachable - * - * @param checkURL - * @return boolean - */ - public static boolean isHTTPreachable(String checkURL) { - try { - // make a URL to a known source - URL url = new URL(checkURL); +/** + * Check if HTTP connection to URL is reachable + * + * @param checkURL + * @return boolean + */ +public static boolean isHTTPreachable(String checkURL){ + try{ + // make a URL to a known source + URL url=new URL(checkURL); - // open a connection to that source - HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection(); + // open a connection to that source + HttpURLConnection urlConnect=(HttpURLConnection)url.openConnection(); - // trying to retrieve data from the source. If there - // is no connection, this line will fail - Object objData = urlConnect.getContent(); + // trying to retrieve data from the source. If there + // is no connection, this line will fail + Object objData=urlConnect.getContent(); - } catch (Exception e) { - e.printStackTrace(); - return false; - } + }catch(Exception e){ + e.printStackTrace(); + return false; + } - return true; - } + return true; + } - /** - * Method to Ping IP Address - * - * @param addr IP address you want to ping it - * @return true if the IP address is reachable - */ - public boolean pingCmd(String addr) { +/** + * Method to Ping IP Address + * + * @param addr IP address you want to ping it + * @return true if the IP address is reachable + */ +public boolean pingCmd(String addr){ - try { + try{ - String ping = "ping -c 1 -W 3 " + addr; - Runtime run = Runtime.getRuntime(); - Process pro = run.exec(ping); + String ping="ping -c 1 -W 3 "+addr; + Runtime run=Runtime.getRuntime(); + Process pro=run.exec(ping); - try { + try{ pro.waitFor(); - } catch (InterruptedException e) { - Log.e(TAG, "InterruptedException error.", e); - } + }catch(InterruptedException e){ + Log.e(TAG,"InterruptedException error.",e); + } - int exit = pro.exitValue(); + int exit=pro.exitValue(); - Log.d(TAG, "pingCmd exitValue" + exit); + Log.d(TAG,"pingCmd exitValue"+exit); - if (exit == 0) { + if(exit==0){ return true; - } else { + }else{ // ip address is not reachable return false; - } - } catch (UnknownHostException e) { - Log.d(TAG, "UnknownHostException: " + e.getMessage()); - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - } - - return false; - } + } + }catch(UnknownHostException e){ + Log.d(TAG,"UnknownHostException: "+e.getMessage()); + }catch(Exception e){ + Log.d(TAG,e.getMessage()); + } - /** - * Network Changed Broadcast Receiver - */ - private class NetworkChangedReceiver extends BroadcastReceiver { + return false; + } - @Override - public void onReceive(final Context context, final Intent intent) { +/** + * Network Changed Broadcast Receiver + */ +private class NetworkChangedReceiver extends BroadcastReceiver { - if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { + @Override + public void onReceive(final Context context, final Intent intent) { - Log.d(TAG, "NETWORK_STATE_CHANGED_ACTION"); + if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { - NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); - WifiInfo info = WifiWizard2.this.wifiManager.getConnectionInfo(); + Log.d(TAG, "NETWORK_STATE_CHANGED_ACTION"); - // Checks that you're connected to the desired network - if (networkInfo.isConnected() && info.getNetworkId() > -1) { + NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); + WifiInfo info = WifiWizard2.this.wifiManager.getConnectionInfo(); - final String ssid = info.getSSID().replaceAll("\"", ""); - final String bssid = info.getBSSID(); + // Checks that you're connected to the desired network + if (networkInfo.isConnected() && info.getNetworkId() > -1) { - Log.d(TAG, "Connected to '" + ssid + "' @ " + bssid); + final String ssid = info.getSSID().replaceAll("\"", ""); + final String bssid = info.getBSSID(); - // Verify the desired network ID is what we actually connected to - if ( desired != null && info.getNetworkId() == desired.apId ) { - onSuccessfulConnection(); - } else { - Log.e(TAG, "Could not connect to the desired ssid: " + ssid); - } + Log.d(TAG, "Connected to '" + ssid + "' @ " + bssid); + // Verify the desired network ID is what we actually connected to + if (desired != null && info.getNetworkId() == desired.apId) { + onSuccessfulConnection(); + } else { + Log.e(TAG, "Could not connect to the desired ssid: " + ssid); } } @@ -1724,16 +1819,18 @@ public void onReceive(final Context context, final Intent intent) { } +} + /** * Register Receiver for Network Changed to handle BindALL * @param netID */ - private void registerBindALL(int netID){ + private void registerBindALL(int netID) { // Bind all requests to WiFi network (only necessary for Lollipop+ - API 21+) - if( API_VERSION > 21 ){ + if (API_VERSION > 21) { Log.d(TAG, "registerBindALL: registering net changed receiver"); - desired = new AP(netID,null,null); + desired = new AP(netID, null, null); cordova.getActivity().getApplicationContext().registerReceiver(networkChangedReceiver, NETWORK_STATE_CHANGED_FILTER); } else { Log.d(TAG, "registerBindALL: API older than 21, bindall ignored."); @@ -1747,35 +1844,37 @@ private void registerBindALL(int netID){ * bindProcessToNetwork or setProcessDefaultNetwork to prevent future sockets from application * being routed through Wifi. */ - private void maybeResetBindALL(){ + private void maybeResetBindALL() { Log.d(TAG, "maybeResetBindALL"); // desired should have a value if receiver is registered - if( desired != null ){ + if (desired != null) { - if( API_VERSION > 21 ){ + if (API_VERSION > 21) { try { // Unregister net changed receiver -- should only be registered in API versions > 21 cordova.getActivity().getApplicationContext().unregisterReceiver(networkChangedReceiver); - } catch (Exception e) {} + } catch (Exception e) { + } } // Lollipop OS or newer - if ( API_VERSION >= 23 ) { + if (API_VERSION >= 23) { connectivityManager.bindProcessToNetwork(null); - } else if( API_VERSION >= 21 && API_VERSION < 23 ){ + } else if (API_VERSION >= 21 && API_VERSION < 23) { connectivityManager.setProcessDefaultNetwork(null); } - if ( API_VERSION > 21 && networkCallback != null) { + if (API_VERSION > 21 && networkCallback != null) { try { // Same behavior as releaseNetworkRequest connectivityManager.unregisterNetworkCallback(networkCallback); // Added in API 21 - } catch (Exception e) {} + } catch (Exception e) { + } } networkCallback = null; @@ -1836,20 +1935,20 @@ private void onSuccessfulConnection() { // see https://android-developers.googleblog.com/2016/07/connecting-your-app-to-wi-fi-device.html // Marshmallow OS or newer - if ( API_VERSION >= 23 ) { + if (API_VERSION >= 23) { Log.d(TAG, "BindALL onSuccessfulConnection API >= 23"); // Marshmallow (API 23+) or newer uses bindProcessToNetwork final NetworkRequest request = new NetworkRequest.Builder() - .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) - .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .build(); + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .build(); networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { - if( connectivityManager.bindProcessToNetwork(network) ){ + if (connectivityManager.bindProcessToNetwork(network)) { Log.d(TAG, "bindProcessToNetwork TRUE onSuccessfulConnection"); } else { Log.d(TAG, "bindProcessToNetwork FALSE onSuccessfulConnection"); @@ -1860,15 +1959,15 @@ public void onAvailable(Network network) { connectivityManager.requestNetwork(request, networkCallback); // Only lollipop (API 21 && 22) use setProcessDefaultNetwork, API < 21 already does this by default - } else if( API_VERSION >= 21 && API_VERSION < 23 ){ + } else if (API_VERSION >= 21 && API_VERSION < 23) { Log.d(TAG, "BindALL onSuccessfulConnection API >= 21 && < 23"); // Lollipop (API 21-22) use setProcessDefaultNetwork (deprecated in API 23 - Marshmallow) final NetworkRequest request = new NetworkRequest.Builder() - .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) - .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .build(); + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .build(); networkCallback = new ConnectivityManager.NetworkCallback() { @Override @@ -1889,26 +1988,26 @@ public void onAvailable(Network network) { } } - /** - * Class to store finished boolean in - */ - private class ScanSyncContext { - - public boolean finished = false; - } +/** + * Class to store finished boolean in + */ +private class ScanSyncContext { - /** - * Used for storing access point information - */ - private static class AP { - final String ssid, bssid; - final int apId; - - AP(int apId, final String ssid, final String bssid) { - this.apId = apId; - this.ssid = ssid; - this.bssid = bssid; - } + public boolean finished = false; +} +/** + * Used for storing access point information + */ +private static class AP { + final String ssid, bssid; + final int apId; + + AP(int apId, final String ssid, final String bssid) { + this.apId = apId; + this.ssid = ssid; + this.bssid = bssid; } + +} } From 0029993b386ab25a7135e496d53c5556c1f566d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Vytla=C4=8Dil?= Date: Fri, 16 Jul 2021 07:48:22 +0200 Subject: [PATCH 2/4] Update WifiWizard2.java Update --- src/android/wifiwizard2/WifiWizard2.java | 1232 ++++++++++------------ 1 file changed, 586 insertions(+), 646 deletions(-) diff --git a/src/android/wifiwizard2/WifiWizard2.java b/src/android/wifiwizard2/WifiWizard2.java index 685a8c4..b1bb9c3 100644 --- a/src/android/wifiwizard2/WifiWizard2.java +++ b/src/android/wifiwizard2/WifiWizard2.java @@ -160,7 +160,7 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) { @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) - throws JSONException { + throws JSONException { this.callbackContext = callbackContext; this.passedData = data; @@ -180,7 +180,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo String ip = getWiFiRouterIP(); String macAddress = getMacAddress(); - if (ip == null || ip.equals("0.0.0.0")) { + if ( ip == null || ip.equals("0.0.0.0")) { callbackContext.error("NO_VALID_ROUTER_IP_FOUND"); return true; } else { @@ -198,7 +198,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo } // Return only IP address - if (action.equals(GET_WIFI_IP_ADDRESS)) { + if( action.equals( GET_WIFI_IP_ADDRESS ) ){ callbackContext.success(ip); return true; } @@ -212,136 +212,81 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo callbackContext.success(result); return true; + } else if (action.equals(GET_MAC_ADDRESS))){ + String macAddress = getMacAddress(); + callbackContext.success(macAddress); } - } else if(action.equals(GET_MAC_ADDRESS)) - - { - String macAddress = getMacAddress(); - callbackContext.success(macAddress); - 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(SCAN)) - - { - this.scan(callbackContext, data); - } 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(START_SCAN)) - - { - this.startScan(callbackContext); - } else if(action.equals(GET_SCAN_RESULTS)) - - { - this.getScanResults(callbackContext, data); - } else if(action.equals(DISCONNECT)) - - { - this.disconnect(callbackContext); - } else if(action.equals(GET_CONNECTED_SSID)) - - { - this.getConnectedSSID(callbackContext); - } else if(action.equals(GET_CONNECTED_BSSID)) - - { - this.getConnectedBSSID(callbackContext); - } else if(action.equals(GET_CONNECTED_NETWORKID)) - - { - this.getConnectedNetworkID(callbackContext); - } else if(action.equals(RESET_BIND_ALL)) - - { - this.resetBindAll(callbackContext); - } else if(action.equals(SET_BIND_ALL)) - - { - this.setBindAll(callbackContext); - } else + 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 + } - { - 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; - } + // 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(SCAN)) { + this.scan(callbackContext, data); + } 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(START_SCAN)) { + this.startScan(callbackContext); + } else if (action.equals(GET_SCAN_RESULTS)) { + this.getScanResults(callbackContext, data); + } else if (action.equals(DISCONNECT)) { + this.disconnect(callbackContext); + } else if (action.equals(GET_CONNECTED_SSID)) { + this.getConnectedSSID(callbackContext); + } else if (action.equals(GET_CONNECTED_BSSID)) { + this.getConnectedBSSID(callbackContext); + } else if (action.equals(GET_CONNECTED_NETWORKID)) { + this.getConnectedNetworkID(callbackContext); + } else if (action.equals(RESET_BIND_ALL)) { + this.resetBindAll(callbackContext); + } else if (action.equals(SET_BIND_ALL)) { + this.setBindAll(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 + * @param data JSONArray with [0] == JSONObject * @return true */ private boolean scan(final CallbackContext callbackContext, final JSONArray data) { @@ -404,8 +349,8 @@ public void run() { Log.v(TAG, "Registering broadcastReceiver"); context.registerReceiver( - receiver, - new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) + receiver, + new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) ); if (!wifiManager.startScan()) { @@ -447,13 +392,13 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { wifi.hiddenSSID = isHiddenSSID; if (authType.equals("WPA") || authType.equals("WPA2")) { - /** - * WPA Data format: - * 0: ssid - * 1: auth - * 2: password - * 3: isHiddenSSID - */ + /** + * WPA Data format: + * 0: ssid + * 1: auth + * 2: password + * 3: isHiddenSSID + */ wifi.SSID = newSSID; wifi.preSharedKey = newPass; @@ -469,13 +414,13 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { wifi.networkId = ssidToNetworkId(newSSID); } else if (authType.equals("WEP")) { - /** - * WEP Data format: - * 0: ssid - * 1: auth - * 2: password - * 3: isHiddenSSID - */ + /** + * WEP Data format: + * 0: ssid + * 1: auth + * 2: password + * 3: isHiddenSSID + */ wifi.SSID = newSSID; if (getHexKey(newPass)) { @@ -501,13 +446,13 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { wifi.networkId = ssidToNetworkId(newSSID); } else if (authType.equals("NONE")) { - /** - * OPEN Network data format: - * 0: ssid - * 1: auth - * 2: - * 3: isHiddenSSID - */ + /** + * OPEN Network data format: + * 0: ssid + * 1: auth + * 2: + * 3: isHiddenSSID + */ wifi.SSID = newSSID; wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifi.networkId = ssidToNetworkId(newSSID); @@ -521,11 +466,11 @@ private boolean add(CallbackContext callbackContext, JSONArray data) { } // Set network to highest priority (deprecated in API >= 26) - if (API_VERSION < 26) { + if(API_VERSION < 26) { wifi.priority = getMaxWifiPriority(wifiManager) + 1; } - if (API_VERSION >= 29) { + if(API_VERSION >= 29) { this.networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { @@ -533,12 +478,11 @@ public void onAvailable(Network network) { Log.d(TAG, "WiFi connected"); callbackContext.success("WiFi connected"); } - @Override public void onUnavailable() { - super.onUnavailable(); - Log.d(TAG, "WiFi not available"); - callbackContext.error("WiFi not available"); + super.onUnavailable(); + Log.d(TAG, "WiFi not available"); + callbackContext.error("WiFi not available"); } }; @@ -560,21 +504,21 @@ public void onUnavailable() { cm.requestNetwork(nr, this.networkCallback, 15000); } else { // After processing authentication types, add or update network - if (wifi.networkId == -1) { // -1 means SSID configuration does not exist yet + if(wifi.networkId == -1) { // -1 means SSID configuration does not exist yet int newNetId = wifiManager.addNetwork(wifi); - if (newNetId > -1) { - callbackContext.success(newNetId); + if( newNetId > -1 ){ + callbackContext.success( newNetId ); } else { - callbackContext.error("ERROR_ADDING_NETWORK"); + callbackContext.error( "ERROR_ADDING_NETWORK" ); } } else { int updatedNetID = wifiManager.updateNetwork(wifi); - if (updatedNetID > -1) { - callbackContext.success(updatedNetID); + if(updatedNetID > -1) { + callbackContext.success( updatedNetID ); } else { callbackContext.error("ERROR_UPDATING_NETWORK"); } @@ -583,7 +527,7 @@ public void onUnavailable() { } // WifiManager configurations are presistent for API 26+ - if (API_VERSION < 26) { + if(API_VERSION < 26) { wifiManager.saveConfiguration(); // Call saveConfiguration for older < 26 API } @@ -601,7 +545,7 @@ public void onUnavailable() { * This method connects a network. * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @param data JSON Array, with [0] being SSID to connect */ private void enable(CallbackContext callbackContext, JSONArray data) { Log.d(TAG, "WifiWizard2: enable entered."); @@ -630,18 +574,18 @@ private void enable(CallbackContext callbackContext, JSONArray data) { try { - if (networkIdToEnable > -1) { + 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")) { + if(bindAll.equals("true")) { registerBindALL(networkIdToEnable); } - if (wifiManager.enableNetwork(networkIdToEnable, true)) { + if(wifiManager.enableNetwork(networkIdToEnable, true)) { - if (waitForConnection.equals("true")) { + if( waitForConnection.equals("true") ){ callbackContext.success("NETWORK_ENABLED"); return; } else { @@ -671,7 +615,7 @@ private void enable(CallbackContext callbackContext, JSONArray data) { * This method disables a network. * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @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) { @@ -698,7 +642,7 @@ private boolean disable(CallbackContext callbackContext, JSONArray data) { try { if (networkIdToDisconnect > 0) { - if (wifiManager.disableNetwork(networkIdToDisconnect)) { + if(wifiManager.disableNetwork(networkIdToDisconnect)){ maybeResetBindALL(); callbackContext.success("Network " + ssidToDisable + " disabled!"); } else { @@ -724,7 +668,7 @@ private boolean disable(CallbackContext callbackContext, JSONArray data) { * 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 + * @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) { @@ -744,19 +688,19 @@ private boolean remove(CallbackContext callbackContext, JSONArray data) { if (networkIdToRemove > -1) { - if (wifiManager.removeNetwork(networkIdToRemove)) { + if( wifiManager.removeNetwork(networkIdToRemove) ){ - // Configurations persist by default in API 26+ - if (API_VERSION < 26) { - wifiManager.saveConfiguration(); - } + // Configurations persist by default in API 26+ + if (API_VERSION < 26) { + wifiManager.saveConfiguration(); + } - callbackContext.success("NETWORK_REMOVED"); + callbackContext.success("NETWORK_REMOVED"); - } else { + } else { - callbackContext.error("UNABLE_TO_REMOVE"); - } + callbackContext.error( "UNABLE_TO_REMOVE" ); + } return true; } else { @@ -775,7 +719,7 @@ private boolean remove(CallbackContext callbackContext, JSONArray data) { * This method connects a network. * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @param data JSON Array, with [0] being SSID to connect */ private void connect(CallbackContext callbackContext, JSONArray data) { Log.d(TAG, "WifiWizard2: connect entered."); @@ -807,7 +751,7 @@ private void connect(CallbackContext callbackContext, JSONArray data) { Log.d(TAG, "Valid networkIdToConnect: attempting connection"); // Bind all requests to WiFi network (only necessary for Lollipop+ - API 21+) - if (bindAll.equals("true")) { + if( bindAll.equals("true") ){ registerBindALL(networkIdToConnect); } @@ -832,76 +776,74 @@ private void connect(CallbackContext callbackContext, JSONArray data) { } } -/** - * 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 { - 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); + /** + * 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 { + 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]; + @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++) { + 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"}; - } + WifiInfo info = wifiManager.getConnectionInfo(); + NetworkInfo.DetailedState connectionState = info + .getDetailedStateOf(info.getSupplicantState()); - Log.d(TAG, "WifiWizard: Got " + connectionState.name() + " on " + (i + 1) + " out of " + TIMES_TO_RETRY); - final int ONE_SECOND = 1000; + 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) + ); - try { - Thread.sleep(ONE_SECOND); - } catch (InterruptedException e) { - Log.e(TAG, e.getMessage()); - return new String[]{"INTERRUPT_EXCEPT_WHILE_CONNECTING", null}; + 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 }; } - 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 + * @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) { @@ -923,17 +865,17 @@ private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray dat return false; } - if (API_VERSION < 29) { - int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect); + if(API_VERSION < 29){ + int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect); - if (networkIdToDisconnect > 0) { + if(networkIdToDisconnect > 0) { - if (wifiManager.disableNetwork(networkIdToDisconnect)) { + if(wifiManager.disableNetwork(networkIdToDisconnect)) { maybeResetBindALL(); // We also remove the configuration from the device (use "disable" to keep config) - if (wifiManager.removeNetwork(networkIdToDisconnect)) { + if( wifiManager.removeNetwork(networkIdToDisconnect) ){ callbackContext.success("Network " + ssidToDisconnect + " disconnected and removed!"); } else { callbackContext.error("DISCONNECT_NET_REMOVE_ERROR"); @@ -948,22 +890,23 @@ private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray dat } return true; - } else { - callbackContext.error("DISCONNECT_NET_ID_NOT_FOUND"); - Log.d(TAG, "WifiWizard2: Network not found to disconnect."); - return false; - } } else { - try { - ConnectivityManager cm = (ConnectivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); - cm.unregisterNetworkCallback(this.networkCallback); - connectivityManager.bindProcessToNetwork(null); - return true; - } catch (Exception e) { - callbackContext.error(e.getMessage()); - return false; - } + callbackContext.error("DISCONNECT_NET_ID_NOT_FOUND"); + Log.d(TAG, "WifiWizard2: Network not found to disconnect."); + return false; } + } else { + try{ + ConnectivityManager cm = (ConnectivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); + cm.unregisterNetworkCallback(this.networkCallback); + connectivityManager.bindProcessToNetwork(null); + return true; + } + catch(Exception e) { + callbackContext.error(e.getMessage()); + return false; + } + } } /** @@ -1048,7 +991,7 @@ private boolean listNetworks(CallbackContext callbackContext) { * networks. * * @param callbackContext A Cordova callback context - * @param data JSONArray with [0] == JSONObject + * @param data JSONArray with [0] == JSONObject * @return true */ private boolean getScanResults(CallbackContext callbackContext, JSONArray data) { @@ -1139,7 +1082,7 @@ private boolean getScanResults(CallbackContext callbackContext, JSONArray data) } else { requestLocationPermission(SCAN_RESULTS_CODE); - return true; + return true; } } @@ -1189,7 +1132,7 @@ private int getConnectedNetId() { * Get Network ID from SSID * * @param callbackContext A Cordova callback context - * @param data JSON Array, with [0] being SSID to connect + * @param data JSON Array, with [0] being SSID to connect * @return true if network connected, false if failed */ private boolean getSSIDNetworkID(CallbackContext callbackContext, JSONArray data) { @@ -1336,7 +1279,6 @@ private String getMacAddress() { } return ""; } -} /** * This method retrieves the current WiFi status @@ -1350,467 +1292,469 @@ private boolean isWifiEnabled(CallbackContext callbackContext){ return isEnabled; } -/** - * This method takes a given String, searches the current list of configured WiFi networks, and - * returns the networkId for the network if the SSID matches. If not, it returns -1. - */ -private int ssidToNetworkId(String ssid){ + /** + * This method takes a given String, searches the current list of configured WiFi networks, and + * returns the networkId for the network if the SSID matches. If not, it returns -1. + */ + private int ssidToNetworkId(String ssid) { - try{ + try { - int maybeNetId=Integer.parseInt(ssid); - Log.d(TAG,"ssidToNetworkId passed SSID is integer, probably a Network ID: "+ssid); - return maybeNetId; + int maybeNetId = Integer.parseInt(ssid); + Log.d(TAG, "ssidToNetworkId passed SSID is integer, probably a Network ID: " + ssid); + return maybeNetId; - }catch(NumberFormatException e){ + } catch (NumberFormatException e) { - List currentNetworks=wifiManager.getConfiguredNetworks(); - int networkId=-1; + List currentNetworks = wifiManager.getConfiguredNetworks(); + int networkId = -1; - // For each network in the list, compare the SSID with the given one - for(WifiConfiguration test:currentNetworks){ - if(test.SSID!=null&&test.SSID.equals(ssid)){ - networkId=test.networkId; - } + // For each network in the list, compare the SSID with the given one + for (WifiConfiguration test : currentNetworks) { + if (test.SSID != null && test.SSID.equals(ssid)) { + networkId = test.networkId; } + } - return networkId; + return networkId; - } - } + } + } -/** - * This method enables or disables the wifi - */ -private boolean setWifiEnabled(CallbackContext callbackContext,JSONArray data){ - if(!validateData(data)){ - callbackContext.error("SETWIFIENABLED_INVALID_DATA"); - Log.d(TAG,"WifiWizard2: setWifiEnabled invalid data"); - return false; - } + /** + * This method enables or disables the wifi + */ + private boolean setWifiEnabled(CallbackContext callbackContext, JSONArray data) { + if (!validateData(data)) { + callbackContext.error("SETWIFIENABLED_INVALID_DATA"); + Log.d(TAG, "WifiWizard2: setWifiEnabled invalid data"); + return false; + } - String status=""; + String status = ""; - try{ - status=data.getString(0); - }catch(Exception e){ - callbackContext.error(e.getMessage()); - Log.d(TAG,e.getMessage()); - return false; - } + try { + status = data.getString(0); + } catch (Exception e) { + callbackContext.error(e.getMessage()); + Log.d(TAG, e.getMessage()); + return false; + } - if(wifiManager.setWifiEnabled(status.equals("true"))){ - callbackContext.success(); - return true; - }else{ - callbackContext.error("ERROR_SETWIFIENABLED"); - return false; - } - } + if (wifiManager.setWifiEnabled(status.equals("true"))) { + callbackContext.success(); + return true; + } else { + callbackContext.error("ERROR_SETWIFIENABLED"); + return false; + } + } -/** - * This method will check if WiFi is enabled, and enable it if not, waiting up to 10 seconds for - * it to enable - * - * @return True if wifi is enabled, false if unable to enable wifi - */ -private boolean verifyWifiEnabled(){ + /** + * This method will check if WiFi is enabled, and enable it if not, waiting up to 10 seconds for + * it to enable + * + * @return True if wifi is enabled, false if unable to enable wifi + */ + private boolean verifyWifiEnabled() { - Log.d(TAG,"WifiWizard2: verifyWifiEnabled entered."); + Log.d(TAG, "WifiWizard2: verifyWifiEnabled entered."); - if(!wifiManager.isWifiEnabled()){ + if (!wifiManager.isWifiEnabled()) { - Log.i(TAG,"Enabling wi-fi..."); + Log.i(TAG, "Enabling wi-fi..."); - if(wifiManager.setWifiEnabled(true)){ - Log.i(TAG,"Wi-fi enabled"); - }else{ - Log.e(TAG,"VERIFY_ERROR_ENABLE_WIFI"); + if (wifiManager.setWifiEnabled(true)) { + Log.i(TAG, "Wi-fi enabled"); + } else { + Log.e(TAG, "VERIFY_ERROR_ENABLE_WIFI"); return false; - } + } - // This happens very quickly, but need to wait for it to enable. A little busy wait? - int count=0; + // This happens very quickly, but need to wait for it to enable. A little busy wait? + int count = 0; - while(!wifiManager.isWifiEnabled()){ - if(count>=10){ - Log.i(TAG,"Took too long to enable wi-fi, quitting"); - return false; + while (!wifiManager.isWifiEnabled()) { + if (count >= 10) { + Log.i(TAG, "Took too long to enable wi-fi, quitting"); + return false; } - Log.i(TAG,"Still waiting for wi-fi to enable..."); + Log.i(TAG, "Still waiting for wi-fi to enable..."); - try{ - Thread.sleep(1000L); - }catch(InterruptedException ie){ - // continue + try { + Thread.sleep(1000L); + } catch (InterruptedException ie) { + // continue } count++; - } + } - // If we make it this far, wifi should be enabled by now - return true; + // If we make it this far, wifi should be enabled by now + return true; - }else{ + } else { - return true; + return true; - } + } - } + } -/** - * Format and return WiFi IPv4 Address - * @return - */ -private String[]getWiFiIPAddress(){ - WifiInfo wifiInfo=wifiManager.getConnectionInfo(); - int ip=wifiInfo.getIpAddress(); + /** + * Format and return WiFi IPv4 Address + * @return + */ + private String[] getWiFiIPAddress() { + WifiInfo wifiInfo = wifiManager.getConnectionInfo(); + int ip = wifiInfo.getIpAddress(); - String ipString=formatIP(ip); - String subnet=""; + String ipString = formatIP(ip); + String subnet = ""; - try{ - InetAddress inetAddress=InetAddress.getByName(ipString); - subnet=getIPv4Subnet(inetAddress); - }catch(Exception e){ - } + try { + InetAddress inetAddress = InetAddress.getByName(ipString); + subnet = getIPv4Subnet(inetAddress); + } catch (Exception e) { + } - return new String[]{ipString,subnet}; - } + return new String[]{ipString, subnet}; + } -/** - * Get WiFi Router IP from DHCP - * @return - */ -private String getWiFiRouterIP(){ - DhcpInfo dhcp=wifiManager.getDhcpInfo(); - int ip=dhcp.gateway; - return formatIP(ip); - } + /** + * Get WiFi Router IP from DHCP + * @return + */ + private String getWiFiRouterIP() { + DhcpInfo dhcp = wifiManager.getDhcpInfo(); + int ip = dhcp.gateway; + return formatIP(ip); + } -/** - * Format IPv4 Address - * @param ip - * @return - */ -private String formatIP(int ip){ - return String.format( + /** + * Format IPv4 Address + * @param ip + * @return + */ + private String formatIP(int ip) { + return String.format( "%d.%d.%d.%d", - (ip&0xff), - (ip>>8&0xff), - (ip>>16&0xff), - (ip>>24&0xff) - ); - } + (ip & 0xff), + (ip >> 8 & 0xff), + (ip >> 16 & 0xff), + (ip >> 24 & 0xff) + ); + } -/** - * Get IPv4 Subnet - * @param inetAddress - * @return - */ -public static String getIPv4Subnet(InetAddress inetAddress){ - try{ - NetworkInterface ni=NetworkInterface.getByInetAddress(inetAddress); - List intAddrs=ni.getInterfaceAddresses(); - for(InterfaceAddress ia:intAddrs){ - if(!ia.getAddress().isLoopbackAddress()&&ia.getAddress()instanceof Inet4Address){ - return getIPv4SubnetFromNetPrefixLength(ia.getNetworkPrefixLength()).getHostAddress() - .toString(); - } - } - }catch(Exception e){ - } - return""; + /** + * Get IPv4 Subnet + * @param inetAddress + * @return + */ + public static String getIPv4Subnet(InetAddress inetAddress) { + try { + NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress); + List intAddrs = ni.getInterfaceAddresses(); + for (InterfaceAddress ia : intAddrs) { + if (!ia.getAddress().isLoopbackAddress() && ia.getAddress() instanceof Inet4Address) { + return getIPv4SubnetFromNetPrefixLength(ia.getNetworkPrefixLength()).getHostAddress() + .toString(); } + } + } catch (Exception e) { + } + return ""; + } -/** - * Get Subnet from Prefix Length - * @param netPrefixLength - * @return - */ -public static InetAddress getIPv4SubnetFromNetPrefixLength(int netPrefixLength){ - try{ - int shift=(1<<31); - for(int i=netPrefixLength-1;i>0;i--){ - shift=(shift>>1); - } - String subnet= - Integer.toString((shift>>24)&255)+"."+Integer.toString((shift>>16)&255)+"." - +Integer.toString((shift>>8)&255)+"."+Integer.toString(shift&255); - return InetAddress.getByName(subnet); - }catch(Exception e){ - } - return null; - } + /** + * Get Subnet from Prefix Length + * @param netPrefixLength + * @return + */ + public static InetAddress getIPv4SubnetFromNetPrefixLength(int netPrefixLength) { + try { + int shift = (1 << 31); + for (int i = netPrefixLength - 1; i > 0; i--) { + shift = (shift >> 1); + } + String subnet = + Integer.toString((shift >> 24) & 255) + "." + Integer.toString((shift >> 16) & 255) + "." + + Integer.toString((shift >> 8) & 255) + "." + Integer.toString(shift & 255); + return InetAddress.getByName(subnet); + } catch (Exception e) { + } + return null; + } -/** - * Validate JSON data - */ -private boolean validateData(JSONArray data){ - try{ - if(data==null||data.get(0)==null){ + /** + * Validate JSON data + */ + private boolean validateData(JSONArray data) { + try { + if (data == null || data.get(0) == null) { callbackContext.error("DATA_IS_NULL"); return false; - } - return true; - }catch(Exception e){ - callbackContext.error(e.getMessage()); - } - return false; - } + } + return true; + } catch (Exception e) { + callbackContext.error(e.getMessage()); + } + return false; + } -/** - * Request ACCESS_FINE_LOCATION Permission - * @param requestCode - */ -protected void requestLocationPermission(int requestCode){ - cordova.requestPermission(this,requestCode,ACCESS_FINE_LOCATION); - } + /** + * Request ACCESS_FINE_LOCATION Permission + * @param requestCode + */ + protected void requestLocationPermission(int requestCode) { + cordova.requestPermission(this, requestCode, ACCESS_FINE_LOCATION); + } -/** - * Handle Android Permission Requests - */ -public void onRequestPermissionResult(int requestCode,String[]permissions,int[]grantResults) - throws JSONException{ + /** + * Handle Android Permission Requests + */ + public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) + throws JSONException { - for(int r:grantResults){ - if(r==PackageManager.PERMISSION_DENIED){ - callbackContext.error("PERMISSION_DENIED"); + for (int r : grantResults) { + if (r == PackageManager.PERMISSION_DENIED) { + callbackContext.error( "PERMISSION_DENIED" ); return; - } - } + } + } - switch(requestCode){ - case SCAN_RESULTS_CODE: - getScanResults(callbackContext,passedData); // Call method again after permissions approved + switch (requestCode) { + case SCAN_RESULTS_CODE: + getScanResults(callbackContext, passedData); // Call method again after permissions approved break; - case SCAN_CODE: - scan(callbackContext,passedData); // Call method again after permissions approved + case SCAN_CODE: + scan(callbackContext, passedData); // Call method again after permissions approved break; - case LOCATION_REQUEST_CODE: + case LOCATION_REQUEST_CODE: callbackContext.success("PERMISSION_GRANTED"); break; - case WIFI_SERVICE_INFO_CODE: - getWifiServiceInfo(callbackContext,bssidRequested); + case WIFI_SERVICE_INFO_CODE: + getWifiServiceInfo(callbackContext, bssidRequested); break; - } - } + } + } -/** - * Figure out what the highest priority network in the network list is and return that priority - */ -private static int getMaxWifiPriority(final WifiManager wifiManager){ -final List configurations=wifiManager.getConfiguredNetworks(); - int maxPriority=0; - for(WifiConfiguration config:configurations){ - if(config.priority>maxPriority){ - maxPriority=config.priority; - } - } + /** + * Figure out what the highest priority network in the network list is and return that priority + */ + private static int getMaxWifiPriority(final WifiManager wifiManager) { + final List configurations = wifiManager.getConfiguredNetworks(); + int maxPriority = 0; + for (WifiConfiguration config : configurations) { + if (config.priority > maxPriority) { + maxPriority = config.priority; + } + } - Log.d(TAG,"WifiWizard: Found max WiFi priority of " - +maxPriority); + Log.d(TAG, "WifiWizard: Found max WiFi priority of " + + maxPriority); - return maxPriority; - } + return maxPriority; + } -/** - * Check if device is connected to Internet - */ -private boolean canConnectToInternet(CallbackContext callbackContext,boolean doPing){ + /** + * Check if device is connected to Internet + */ + private boolean canConnectToInternet(CallbackContext callbackContext, boolean doPing) { - try{ + try { - if(hasInternetConnection(doPing)){ + if ( hasInternetConnection(doPing) ) { // Send success as 1 to return true from Promise (handled in JS) callbackContext.success("1"); return true; - }else{ + } else { callbackContext.success("0"); return false; - } + } - }catch(Exception e){ - callbackContext.error(e.getMessage()); - Log.d(TAG,e.getMessage()); - return false; - } - } + } catch (Exception e) { + callbackContext.error(e.getMessage()); + Log.d(TAG, e.getMessage()); + return false; + } + } -/** - * Check if we can conenct to router via HTTP connection - * - * @param callbackContext - * @param doPing - * @return boolean - */ -private boolean canConnectToRouter(CallbackContext callbackContext,boolean doPing){ + /** + * Check if we can conenct to router via HTTP connection + * + * @param callbackContext + * @param doPing + * @return boolean + */ + private boolean canConnectToRouter(CallbackContext callbackContext, boolean doPing) { - try{ + try { - if(hasConnectionToRouter(doPing)){ + if (hasConnectionToRouter(doPing)) { // Send success as 1 to return true from Promise (handled in JS) callbackContext.success("1"); return true; - }else{ + } else { callbackContext.success("0"); return false; - } + } - }catch(Exception e){ - callbackContext.error(e.getMessage()); - Log.d(TAG,e.getMessage()); - return false; - } - } + } catch (Exception e) { + callbackContext.error(e.getMessage()); + Log.d(TAG, e.getMessage()); + return false; + } + } -/** - * Check if The Device Is Connected to Internet - * - * @return true if device connect to Internet or return false if not - */ -public boolean hasInternetConnection(boolean doPing){ - if(connectivityManager!=null){ - NetworkInfo info=connectivityManager.getActiveNetworkInfo(); - if(info!=null){ - if(info.isConnected()){ - if(doPing){ - return pingCmd("8.8.8.8"); - }else{ - return isHTTPreachable("http://www.google.com/"); - } - } - } - } - return false; + /** + * Check if The Device Is Connected to Internet + * + * @return true if device connect to Internet or return false if not + */ + public boolean hasInternetConnection(boolean doPing) { + if (connectivityManager != null) { + NetworkInfo info = connectivityManager.getActiveNetworkInfo(); + if (info != null) { + if (info.isConnected()) { + if( doPing ){ + return pingCmd("8.8.8.8"); + } else { + return isHTTPreachable("http://www.google.com/"); + } } + } + } + return false; + } -/** - * Check for connection to router by pinging router IP - * @return - */ -public boolean hasConnectionToRouter(boolean doPing){ + /** + * Check for connection to router by pinging router IP + * @return + */ + public boolean hasConnectionToRouter( boolean doPing ) { - String ip=getWiFiRouterIP(); + String ip = getWiFiRouterIP(); - if(ip==null||ip.equals("0.0.0.0")||connectivityManager==null){ + if ( ip == null || ip.equals("0.0.0.0") || connectivityManager == null) { - return false; + return false; - }else{ + } else { - NetworkInfo info=connectivityManager.getActiveNetworkInfo(); + NetworkInfo info = connectivityManager.getActiveNetworkInfo(); - if(info!=null&&info.isConnected()){ + if (info != null && info.isConnected()) { - if(doPing){ - return pingCmd(ip); - }else{ - return isHTTPreachable("http://"+ip+"/"); + if( doPing ){ + return pingCmd(ip); + } else { + return isHTTPreachable("http://" + ip + "/"); } - }else{ + } else { return false; - } + } - } + } - } + } -/** - * Check if HTTP connection to URL is reachable - * - * @param checkURL - * @return boolean - */ -public static boolean isHTTPreachable(String checkURL){ - try{ - // make a URL to a known source - URL url=new URL(checkURL); + /** + * Check if HTTP connection to URL is reachable + * + * @param checkURL + * @return boolean + */ + public static boolean isHTTPreachable(String checkURL) { + try { + // make a URL to a known source + URL url = new URL(checkURL); - // open a connection to that source - HttpURLConnection urlConnect=(HttpURLConnection)url.openConnection(); + // open a connection to that source + HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection(); - // trying to retrieve data from the source. If there - // is no connection, this line will fail - Object objData=urlConnect.getContent(); + // trying to retrieve data from the source. If there + // is no connection, this line will fail + Object objData = urlConnect.getContent(); - }catch(Exception e){ - e.printStackTrace(); - return false; - } + } catch (Exception e) { + e.printStackTrace(); + return false; + } - return true; - } + return true; + } -/** - * Method to Ping IP Address - * - * @param addr IP address you want to ping it - * @return true if the IP address is reachable - */ -public boolean pingCmd(String addr){ + /** + * Method to Ping IP Address + * + * @param addr IP address you want to ping it + * @return true if the IP address is reachable + */ + public boolean pingCmd(String addr) { - try{ + try { - String ping="ping -c 1 -W 3 "+addr; - Runtime run=Runtime.getRuntime(); - Process pro=run.exec(ping); + String ping = "ping -c 1 -W 3 " + addr; + Runtime run = Runtime.getRuntime(); + Process pro = run.exec(ping); - try{ + try { pro.waitFor(); - }catch(InterruptedException e){ - Log.e(TAG,"InterruptedException error.",e); - } + } catch (InterruptedException e) { + Log.e(TAG, "InterruptedException error.", e); + } - int exit=pro.exitValue(); + int exit = pro.exitValue(); - Log.d(TAG,"pingCmd exitValue"+exit); + Log.d(TAG, "pingCmd exitValue" + exit); - if(exit==0){ + if (exit == 0) { return true; - }else{ + } else { // ip address is not reachable return false; - } - }catch(UnknownHostException e){ - Log.d(TAG,"UnknownHostException: "+e.getMessage()); - }catch(Exception e){ - Log.d(TAG,e.getMessage()); - } + } + } catch (UnknownHostException e) { + Log.d(TAG, "UnknownHostException: " + e.getMessage()); + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + } - return false; - } + return false; + } -/** - * Network Changed Broadcast Receiver - */ -private class NetworkChangedReceiver extends BroadcastReceiver { + /** + * Network Changed Broadcast Receiver + */ + private class NetworkChangedReceiver extends BroadcastReceiver { - @Override - public void onReceive(final Context context, final Intent intent) { + @Override + public void onReceive(final Context context, final Intent intent) { - if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { + if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { - Log.d(TAG, "NETWORK_STATE_CHANGED_ACTION"); + Log.d(TAG, "NETWORK_STATE_CHANGED_ACTION"); - NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); - WifiInfo info = WifiWizard2.this.wifiManager.getConnectionInfo(); + NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); + WifiInfo info = WifiWizard2.this.wifiManager.getConnectionInfo(); - // Checks that you're connected to the desired network - if (networkInfo.isConnected() && info.getNetworkId() > -1) { + // Checks that you're connected to the desired network + if (networkInfo.isConnected() && info.getNetworkId() > -1) { - final String ssid = info.getSSID().replaceAll("\"", ""); - final String bssid = info.getBSSID(); + final String ssid = info.getSSID().replaceAll("\"", ""); + final String bssid = info.getBSSID(); - Log.d(TAG, "Connected to '" + ssid + "' @ " + bssid); + Log.d(TAG, "Connected to '" + ssid + "' @ " + bssid); + + // Verify the desired network ID is what we actually connected to + if ( desired != null && info.getNetworkId() == desired.apId ) { + onSuccessfulConnection(); + } else { + Log.e(TAG, "Could not connect to the desired ssid: " + ssid); + } - // Verify the desired network ID is what we actually connected to - if (desired != null && info.getNetworkId() == desired.apId) { - onSuccessfulConnection(); - } else { - Log.e(TAG, "Could not connect to the desired ssid: " + ssid); } } @@ -1819,18 +1763,16 @@ public void onReceive(final Context context, final Intent intent) { } -} - /** * Register Receiver for Network Changed to handle BindALL * @param netID */ - private void registerBindALL(int netID) { + private void registerBindALL(int netID){ // Bind all requests to WiFi network (only necessary for Lollipop+ - API 21+) - if (API_VERSION > 21) { + if( API_VERSION > 21 ){ Log.d(TAG, "registerBindALL: registering net changed receiver"); - desired = new AP(netID, null, null); + desired = new AP(netID,null,null); cordova.getActivity().getApplicationContext().registerReceiver(networkChangedReceiver, NETWORK_STATE_CHANGED_FILTER); } else { Log.d(TAG, "registerBindALL: API older than 21, bindall ignored."); @@ -1844,37 +1786,35 @@ private void registerBindALL(int netID) { * bindProcessToNetwork or setProcessDefaultNetwork to prevent future sockets from application * being routed through Wifi. */ - private void maybeResetBindALL() { + private void maybeResetBindALL(){ Log.d(TAG, "maybeResetBindALL"); // desired should have a value if receiver is registered - if (desired != null) { + if( desired != null ){ - if (API_VERSION > 21) { + if( API_VERSION > 21 ){ try { // Unregister net changed receiver -- should only be registered in API versions > 21 cordova.getActivity().getApplicationContext().unregisterReceiver(networkChangedReceiver); - } catch (Exception e) { - } + } catch (Exception e) {} } // Lollipop OS or newer - if (API_VERSION >= 23) { + if ( API_VERSION >= 23 ) { connectivityManager.bindProcessToNetwork(null); - } else if (API_VERSION >= 21 && API_VERSION < 23) { + } else if( API_VERSION >= 21 && API_VERSION < 23 ){ connectivityManager.setProcessDefaultNetwork(null); } - if (API_VERSION > 21 && networkCallback != null) { + if ( API_VERSION > 21 && networkCallback != null) { try { // Same behavior as releaseNetworkRequest connectivityManager.unregisterNetworkCallback(networkCallback); // Added in API 21 - } catch (Exception e) { - } + } catch (Exception e) {} } networkCallback = null; @@ -1935,20 +1875,20 @@ private void onSuccessfulConnection() { // see https://android-developers.googleblog.com/2016/07/connecting-your-app-to-wi-fi-device.html // Marshmallow OS or newer - if (API_VERSION >= 23) { + if ( API_VERSION >= 23 ) { Log.d(TAG, "BindALL onSuccessfulConnection API >= 23"); // Marshmallow (API 23+) or newer uses bindProcessToNetwork final NetworkRequest request = new NetworkRequest.Builder() - .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) - .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .build(); + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .build(); networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { - if (connectivityManager.bindProcessToNetwork(network)) { + if( connectivityManager.bindProcessToNetwork(network) ){ Log.d(TAG, "bindProcessToNetwork TRUE onSuccessfulConnection"); } else { Log.d(TAG, "bindProcessToNetwork FALSE onSuccessfulConnection"); @@ -1959,15 +1899,15 @@ public void onAvailable(Network network) { connectivityManager.requestNetwork(request, networkCallback); // Only lollipop (API 21 && 22) use setProcessDefaultNetwork, API < 21 already does this by default - } else if (API_VERSION >= 21 && API_VERSION < 23) { + } else if( API_VERSION >= 21 && API_VERSION < 23 ){ Log.d(TAG, "BindALL onSuccessfulConnection API >= 21 && < 23"); // Lollipop (API 21-22) use setProcessDefaultNetwork (deprecated in API 23 - Marshmallow) final NetworkRequest request = new NetworkRequest.Builder() - .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) - .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .build(); + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .build(); networkCallback = new ConnectivityManager.NetworkCallback() { @Override @@ -1988,26 +1928,26 @@ public void onAvailable(Network network) { } } -/** - * Class to store finished boolean in - */ -private class ScanSyncContext { - - public boolean finished = false; -} + /** + * Class to store finished boolean in + */ + private class ScanSyncContext { -/** - * Used for storing access point information - */ -private static class AP { - final String ssid, bssid; - final int apId; - - AP(int apId, final String ssid, final String bssid) { - this.apId = apId; - this.ssid = ssid; - this.bssid = bssid; + public boolean finished = false; } -} + /** + * Used for storing access point information + */ + private static class AP { + final String ssid, bssid; + final int apId; + + AP(int apId, final String ssid, final String bssid) { + this.apId = apId; + this.ssid = ssid; + this.bssid = bssid; + } + + } } From 3dffc84f5e67f4fcf2f3a7f9cf4c85edeb8d4964 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Vytla=C4=8Dil?= Date: Fri, 16 Jul 2021 08:07:30 +0200 Subject: [PATCH 3/4] Update Update --- src/android/wifiwizard2/WifiWizard2.java | 4 ++-- www/WifiWizard2.js | 13 +++++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/android/wifiwizard2/WifiWizard2.java b/src/android/wifiwizard2/WifiWizard2.java index b1bb9c3..046ac8e 100644 --- a/src/android/wifiwizard2/WifiWizard2.java +++ b/src/android/wifiwizard2/WifiWizard2.java @@ -178,7 +178,6 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo } else if (action.equals(GET_WIFI_ROUTER_IP_ADDRESS)) { String ip = getWiFiRouterIP(); - String macAddress = getMacAddress(); if ( ip == null || ip.equals("0.0.0.0")) { callbackContext.error("NO_VALID_ROUTER_IP_FOUND"); @@ -189,6 +188,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo } } else if (action.equals(GET_WIFI_IP_ADDRESS) || action.equals(GET_WIFI_IP_INFO)) { + String macAddress = getMacAddress(); String[] ipInfo = getWiFiIPAddress(); String ip = ipInfo[0]; String subnet = ipInfo[1]; @@ -212,7 +212,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo callbackContext.success(result); return true; - } else if (action.equals(GET_MAC_ADDRESS))){ + } else if (action.equals(GET_MAC_ADDRESS)){ String macAddress = getMacAddress(); callbackContext.success(macAddress); } diff --git a/www/WifiWizard2.js b/www/WifiWizard2.js index 2408a31..be57ede 100644 --- a/www/WifiWizard2.js +++ b/www/WifiWizard2.js @@ -366,7 +366,7 @@ var WifiWizard2 = { cordova.exec(resolve, reject, "WifiWizard2", "setBindAll", []); }); }, - + /** * Get Wifi Router IP from DHCP * @returns {Promise} @@ -385,6 +385,15 @@ var WifiWizard2 = { cordova.exec(resolve, reject, "WifiWizard2", "getWifiIP", []); }); }, + /** + * Get Mac Address + * @returns {Promise} + */ + getMacAddress: function () { + return new Promise(function (resolve, reject) { + cordova.exec(resolve, reject, "WifiWizard2", "getMacAddress", []); + }); + }, /** * Get Wifi IP and Subnet Address * @@ -623,7 +632,7 @@ var WifiWizard2 = { if(device.platform === "Android" && parseInt(device.version.split('.')[0]) >= 10){ // Do not add "" To the SSID, as the new method for Android Q does not support it - } + } else { if (ssid.charAt(0) != '"') { ssid = '"' + ssid; From 342f4bfe3c2d577306a62bc573d4eb512d131a94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Vytla=C4=8Dil?= Date: Fri, 16 Jul 2021 08:40:55 +0200 Subject: [PATCH 4/4] Update documentation --- www/WifiWizard2.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/WifiWizard2.js b/www/WifiWizard2.js index be57ede..016fae0 100644 --- a/www/WifiWizard2.js +++ b/www/WifiWizard2.js @@ -397,7 +397,7 @@ var WifiWizard2 = { /** * Get Wifi IP and Subnet Address * - * This method returns a JSON object similar to: { "ip": "0.0.0.0", "subnet": "0.0.0.0" } + * This method returns a JSON object similar to: { "ip": "0.0.0.0", "subnet": "0.0.0.0", "macAddress":"0.0.0.0"} * @returns {Promise} */ getWifiIPInfo: function () {