/
lock_scanner.js
53 lines (48 loc) · 1.4 KB
/
lock_scanner.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
const noble = require('noble');
const util = require('util');
const delay = require('./delay');
const EventEmitter = require('events');
const Lock = require('./lock');
function LockScanner() {
EventEmitter.call(this);
this.start = function start(){
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
noble.startScanning(["bd4ac6100b4511e38ffd0800200c9a66"], false);
this.emit('start');
} else {
noble.stopScanning();
this.emit('stop');
}
}.bind(this));
noble.on('discover', async peripheral => {
// things seem pretty unstable if one starts looking
// at the peripheral immediately.
await delay(500);
if(!peripheral.advertisement.manufacturerData || peripheral.advertisement.manufacturerData.length < 20) {
return;
}
peripheral.connect(async (err)=>{
if(err){
this.emit('error', err);
return;
}
try {
var lock = new Lock(peripheral);
if(!lock.id) {
await peripheral.disconnect();
return;
}
await lock.discover();
await lock.secNotify(true);
await lock.mcuNotify(true);
this.emit('lockFound', lock);
} catch (e){
this.emit('error', e);
}
});
});
}
}
util.inherits(LockScanner, EventEmitter);
module.exports = new LockScanner;