-
Notifications
You must be signed in to change notification settings - Fork 0
/
button.js
79 lines (69 loc) · 2.48 KB
/
button.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
const EventEmitter = require('events');
const pcap = require('pcap');
const convertIntToHex = require('./helpers');
class Button extends EventEmitter {
constructor(macAddresses) {
super();
if (Array.isArray(macAddresses)) {
this.macAddresses = macAddresses.reduce((accumulator, current) => {
accumulator[current.address] = {
name: current.name || 'Name not provided',
isDeboucing: false,
};
return accumulator;
}, {});
} else if (typeof macAddresses === 'object') {
this.macAddresses = {
[macAddresses.address]: {
name: macAddresses.name || 'Name not provided',
isDeboucing: false,
}
};
} else {
this.macAddresses = {
[macAddresses]: {
name: 'Name not provided',
isDeboucing: false,
}
};
}
this.createSession();
}
createSession(filter) {
this.session = pcap.createSession(null, filter);
this.session.on('packet', (rawPacket) => {
const decoded = this._decodePacket(rawPacket);
const targetMacOrFalse = this._filterPacket(decoded);
if (targetMacOrFalse) {
if (!this.macAddresses[targetMacOrFalse].debouncing) {
const emittingPayload = {
address: targetMacOrFalse,
name: this.macAddresses[targetMacOrFalse].name
};
this.emit('pressed', emittingPayload);
this.macAddresses[targetMacOrFalse].debouncing = true;
setTimeout(() => {
this.macAddresses[targetMacOrFalse].debouncing = false;
}, 5000);
}
}
});
}
_decodePacket(rawPacket) {
return pcap.decode.packet(rawPacket);
}
_filterPacket(packet) {
let packetMac = null;
if (packet.payload.ethertype === 2054) {
packetMac = convertIntToHex(packet.payload.payload.sender_ha.addr);
}
if (packet.payload.ethertype === 2048) {
packetMac = convertIntToHex(packet.payload.shost.addr);
}
if (packetMac && this.macAddresses[packetMac]) {
return packetMac;
}
return false;
}
}
module.exports = Button;