-
Notifications
You must be signed in to change notification settings - Fork 0
/
wifiController.js
92 lines (84 loc) · 2.79 KB
/
wifiController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Load the wifi control package
var WiFiControl = require('wifi-control'),
freeToScan = true,
scanner,
socket,
events;
// Set up the socket and event objects
function init(socketInstance, eventEmitterInstance) {
socket = socketInstance;
events = eventEmitterInstance || false;
}
// Initialize wifi-control package
function initialiseWifi() {
WiFiControl.init({'debug': true});
}
// Returns true if the wifi network we are connected to is a Bebop 2 network.
function alreadyConnectedToDrone() {
var ifaceState = WiFiControl.getIfaceState();
if (ifaceState.ssid != undefined && ifaceState.ssid.indexOf('Bebop') == 0) {
return true;
}
return false;
}
function networkScan() {
// We are scanning, so set freeToScan to false
freeToScan = false;
WiFiControl.scanForWiFi( function(err, response) {
if (err) console.log(err);
var networks = response.networks;
// Loop through all found networks.
// If we find a Bebop 2 network, set the wifi name and remove the scanner interval.
for (var i = 0; i < networks.length; i++) {
var network = networks[i];
var SSID = network.ssid;
if (SSID.indexOf('Bebop') == 0) {
droneWiFiName = SSID;
removeScanner();
}
}
// Finished doing scanning logic, we are free to scan again
freeToScan = true;
})
}
// We have detected the drone's wifi signal
// Remove the interval for the scanner and connect to the network
function removeScanner() {
socket.emit('droneWifiDetected', droneWiFiName);
clearInterval(scanner);
connectToNetwork(droneWiFiName);
}
function connectToNetwork(SSID) {
var results = WiFiControl.connectToAP({ssid: SSID}, function(err, response) {
if (err) console.log(err);
if (response.success) {
socket.emit('droneWifiConnected');
if (events) {
events.emit('wifiConnected');
}
}
});
}
function attemptDroneConnection() {
initialiseWifi();
// Try scanning for access points:
if (alreadyConnectedToDrone()) {
// WiFi is already connected to drone, so send through socket
socket.emit('droneWifiConnected');
}
else {
// Here, the first network scan will be 4 seconds after the app is initialised.
// After that, every 1s there will be a check to see if a scan is already in place.
// If it is not, we will scan again.
setTimeout(function() {
networkScan();
scanner = setInterval(function(){
if (freeToScan) {
networkScan();
}
}, 1000);
}, 4000);
}
}
module.exports.init = init;
module.exports.connectDroneWifi = attemptDroneConnection;