-
Notifications
You must be signed in to change notification settings - Fork 1
/
ble.js
262 lines (224 loc) · 7.38 KB
/
ble.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
const noble = require('@abandonware/noble');
const { exec } = require('child_process');
const { Console } = require('console');
const { tagFactory } = require('./tags/known-tags');
const STACK_SIZE = 3;
const device_data = {};
function lock_device() {
exec('python3 mac.py lock');
}
let lastTrackTime = Date.now();
let totalRetryAttempts = 2;
let currentRetryAttempts = totalRetryAttempts;
let scanTimeout = 2_000;
function onRSSIUpdate(uuid, threshold = -70, lockCB = () => {}) {
if (currentRetryAttempts != totalRetryAttempts) {
currentRetryAttempts = totalRetryAttempts;
}
let rssi = device_data[uuid].current_rssi;
let median_rssi = get_median(device_data[uuid].rssi_list);
if (Math.abs(rssi) > Math.abs(threshold)) {
console.log('Device lock due to rssi threshold, ', rssi);
lock_device();
lockCB();
}
console.log({
date: Date(),
rssi,
median_rssi,
uuid,
});
}
function get_median(arr) {
const array_length = arr.length;
median = Math.floor(array_length / 2);
if (array_length % 2 == 0) {
const next_value = median + 1 > array_length ? median + 1 : median - 1;
median = (arr[median] + arr[next_value]) / 2;
} else {
median = arr[median];
}
return median;
}
function validateDevice(peripheral, uuid = false, localName = false) {
if (uuid != false) {
return peripheral.uuid == uuid;
}
if (localName != false) {
return peripheral.advertisement.localName == localName;
process.exit(0);
}
}
function handle_device_timeout() {
setInterval(() => {
if (Date.now() - lastTrackTime > scanTimeout) {
console.log(Date.now() - lastTrackTime, scanTimeout);
console.log('Device timed out. Retry connection');
if (!currentRetryAttempts) {
console.log('Lock device due to timeout. Retry connection');
lock_device();
currentRetryAttempts = totalRetryAttempts;
} else {
currentRetryAttempts--;
lastTrackTime = Date.now();
}
}
}, 2_000);
}
async function run(uuid = false, localName = false, awayRssi) {
await noble.startScanningAsync([], true); // any service UUID, allow duplicates, listens to all advertismenet ids
// Listens to advertisement events
noble.removeAllListeners();
noble.on('discover', (peripheral) => {
if (validateDevice(peripheral, uuid, localName)) {
lastTrackTime = Date.now();
let isSameEvent = false;
device_data[peripheral.uuid] = device_data[peripheral.uuid] || {
last_rssi: 0,
current_rssi: 0,
rssi_list: [],
last_events: [],
};
if (device_data[peripheral.uuid].last_events.length >= STACK_SIZE) {
device_data[peripheral.uuid].last_events.shift();
}
device_data[peripheral.uuid].last_events.push({ date: Date.now(), rssi: peripheral.rssi });
//Detect if is same event
if (device_data[peripheral.uuid].last_events.length > 1) {
const last_event = device_data[peripheral.uuid].last_events.length - 1;
const previous_event = device_data[peripheral.uuid].last_events.length - 2;
isSameEvent =
device_data[peripheral.uuid].last_events[last_event].date - device_data[peripheral.uuid].last_events[previous_event].date < 10;
}
if (isSameEvent == false) {
device_data[peripheral.uuid].last_rssi = device_data[peripheral.uuid].current_rssi;
device_data[peripheral.uuid].current_rssi = peripheral.rssi;
if (device_data[peripheral.uuid].rssi_list.length >= STACK_SIZE) {
device_data[peripheral.uuid].rssi_list.shift();
}
device_data[peripheral.uuid].rssi_list.push(peripheral.rssi);
onRSSIUpdate(peripheral.uuid, awayRssi);
}
lastTrackTime = Date.now();
}
});
handle_device_timeout();
}
async function run_active(uuid = false, localName = false, awayRssi = -70) {
await noble.startScanningAsync([], false); // any service UUID, allow duplicates, listens to all advertismenet ids
// Listens to advertisement events
noble.removeAllListeners();
noble.on('discover', async (peripheral) => {
if (validateDevice(peripheral, uuid, localName)) {
await noble.stopScanningAsync();
await peripheral.connectAsync();
console.log('connected');
device_data[peripheral.uuid] = device_data[peripheral.uuid] || {
last_rssi: 0,
current_rssi: 0,
rssi_list: [],
last_events: [],
};
const knownTag = await tagFactory(localName, peripheral);
await knownTag.onConnect();
peripheral.updateRssi();
setInterval(() => {
peripheral.updateRssi();
}, 1_000);
peripheral.on('rssiUpdate', (rssi) => {
//Collect Median
if (device_data[peripheral.uuid].last_events.length >= STACK_SIZE) {
device_data[peripheral.uuid].last_events.shift();
}
device_data[peripheral.uuid].last_events.push({ date: Date.now(), rssi: rssi });
device_data[peripheral.uuid].last_rssi = device_data[peripheral.uuid].current_rssi;
device_data[peripheral.uuid].current_rssi = rssi;
if (device_data[peripheral.uuid].rssi_list.length >= STACK_SIZE) {
device_data[peripheral.uuid].rssi_list.shift();
}
device_data[peripheral.uuid].rssi_list.push(rssi);
onRSSIUpdate(peripheral.uuid, awayRssi, () => {
//knownTag.sendAlert();
});
lastTrackTime = Date.now();
});
// TODO: Handle connect/disconnect
peripheral.on('disconnect', () => {
console.log('Device Disconnected. Reconnect');
process.exit(0);
});
handle_device_timeout(lastTrackTime, scanTimeout);
}
});
//Handle devices out of reach
}
function scan_devices() {
console.log('Scanning during 10 seconds');
noble.startScanningAsync([], false); // any service UUID, allow duplicates, listens to all advertismenet ids
// Listens to advertisement events
noble.on('discover', (peripheral) => {
console.log(peripheral.advertisement.localName, peripheral.uuid, peripheral.rssi);
});
setTimeout(() => {
console.log('Stop scanning for devices');
noble.stopScanningAsync();
process.exit(0);
}, 10_000);
}
function calibrate(uuid, localName) {
const start = Date.now();
console.log('Stand close to the device');
noble.startScanningAsync([], true); // any service UUID, allow duplicates, listens to all advertismenet ids
const near_rssi = [];
const away_rssi = [];
let mode = 'near';
// Listens to advertisement events
noble.on('discover', (peripheral) => {
if (validateDevice(peripheral, uuid, localName)) {
if (mode == 'near') {
near_rssi.push(peripheral.rssi);
} else if (mode == 'away') {
away_rssi.push(peripheral.rssi);
}
}
});
calibrateInterval = setInterval(() => {
if (Date.now() - start > 30_000 && mode != 'away') {
console.log('Stand away of the device');
mode = 'away';
}
if (Date.now() - start > 60_000) {
clearInterval(calibrateInterval);
console.log('Calibration Done');
noble.stopScanningAsync();
console.log('Device UUID: ', uuid);
console.log('Near RSSI: ', get_median(near_rssi));
console.log('Away RSSI: ', get_median(away_rssi));
process.exit(0);
}
}, 1_000);
}
function debug(uuid) {
console.log('Stand close to the device');
noble.on('stateChange', (state) => {
if (state === 'poweredOn') {
noble.startScanning([], true); // any service UUID, allow duplicates, listens to all advertismenet ids
}
});
if (noble.state === 'poweredOn') {
noble.startScanning([], true); // any service UUID, allow duplicates, listens to all advertismenet ids
}
// Listens to advertisement events
noble.on('discover', (peripheral) => {
if (peripheral.uuid == uuid) {
console.log(peripheral.rssi);
}
});
}
module.exports = {
scan_devices,
calibrate,
run,
run_active,
debug,
};