This repository has been archived by the owner on Aug 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBeaconScanner.js
68 lines (55 loc) · 1.51 KB
/
BeaconScanner.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
module.exports = function (RED) {
const BS = require('node-beacon-scanner');
const scanner = new BS();
let setStatus = (node, scanning, error) => {
node.status({
fill: scanning ? "blue" : error ? "red" : "grey",
shape: scanning ? "dot" : "ring",
text: scanning ? "scanning" : error ? "error" : "stopped"
});
node.scanning = scanning;
};
let start = (node, scanner) => {
if (node.scanning) return;
scanner.startScan().then(() => {
setStatus(node, true)
node.log('Scanner started');
}).catch((error) => {
setStatus(node, false, error);
node.error('Error starting scanner', { payload: {}, error: error });
});
};
let stop = (node, scanner) => {
if (!node.scanning) return;
scanner.stopScan();
setStatus(node, false)
node.log('Scanner stopped');
}
function BeaconScanner(config) {
RED.nodes.createNode(this, config);
let node = this;
// Initial status
setStatus(node, false);
// Read input
node.on("input", function (msg) {
if (msg.payload === true || msg.payload === 1 || msg.payload === "on") {
start(node, scanner);
} else {
stop(node, scanner);
}
});
// Send message when receive an advertisement
scanner.onadvertisement = (data) => {
msg = {};
msg.topic = node.topic;
msg.payload = JSON.stringify(data);
node.send(msg);
node.trace('Sending message payload', msg.payload);
};
// Stop scanning on close
node.on("close", function () {
stop(node, scanner);
});
}
RED.nodes.registerType("BeaconScanner", BeaconScanner);
}