-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnect.js
99 lines (84 loc) · 2.86 KB
/
connect.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
93
94
95
96
97
98
99
const chalk = require('chalk');
const wpa_cli = require('wireless-tools/wpa_cli');
const eventBus = require('./event-bus.js');
const iface = "wlan0";
module.exports = {};
module.exports.connectToAP = function (ssid, pass) {
return new Promise((res, rej) => {
console.log('remove_network');
wpa_cli.remove_network(iface, 'all', (err) => {
if (err) {
rej(err);
return;
}
console.log('add_network');
wpa_cli.add_network(iface, (err, id) => {
if (err) {
rej(err);
return;
}
id = parseInt(id.result);
console.log('set_network ssid');
wpa_cli.set_network(iface, id, '"ssid"', `'"${ssid}"'`, (err) => {
if (err) {
rej(err);
return;
}
console.log('set_network psk');
wpa_cli.set_network(iface, id, "psk", `'"${pass}"'`, (err) => {
if (err) {
rej(err);
return;
}
console.log('set_network key_mgmt');
wpa_cli.set_network(iface, id, "key_mgmt", "WPA-PSK", (err) => {
if (err) {
rej(err);
return;
}
console.log('enable_network');
wpa_cli.enable_network(iface, id, (err,data) => {
if (err) {
rej(err);
return;
}
let connected = false;
let dns = require('dns');
let try_count = 0;
let connectTimer = setInterval(function () {
dns.lookup('www.google.com', function (err) {
if (err) {
// server.log(['other','wifi'], chalk.red('No Connection'));
eventBus.emit('wifi:state', { msg: chalk.red('No Connection') });
try_count += 1;
} else {
clearInterval(connectTimer);
// server.log(['other','wifi'], chalk.green('Connected');
connectTimer = setInterval(function () {
wpa_cli.status('wlan0', (err, status) => {
if (err) {
rej(err);
return;
}
if (status.ip) {
clearInterval(connectTimer);
eventBus.emit('wifi:state', { msg: chalk.green(`Connected. IP: ${status.ip}`) });
res('connected');
}
});
}, 2000);
}
if (try_count >= 5) {
rej('no connection');
clearInterval(connectTimer);
}
});
}, 2000);
});
});
});
});
});
});
});
}