forked from abandonware/noble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenter-exit.js
78 lines (62 loc) · 1.76 KB
/
enter-exit.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
/* eslint-disable handle-callback-err */
/*
Continuously scans for peripherals and prints out message when they enter/exit
In range criteria: RSSI < threshold
Out of range criteria: lastSeen > grace period
based on code provided by: Mattias Ask (http://www.dittlof.com)
*/
const noble = require('../index')({ extended: false });
const RSSI_THRESHOLD = -90;
const EXIT_GRACE_PERIOD = 2000; // milliseconds
const inRange = [];
noble.on('discover', function (peripheral) {
if (peripheral.rssi < RSSI_THRESHOLD) {
// ignore
return;
}
const id = peripheral.id;
const entered = !inRange[id];
if (entered) {
inRange[id] = {
peripheral: peripheral
};
console.log(
`"${peripheral.advertisement.localName}" entered (RSSI ${
peripheral.rssi
}) ${new Date()}`
);
}
inRange[id].lastSeen = Date.now();
});
setInterval(function () {
for (const id in inRange) {
if (inRange[id].lastSeen < Date.now() - EXIT_GRACE_PERIOD) {
const peripheral = inRange[id].peripheral;
console.log(
`"${peripheral.advertisement.localName}" exited (RSSI ${
peripheral.rssi
}) ${new Date()}`
);
delete inRange[id];
}
}
}, EXIT_GRACE_PERIOD / 2);
noble.on('stateChange', function (state) {
if (state === 'poweredOn') {
noble.startScanning([], true);
} else {
noble.stopScanning();
}
});
process.on('SIGINT', function () {
console.log('Caught interrupt signal');
noble.stopScanning(() => process.exit());
});
process.on('SIGQUIT', function () {
console.log('Caught interrupt signal');
noble.stopScanning(() => process.exit());
});
process.on('SIGTERM', function () {
console.log('Caught interrupt signal');
noble.stopScanning(() => process.exit());
});