Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extension with the ability to get a mac address on Android devices #130

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 57 additions & 18 deletions src/android/wifiwizard2/WifiWizard2.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -187,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];
Expand All @@ -206,9 +208,13 @@ 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;
} else if (action.equals(GET_MAC_ADDRESS)){
String macAddress = getMacAddress();
callbackContext.success(macAddress);
}

boolean wifiIsEnabled = verifyWifiEnabled();
Expand Down Expand Up @@ -1199,7 +1205,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;
Expand All @@ -1211,56 +1217,89 @@ 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<NetworkInterface> 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 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;
}

/**
* 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;
Expand Down Expand Up @@ -1544,7 +1583,7 @@ private boolean canConnectToInternet(CallbackContext callbackContext, boolean do

/**
* Check if we can conenct to router via HTTP connection
*
*
* @param callbackContext
* @param doPing
* @return boolean
Expand Down Expand Up @@ -1623,7 +1662,7 @@ public boolean hasConnectionToRouter( boolean doPing ) {

/**
* Check if HTTP connection to URL is reachable
*
*
* @param checkURL
* @return boolean
*/
Expand Down
15 changes: 12 additions & 3 deletions www/WifiWizard2.js
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ var WifiWizard2 = {
cordova.exec(resolve, reject, "WifiWizard2", "setBindAll", []);
});
},

/**
* Get Wifi Router IP from DHCP
* @returns {Promise<any>}
Expand All @@ -385,10 +385,19 @@ var WifiWizard2 = {
cordova.exec(resolve, reject, "WifiWizard2", "getWifiIP", []);
});
},
/**
* Get Mac Address
* @returns {Promise<any>}
*/
getMacAddress: function () {
return new Promise(function (resolve, reject) {
cordova.exec(resolve, reject, "WifiWizard2", "getMacAddress", []);
});
},
/**
* 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<any>}
*/
getWifiIPInfo: function () {
Expand Down Expand Up @@ -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;
Expand Down