community-cordova-plugin-wifi 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,345 @@
1
+ #import "WifiPlugin.h"
2
+ #include <ifaddrs.h>
3
+ #include <arpa/inet.h>
4
+ #import <CoreLocation/CoreLocation.h>
5
+ #import <SystemConfiguration/CaptiveNetwork.h>
6
+ #import <Network/Network.h>
7
+ #import <SystemConfiguration/SystemConfiguration.h>
8
+ #import <netinet/in.h>
9
+
10
+ @interface WifiPlugin() <CLLocationManagerDelegate>
11
+
12
+ @property (strong, nonatomic) CLLocationManager *locationManager;
13
+ @property (strong, nonatomic) CDVInvokedUrlCommand *currentCommand;
14
+
15
+ @end
16
+
17
+ @implementation WifiPlugin
18
+
19
+ - (void)pluginInitialize {
20
+ self.locationManager = [[CLLocationManager alloc] init];
21
+ self.locationManager.delegate = self;
22
+ self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
23
+ }
24
+
25
+
26
+ - (void)getWifiList:(CDVInvokedUrlCommand*)command {
27
+ // This is not supported on iOS due to privacy reasons.
28
+ [self sendNotSupportedError:command];
29
+ }
30
+
31
+ - (void)connectToNetwork:(CDVInvokedUrlCommand*)command {
32
+ // This is not supported on iOS.
33
+ [self sendNotSupportedError:command];
34
+ }
35
+
36
+ - (void)disconnectFromNetwork:(CDVInvokedUrlCommand*)command {
37
+ // This is not supported on iOS.
38
+ [self sendNotSupportedError:command];
39
+ }
40
+
41
+ - (void)isWifiEnabled:(CDVInvokedUrlCommand*)command {
42
+ // iOS does not provide a way to check if WiFi is enabled.
43
+ [self sendNotSupportedError:command];
44
+ }
45
+
46
+ - (void)wifiToggle:(CDVInvokedUrlCommand*)command {
47
+ // Toggling WiFi is not supported on iOS.
48
+ [self sendNotSupportedError:command];
49
+ }
50
+
51
+ - (void)isConnectedToInternet:(CDVInvokedUrlCommand*)command {
52
+ // Define zero address for internet reachability check
53
+ struct sockaddr_in zeroAddress;
54
+ bzero(&zeroAddress, sizeof(zeroAddress));
55
+ zeroAddress.sin_len = sizeof(zeroAddress);
56
+ zeroAddress.sin_family = AF_INET; // IPv4 address
57
+
58
+ // Use SCNetworkReachability to check reachability to the zero address
59
+ SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr *)&zeroAddress);
60
+ SCNetworkReachabilityFlags flags;
61
+
62
+ // Prepare the plugin result variable
63
+ CDVPluginResult* pluginResult = nil;
64
+
65
+ if (reachabilityRef) {
66
+ // Check if the reachability can get flags successfully
67
+ if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
68
+ // Flags are available, check if the network is reachable
69
+ BOOL isReachable = flags & kSCNetworkFlagsReachable;
70
+ BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
71
+
72
+ // The network is considered reachable if it's reachable without requiring a connection
73
+ BOOL isConnected = isReachable && !needsConnection;
74
+
75
+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isConnected];
76
+ } else {
77
+ // Unable to get flags, consider the internet as not reachable
78
+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot determine internet connectivity."];
79
+ }
80
+
81
+ // Release the reachability reference
82
+ CFRelease(reachabilityRef);
83
+ } else {
84
+ // Reachability reference creation failed
85
+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to create reachability reference."];
86
+ }
87
+
88
+ // Send the plugin result back to the Cordova callback
89
+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
90
+ }
91
+
92
+
93
+ - (void)checkAndRequestWifiPermission:(CDVInvokedUrlCommand*)command {
94
+ // Permissions for WiFi are not explicitly required on iOS for basic operations.
95
+ [self sendNotSupportedError:command];
96
+ }
97
+
98
+ - (void)getConnectedDevices:(CDVInvokedUrlCommand*)command {
99
+ // Scanning for devices on the network is not supported without specific network privileges.
100
+ [self sendNotSupportedError:command];
101
+ }
102
+
103
+ - (void)getWifiStrength:(CDVInvokedUrlCommand*)command {
104
+ // Directly accessing WiFi strength is not possible through public APIs.
105
+ [self sendNotSupportedError:command];
106
+ }
107
+
108
+ - (void)ping:(CDVInvokedUrlCommand*)command {
109
+ // Implementing a ping function would require using ICMP or similar, which is beyond this scope.
110
+ [self sendNotSupportedError:command];
111
+ }
112
+
113
+ - (void)canConnectToInternet:(CDVInvokedUrlCommand*)command {
114
+ // This would be similar to isConnectedToInternet and depends on external reachability.
115
+ [self sendNotSupportedError:command];
116
+ }
117
+
118
+ - (void)canConnectToRouter:(CDVInvokedUrlCommand*)command {
119
+ // Checking connection to a specific router is not supported without specific permissions.
120
+ [self sendNotSupportedError:command];
121
+ }
122
+
123
+
124
+ - (void)getAllWifiDetails:(CDVInvokedUrlCommand*)command {
125
+ // Assuming location permissions are handled as before
126
+ NSDictionary *networkInfo = [self fetchSSIDInfo];
127
+ NSString *ipAddress = [self getIPAddress];
128
+
129
+ NSDictionary *wifiDetails = @{
130
+ @"isWifiEnabled": @([self isConnectedToWiFi]), // Placeholder; actual implementation may vary
131
+ @"isSupportWifi": @YES,
132
+ @"SSID": networkInfo[@"SSID"] ?: @"Unavailable",
133
+ @"BSSID": networkInfo[@"BSSID"] ?: @"Unavailable",
134
+ @"IP": ipAddress ?: @"Unavailable",
135
+ @"MAC": @"Unavailable", // Not accessible on iOS
136
+ @"NetworkID": @-1, // Not applicable
137
+ @"LinkSpeed": @-1, // Not accessible
138
+ @"SignalStrength": @-1, // Not directly accessible; could use RSSI if available
139
+ @"Gateway": @"Unavailable", // Not directly accessible
140
+ @"RSSI": @-1, // Could parse from networkInfo if available
141
+ @"Speed": @-1, // Not directly accessible
142
+ @"Frequency": @-1, // Not directly accessible
143
+ @"Channel": @-1, // Not directly accessible
144
+ @"DNS1": @"Unavailable", // Not directly accessible
145
+ @"DNS2": @"Unavailable", // Not directly accessible
146
+ };
147
+
148
+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:wifiDetails];
149
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
150
+ }
151
+
152
+
153
+ - (void)getIpInfo:(CDVInvokedUrlCommand*)command {
154
+ self.currentCommand = command;
155
+
156
+ if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
157
+ [self.locationManager requestWhenInUseAuthorization];
158
+ } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
159
+ [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
160
+ // Location permissions are granted, proceed to fetch WiFi details
161
+ } else {
162
+ // Handle case where location permissions are denied
163
+ [self sendError:@"Location services are not enabled." toCommand:command];
164
+ }
165
+
166
+ // Check for Location Services
167
+ if ([CLLocationManager locationServicesEnabled]) {
168
+ [self.locationManager requestWhenInUseAuthorization];
169
+ [self.locationManager startUpdatingLocation];
170
+ } else {
171
+ // Location services are not enabled. Return error or default data.
172
+ [self sendError:@"Location request services are not enabled." toCommand:command];
173
+ }
174
+ }
175
+
176
+ #pragma mark - CLLocationManagerDelegate
177
+ - (BOOL)isConnectedToWiFi {
178
+ NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
179
+ if (!interfaceNames) {
180
+ return NO;
181
+ }
182
+
183
+ NSDictionary *networkInfo;
184
+ for (NSString *interfaceName in interfaceNames) {
185
+ networkInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
186
+ if (networkInfo && [networkInfo count]) { break; }
187
+ }
188
+
189
+ return (networkInfo != nil);
190
+ }
191
+
192
+ - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
193
+ [self.locationManager stopUpdatingLocation]; // Stop location updates to conserve battery life
194
+
195
+ CLLocation *location = [locations lastObject];
196
+ [self reverseGeocodeLocation:location forCommand:self.currentCommand];
197
+ }
198
+
199
+ - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
200
+ [self sendError:@"Failed to get location." toCommand:self.currentCommand];
201
+ }
202
+
203
+ #pragma mark - Utility Methods
204
+
205
+ - (NSString *)getIPAddress {
206
+ NSString *address = nil;
207
+ struct ifaddrs *interfaces = NULL;
208
+ struct ifaddrs *temp_addr = NULL;
209
+ int success = 0;
210
+
211
+ success = getifaddrs(&interfaces);
212
+ if (success == 0) {
213
+ temp_addr = interfaces;
214
+ while (temp_addr != NULL) {
215
+ if(temp_addr->ifa_addr->sa_family == AF_INET) {
216
+ if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
217
+ address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
218
+ }
219
+ }
220
+ temp_addr = temp_addr->ifa_next;
221
+ }
222
+ }
223
+ freeifaddrs(interfaces);
224
+ return address ?: @"Unavailable";
225
+ }
226
+
227
+
228
+ - (NSString *)checkConnectionType {
229
+ struct sockaddr_in zeroAddress;
230
+ bzero(&zeroAddress, sizeof(zeroAddress));
231
+ zeroAddress.sin_len = sizeof(zeroAddress);
232
+ zeroAddress.sin_family = AF_INET;
233
+
234
+ SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress);
235
+ if (reachabilityRef != NULL) {
236
+ SCNetworkReachabilityFlags flags;
237
+ if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
238
+ if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) {
239
+ // The target host is not reachable.
240
+ CFRelease(reachabilityRef);
241
+ return @"none";
242
+ }
243
+
244
+ NSString *connectionType = @"unknown";
245
+
246
+ if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) {
247
+ // If the target host is reachable and no connection is required, then we'll assume it's WiFi
248
+ connectionType = @"wifi";
249
+ }
250
+
251
+ if (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) ||
252
+ ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)) {
253
+ // ... and the connection is on-demand (or on-traffic) if the
254
+ // calling application is using the CFSocketStream or higher APIs.
255
+ if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) {
256
+ // ... and no [user] intervention is needed
257
+ connectionType = @"wifi";
258
+ }
259
+ }
260
+
261
+ #if TARGET_OS_IPHONE
262
+ if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
263
+ // ... but WWAN connections are OK if the calling application
264
+ // is using the CFNetwork APIs.
265
+ connectionType = @"cellular";
266
+ }
267
+ #endif
268
+
269
+ CFRelease(reachabilityRef);
270
+ return connectionType;
271
+ }
272
+ CFRelease(reachabilityRef);
273
+ }
274
+
275
+ return @"unknown";
276
+ }
277
+
278
+
279
+ - (void)reverseGeocodeLocation:(CLLocation *)location forCommand:(CDVInvokedUrlCommand *)command {
280
+ CLGeocoder *geocoder = [[CLGeocoder alloc] init];
281
+
282
+ [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> *placemarks, NSError *error) {
283
+ if (error) {
284
+ [self sendError:@"Failed to get location information." toCommand:command];
285
+ return;
286
+ }
287
+
288
+ CLPlacemark *placemark = [placemarks firstObject];
289
+ NSDictionary *networkInfo = [self fetchSSIDInfo];
290
+
291
+ NSMutableArray *ipInfos = [NSMutableArray array];
292
+ NSDictionary *ipInfo = @{
293
+ @"type": [self checkConnectionType],
294
+ @"signal": @-1, // Not directly accessible
295
+ @"speed": @-1, // Not directly accessible
296
+ @"ssid": networkInfo[@"SSID"] ?: @"",
297
+ @"internalip": [self getIPAddress] ?: @"",
298
+ @"macaddress": @"Unavailable", // Not accessible on iOS
299
+ @"networkid": @-1, // Not applicable
300
+ @"frequency": @-1, // Not directly accessible
301
+ @"bssid": networkInfo[@"BSSID"] ?: @"",
302
+ @"dns1": @"Unavailable", // Not directly accessible
303
+ @"dns2": @"Unavailable", // Not directly accessible
304
+ @"timezone": [[NSTimeZone localTimeZone] name],
305
+ @"latitude": location ? @(location.coordinate.latitude) : @0,
306
+ @"longitude": location ? @(location.coordinate.longitude) : @0,
307
+ @"city": placemark.locality ?: @"",
308
+ @"street": placemark.thoroughfare ?: @"",
309
+ @"country": placemark.country ?: @"",
310
+ @"region": placemark.administrativeArea ?: @"",
311
+ @"zipcode": placemark.postalCode ?: @"",
312
+ @"state": placemark.administrativeArea ?: @"",
313
+ };
314
+
315
+ [ipInfos addObject:ipInfo];
316
+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:ipInfos];
317
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
318
+ }];
319
+ }
320
+
321
+ - (NSDictionary *)fetchSSIDInfo {
322
+ NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
323
+ NSDictionary *SSIDInfo = nil;
324
+ for (NSString *interfaceName in interfaceNames) {
325
+ SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
326
+ if (SSIDInfo.count > 0) {
327
+ break;
328
+ }
329
+ }
330
+ return SSIDInfo;
331
+ }
332
+
333
+
334
+ - (void)sendError:(NSString *)errorMessage toCommand:(CDVInvokedUrlCommand *)command {
335
+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage];
336
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
337
+ }
338
+
339
+ - (void)sendNotSupportedError:(CDVInvokedUrlCommand*)command {
340
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"This feature is not supported on iOS."];
341
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
342
+ }
343
+
344
+
345
+ @end
@@ -0,0 +1,98 @@
1
+ interface WifiNetwork {
2
+ SSID: string;
3
+ BSSID: string;
4
+ capabilities: string;
5
+ frequency: string;
6
+ level: number;
7
+ security: string;
8
+ channelWidth: string;
9
+ distance: string;
10
+ hasPassword: boolean;
11
+ }
12
+ interface NetworkDetails {
13
+ type: string;
14
+ state: string;
15
+ isConnected: boolean;
16
+ isConnectedToInternet?: boolean;
17
+ canConnectToRouter?: boolean;
18
+ isConnectedToWifi?: boolean;
19
+ }
20
+ interface ConnectedDeviceInfo {
21
+ ipAddress: string;
22
+ deviceName: string;
23
+ localHost: boolean;
24
+ loopbackAddress: boolean;
25
+ hostAddress: string;
26
+ canonicalHostName: string;
27
+ multicastAddress: boolean;
28
+ siteLocalAddress: boolean;
29
+ }
30
+
31
+ interface WifiDetails {
32
+ iswifienabled: boolean;
33
+ issupportwifi: boolean;
34
+ ssid: string;
35
+ bssid: string;
36
+ ip: string;
37
+ mac: string;
38
+ networkid: number;
39
+ linkspeed: number;
40
+ signalstrength: number;
41
+ gateway: string;
42
+ rssi: number;
43
+ speed: number;
44
+ frequency: number;
45
+ channel: number;
46
+ dns1: string;
47
+ dns2: string;
48
+ }
49
+
50
+
51
+ interface PingResponse {
52
+ line?: string;
53
+ fullResponse?: string;
54
+ progress?: number;
55
+ status?: string;
56
+ linesRead?: number;
57
+ }
58
+
59
+ interface IpInfo {
60
+ type: string;
61
+ signal: number;
62
+ speed: number;
63
+ ssid: string;
64
+ internalip: string;
65
+ macaddress: string;
66
+ networkid: number;
67
+ frequency: number;
68
+ bssid: string;
69
+ dns1: string;
70
+ dns2: string;
71
+ timezone: string;
72
+ latitude?: number;
73
+ longitude?: number;
74
+ city?: string;
75
+ street?: string;
76
+ country?: string;
77
+ region?: string;
78
+ zipcode?: string;
79
+ state?: string;
80
+ }
81
+ export default class WifiManager {
82
+ getWifiList(): Promise<WifiNetwork[]>;
83
+ getIpInfo(): Promise<IpInfo[]>;
84
+ getAllWifiDetails(): Promise<WifiDetails>;
85
+ isConnectedToInternet(): Promise<boolean>;
86
+ canConnectToInternet(): Promise<number>;
87
+ canConnectToRouter(): Promise<boolean>;
88
+ connectToNetwork(ssid: string, password: string): Promise<void>;
89
+ disconnectFromNetwork(): Promise<void>;
90
+ isWifiEnabled(): Promise<boolean>;
91
+ wifiToggle(): Promise<void>;
92
+ checkAndRequestWifiPermission(): Promise<string>;
93
+ getConnectedDevices(): Promise<ConnectedDeviceInfo[]>;
94
+ getWifiStrength(): Promise<number>;
95
+ getSignalStrength(): Promise<number>;
96
+ ping(address: string, count: number, timeout: number, successCallback: (response: PingResponse) => void, errorCallback: (error: any) => void): void;
97
+
98
+ }
package/www/plugin.js ADDED
@@ -0,0 +1,101 @@
1
+ var PLUGIN_NAME = 'WifiPlugin';
2
+
3
+ var exec = require('cordova/exec');
4
+
5
+ class WifiManager {
6
+ getWifiList() {
7
+ return new Promise((resolve, reject) => {
8
+ exec(resolve, reject, PLUGIN_NAME, 'getWifiList', []);
9
+ });
10
+ }
11
+ ping(address, count, timeout) {
12
+ return new Promise((resolve, reject) => {
13
+ exec(resolve, reject, PLUGIN_NAME, 'ping', [address, count, timeout]);
14
+ });
15
+ }
16
+ getIpInfo() {
17
+ return new Promise((resolve, reject) => {
18
+ exec(resolve, reject, PLUGIN_NAME, 'getIpInfo', []);
19
+ });
20
+ }
21
+ getSignalStrength() {
22
+ return new Promise((resolve, reject) => {
23
+ exec(resolve, reject, PLUGIN_NAME, 'getSignalStrength', []);
24
+ });
25
+ }
26
+ getWifiStrength() {
27
+ return new Promise((resolve, reject) => {
28
+ exec(resolve, reject, PLUGIN_NAME, 'getWifiStrength', []);
29
+ });
30
+ }
31
+
32
+ getAllWifiDetails() {
33
+ return new Promise((resolve, reject) => {
34
+ exec(resolve, reject, PLUGIN_NAME, 'getAllWifiDetails', []);
35
+ });
36
+ }
37
+
38
+ isConnectedToInternet() {
39
+ return new Promise((resolve, reject) => {
40
+ exec(function (result) {
41
+ resolve(result == '1');
42
+ }, reject, PLUGIN_NAME, 'isConnectedToInternet', []);
43
+ });
44
+ }
45
+
46
+ canConnectToInternet() {
47
+ return new Promise((resolve, reject) => {
48
+ exec(function (result) {
49
+ resolve(result == '1');
50
+ }, reject, PLUGIN_NAME, 'canConnectToInternet', []);
51
+ });
52
+ }
53
+
54
+ canConnectToRouter() {
55
+ return new Promise((resolve, reject) => {
56
+ exec(function (result) {
57
+ resolve(result == '1');
58
+ }, reject, PLUGIN_NAME, 'canConnectToRouter', []);
59
+ });
60
+ }
61
+
62
+ connectToNetwork(ssid, password) {
63
+ return new Promise((resolve, reject) => {
64
+ exec(resolve, reject, PLUGIN_NAME, 'connectToNetwork', [ssid, password]);
65
+ });
66
+ }
67
+
68
+ disconnectFromNetwork() {
69
+ return new Promise((resolve, reject) => {
70
+ exec(resolve, reject, PLUGIN_NAME, 'disconnectFromNetwork', []);
71
+ });
72
+ }
73
+
74
+ isWifiEnabled() {
75
+ return new Promise((resolve, reject) => {
76
+ exec(function (result) {
77
+ resolve(result == '1');
78
+ }, reject, PLUGIN_NAME, 'isWifiEnabled', []);
79
+ });
80
+ }
81
+
82
+ wifiToggle() {
83
+ return new Promise((resolve, reject) => {
84
+ exec(resolve, reject, PLUGIN_NAME, 'wifiToggle', []);
85
+ });
86
+ }
87
+
88
+ checkAndRequestWifiPermission() {
89
+ return new Promise((resolve, reject) => {
90
+ exec(resolve, reject, PLUGIN_NAME, 'checkAndRequestWifiPermission', []);
91
+ });
92
+ }
93
+
94
+ getConnectedDevices() {
95
+ return new Promise((resolve, reject) => {
96
+ exec(resolve, reject, PLUGIN_NAME, 'getConnectedDevices', []);
97
+ });
98
+ }
99
+ }
100
+
101
+ module.exports = new WifiManager();