WifiWizard2
WifiWizard2 enables Wifi management for both Android and iOS applications within Cordova/Phonegap projects.
This project is a fork of the WifiWizard plugin with fixes and updates, as well as patches taken from the Cordova Network Manager plugin.
https://github.com/tripflex/WifiWizard2
Stuck on a Cordova issue?
If you're building a serious project, you can't afford to spend hours troubleshooting. Ionic’s experts offer premium advisory services for both community plugins and premier plugins.
Installation#
- Capacitor
- Cordova
- Enterprise
Ionic Enterprise comes with fully supported and maintained plugins from the Ionic Team. Learn More or if you're interested in an enterprise version of this plugin Contact Us
Supported Platforms#
- Android
- iOS
Usage#
React#
Learn more about using Ionic Native components in React
Angular#
Returns connected network SSID (only if connected) in success callback, otherwise fail callback will be called (if not connected or unable to retrieve)
This does NOT return the BSSID if unable to obtain SSID (like original WifiWizard did)
Same as above, except BSSID (mac) is returned
delayshould be time in milliseconds to delayHelper async timeout delay,
delayis optional, default is 2000ms = 2 secondsThis method always returns a resolved promise after the delay, it will never reject or throw an error
Example inside async function
Example inside standard non-async function
Thrown Errors
TIMEOUT_WAITING_FOR_SCANon timeout waiting for scan 10 seconds +SCAN_FAILEDif unable to start scaniOS Functions#
For functionality, you need to note the following:
Connect/Disconnect only works for iOS11+
Can't run in the simulator so you need to attach an actual device when building with xCode
Will ensure 'HotspotConfiguration' and 'NetworkExtensions' capabilities are added to your xCode project
To connect to open network omit
ssidPasswordor call withfalseAndroid Functions#
WifiWizard2 will automagically try to enable WiFi if it's disabled when calling any android related methods that require WiFi to be enabled
Connect vs Enable#
When writing Android Java code, there is no
connectmethods, you basically eitherenableordisablea network. In the original versions of WifiWizard theconnectmethod would basically just callenablein Android. I have changed the way this works in WifiWizard2 version 3.0.0+, converting it to a helper method to eliminate having to callformatWifiConfigthenaddand thenenable... theconnectmethod will now automatically callformatWifiConfig, then calladdto either add or update the network configuration, and then callenable. If the connect method is unable to update existing network configuration (added by user or other apps), but there is a valid network ID, it will still attempt to enable that network ID.ssidshould be the SSID to connect to requiredbindAllshould be set totrueto tell Android to route all connections from your Android app, through the wifi connection (default isfalse) optionalSee
WifiWizard2.enablefor more details regardingbindAllfeaturealgorithmandpasswordis not required if connecting to an open networkCurrently
WPAandWEPare only supported algorithmsFor
WPA2just passWPAas the algorithmSet
isHiddenSSIDtotrueif the network you're connecting to is hiddenThese arguments are the same as for
formatWifiConfigThis method essentially calls
formatWifiConfigthenaddthenenableIf unable to update network configuration (was added by user or other app), but a valid network ID exists, this method will still attempt to enable the network
Promise will not be returned until method has verified that connection to WiFi was in completed state (waits up to 60 seconds)
Thrown Errors
CONNECT_FAILED_TIMEOUTunable to verify connection, timed out after 60 secondsINVALID_NETWORK_ID_TO_CONNECTUnable to connect based on generated wifi configINTERPUT_EXCEPT_WHILE_CONNECTINGInterupt exception while waiting for connection
Disconnect vs Disable#
Same as above for Connect vs Enable, except in this situation, disconnect will first disable the network, and then attempt to remove it (if SSID is passed)
ssidcan either be an SSID (string) or a network ID (integer)ssidis OPTIONAL .. if not passed, will disconnect current WiFi (almost all Android versions now will just automatically reconnect to last wifi after disconnecting)If
ssidis provided, this method will first attempt todisableand thenremovethe networkIf you do not want to remove network configuration, use
disableinsteadThrown Errors
DISCONNECT_NET_REMOVE_ERRORAndroid returned error when removing wifi configurationDISCONNECT_NET_DISABLE_ERRORUnable to connect based on generated wifi configDISCONNECT_NET_ID_NOT_FOUNDUnable to determine network ID to disconnect/remove (from passed SSID)ERROR_DISCONNECT- Android error disconnecting wifi (only when SSID is not passed)algorithmandpasswordis not required if connecting to an open networkCurrently
WPAandWEPare only supported algorithmsFor
WPA2just passWPAas the algorithmSet
isHiddenSSIDtotrueif the network you're connecting to is hiddenThis is just a helper method that calls
WifiWizard2.formatWifiConfig( ssid, password, 'WPA', isHiddenSSID );wifimust be an object formatted byformatWifiConfig, this must be done before callingenableThrown Errors
AUTH_TYPE_NOT_SUPPORTED- Invalid auth type specifiedERROR_ADDING_NETWORK- Android returned-1specifying error adding networkERROR_UPDATING_NETWORK- Same as above, except an existing network ID was found, and unable to update itssidcan either be an SSID (string) or a network ID (integer)Please note, most newer versions of Android will only allow wifi to be removed if created by your application
Thrown Errors
UNABLE_TO_REMOVEAndroid returned failure in removing networkREMOVE_NETWORK_NOT_FOUNDUnable to determine network ID from passed SSID
Same as calling
startScanand thengetScanResults, except this method will only resolve the promise after the scan completes and returns the results.It is recommended to just use the
scanmethod instead ofstartScanThrown Errors
STARTSCAN_FAILEDAndroid returned failure in starting scan
getScanResultsshould only be called after callingstartScan(it is recommended to usescaninstead as this starts the scan, then returns the results)[options]is optional, if you do not want to specify, just passsuccesscallback as first parameter, andfailcallback as second parameterRetrieves a list of the available networks as an array of objects and passes them to the function listHandler. The format of the array is:
channelWidthcenterFreq0andcenterFreq1are only supported on API > 23 (Marshmallow), any older API will return null for these valuesAn options object may be passed. Currently, the only supported option is
numLevels, and it has the following behavior:if
(n == true || n < 2),*.getScanResults({numLevels: n})will return data as before, split in 5 levels;if
(n > 1),*.getScanResults({numLevels: n})will calculate the signal level, split in n levels;if
(n == false),*.getScanResults({numLevels: n})will use the raw signal level;Returns boolean value of whether Wifi is enabled or not
Pass
trueforenabledparameter to set Wifi enabledYou do not need to call this function to set WiFi enabled to call other methods that require wifi enabled. This plugin will automagically enable WiFi if a method is called that requires WiFi to be enabled.
Thrown Errors
ERROR_SETWIFIENABLEDwifi state does not match call (enable or disable)Returns currently connected network ID in success callback (only if connected), otherwise fail callback will be called
Thrown Errors
GET_CONNECTED_NET_ID_ERRORUnable to determine currently connected network ID (may not be connected)New to 3.1.1+#
Disable bindAll to WiFi network without disconnecting from WiFi
Enable bindAll to WiFi network without disconnecting from WiFi
Returns boolean, true or false, if device is able to connect to https://www.google.com via HTTP connection (since ping is unreliable)
Unknown errors will still be thrown like all other async functions
If you called
connectorenableand passedtrueforbindAll, your application will force the ping through wifi connection.If you did not pass
true(or passedfalse) forbindAll, and the wifi does not have internet connection, Android Lollipop+ (API 21+) will use cell connection to ping (due to Android using cell connection when wifi does not have internet) More Details
As
canPingWifiRouteris notoriously unreliable, this method uses HTTP connection to test if able to connect to router (as most routers should have web server running on port 80)Unknown errors will still be thrown like all other async functions
This is useful for testing to make sure that your Android app is able to connect to the private network after connecting to WiFi
This was added for testing the
bindAllfeature to support issues with Android Lollipop+ (API 21+) not routing calls through WiFi if WiFi does not have internet connection See Android BlogAttempts to connect router IP HTTP server on port 80 (example:
http://192.168.0.1/where192.168.0.1is the automatically detected IP address)New to 3.0.0+#
Returns boolean, true or false, if device is able to ping 8.8.8.8
Unknown errors will still be thrown like all other async functions
If you called
connectorenableand passedtrueforbindAll, your application will force the ping through wifi connection.If you did not pass
true(or passedfalse) forbindAll, and the wifi does not have internet connection, Android Lollipop+ (API 21+) will use cell connection to ping (due to Android using cell connection when wifi does not have internet) More DetailsReturns boolean, true or false, if device is able to ping the connected WiFi router IP (obtained from DHCP info)
Version 3.1.1+ uses HTTP connection to test if able to connect to router (as ping previous did not work)
Unknown errors will still be thrown like all other async functions
This is useful for testing to make sure that your Android app is able to connect to the private network after connecting to WiFi
This was added for testing the
bindAllfeature to support issues with Android Lollipop+ (API 21+) not routing calls through WiFi if WiFi does not have internet connection See Android BlogReturns IPv4 address of currently connected WiFi, or rejects promise if IP not found or wifi not connected
Returns IPv4 WiFi router IP from currently connected WiFi, or rejects promise if unable to determine, or wifi not connected
Thrown Errors
NO_VALID_IP_IDENTIFIEDif unable to determine a valid IP (ip returned from device is0.0.0.0)Returns a JSON object with IPv4 address and subnet
{"ip": "192.168.1.2", "subnet": "255.255.255.0" }or rejected promise if not found or not connected Thrown ErrorsNO_VALID_IP_IDENTIFIEDif unable to determine a valid IP (ip returned from device is0.0.0.0)Reconnect to the currently active access point, if we are currently disconnected.
Thrown Errors
ERROR_RECONNECTAndroid returned error when reconnectingReconnect to the currently active access point, even if we are already connected.
Thrown Errors
ERROR_REASSOCIATEAndroid returned error when reassociating
Get Android Network ID from passed SSID
ssidcan either be an SSID (string) or a network ID (integer)Disable the passed SSID network
Please note that most newer versions of Android will only allow you to disable networks created by your application
Thrown Errors
UNABLE_TO_DISABLEAndroid returned failure in disabling networkDISABLE_NETWORK_NOT_FOUNDUnable to determine network ID from passed SSID to disable
Request
ACCESS_FINE_LOCATIONpermssionThis Android permission is required to run
scan,startStartandgetScanResultsYou can request permission by running this function manually, or WifiWizard2 will automagically request permission when one of the functions above is called
Thrown Errors
PERMISSION_DENIEDuser denied permission on device
ssidcan either be an SSID (string) or a network ID (integer)bindAllshould be set totrueto tell Android to route all connections from your Android app, through the wifi connectionAndroid Lollipop+ (API 21+) will not route connections to the WiFi device if it does not have internet connection. Passing
truetobindAllwill force Android to route connections from your Android app through Wifi, regardless of internet connection.If you are having problems connecting to a local IP through WiFi because it does not have internet, try enabling
bindAlland this should fix the problem.During my testing, some versions of Android (5.0 - 7.1.2) would still route connections through WiFi without internet, but it was random that some versions would and would not work.
Testing Android Oreo+ (8.0.0+) if wifi does not have internet, 100% of the time it would NOT route connections through WiFi, so you must enable this for Oreo or newer to route connections from your application through wifi without internet.
When
bindAllis enabled, ALL connections from your app will be routed through WiFi, until you calldisconnectordisableSee the Google Android Blog for More Details
This feature ONLY works for Android Lollipop+ (API 21+), if device is running API older than 21,
bindallwill be ignored (as API older than 21 does this by default)Enable the passed SSID network
You MUST call
WifiWizard2.add(wifi)before callingenableas the wifi configuration must exist before you can enable it (or previously usedconnectwithout callingdisconnect)This method does NOT wait or verify connection to wifi network, pass
truetowaitForConnectionto only return promise once connection is verified in COMPLETED state to specificssidThrown Errors
UNABLE_TO_ENABLE- Android returned-1signifying failure enablingInstallation#
Master#
Run
cordova plugin add https://github.com/tripflex/wifiwizard2To install from the master branch (latest on GitHub)
To install a specific branch (add
#tagreplacingtagwith tag from this repo, example:cordova plugin add https://github.com/tripflex/wifiwizard2#v3.1.1Find available tags here: https://github.com/tripflex/WifiWizard2/tags
If you are wanting to have the latest and greatest stable version, then run the 'Releases' command below.
Releases#
Run cordova plugin add cordova-plugin-wifiwizard2
Meteor#
To install and use this plugin in a Meteor project, you have to specify the exact version from NPM repository: https://www.npmjs.com/package/cordova-plugin-wifiwizard2
As of April 4th 2019, the latest version is 3.1.1:
meteor add cordova:cordova-plugin-wifiwizard2@3.1.1
Errors/Rejections#
Methods now return formatted string errors as detailed below, instead of returning generic error messages. This allows you to check yourself what specific error was returned, and customize the error message. In an upcoming release I may add easy ways to override generic messages, or set your own, but for now, errors returned can be found below each method/function.
Generic Thrown Errors#
WIFI_NOT_ENABLED