forked from kolarcz/node-btwatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (52 loc) · 1.71 KB
/
index.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
var EventEmitter = require('events').EventEmitter;
var Spawn = require('child_process').spawn;
function BTWatch () {
EventEmitter.call(this);
this.macAddresses = {};
}
BTWatch.prototype = {
__proto__: EventEmitter.prototype,
watch: function (macAddress) {
if (typeof this.macAddresses[macAddress] === 'undefined') {
this.macAddresses[macAddress] = '?';
this.check_(macAddress);
}
},
unwatch: function (macAddress) {
delete this.macAddresses[macAddress];
},
check_: function (macAddress) {
this.inRangeCheck_(macAddress, function (macAddress, inRange) {
if (typeof this.macAddresses[macAddress] !== 'undefined') {
if (this.macAddresses[macAddress] !== inRange) {
this.macAddresses[macAddress] = inRange;
this.emit('change::' + macAddress, inRange, macAddress);
this.emit('change', inRange, macAddress);
}
setTimeout(function(){this.check_(macAddress);}.bind(this), inRange ? 5000 : 0);
}
}.bind(this));
},
inRangeCheck_: function (macAddress, callback, prevCntFails) {
prevCntFails = prevCntFails || 0;
var ls = Spawn('l2ping', ['-c', '1', '-t', '5', macAddress]);
var result = '';
ls.stdout.on('data', function (data) {
result += data;
});
ls.on('close', function () {
var inRange = Boolean(String(result).match(' time '));
if (inRange) {
callback(macAddress, true);
} else if(++prevCntFails < 5) {
this.inRangeCheck_(macAddress, callback, prevCntFails);
} else {
callback(macAddress, false);
}
}.bind(this));
},
inRange: function (macAddress) {
return this.macAddresses[macAddress];
}
};
module.exports = new BTWatch();