-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
99 lines (67 loc) · 2.71 KB
/
index.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
/**
* Bluetooth scanner using Bluez tools
* Only Bluez supported platforms are supported by this module
*
* Based on BLE-Scanner from Martin Gradler
*
* Author: Pedro Paixao
* License: MIT
*/
var spawn = require('child_process').spawn;
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var BluetoothScanner = module.exports = function(hcidev) {
var self = this;
// Inherit EventEmitter
EventEmitter.call(self);
self.init = function(hcidev) {
var tool_path = "";
if (hcidev === 'fake') {
tool_path = './';
}
// Bring selected device UP
var hciconfig = spawn(tool_path + 'hciconfig', [hcidev, 'up']);
hciconfig.on("exit", function(code) {
if (code !== 0) {
// Could not get the device UP, maybe due to permissions, should run with sudo.
self.emit('error','hciconfig: failed to bring up device ' + hcidev +'. Try running with sudo.');
return;
} else {
console.log("hciconfig: succesfully brought up device " + hcidev);
// Kill any previous hcitool command
var clearHciTool = spawn("killall", ["hcitool"]);
clearHciTool.on("exit", function(code) {
console.log("hcitool: killed (code " + code + ")");
// Need to run this so scan returns actual results on Raspberry Pi devices
var hciToolDev = spawn(tool_path + 'hcitool', ['dev']);
hciToolDev.on("exit", function(code) {
if (code === 1) {
self.emit('error', 'hcitool dev: exited, already running? (code 1)');
return;
} else {
console.log("hcitool dev: done (code " + code + ")");
// Start scan
var hciToolScan = spawn(tool_path + 'hcitool', ['scan']);
console.log("hcitool scan: started...");
hciToolScan.stdout.on('data', function(data) {
if ( data.length ) {
data = data.toString('ascii');
var result;
var re = /((?:[0-9A-F]{2}(?::|)){6})[\t\s]+([^\n\r]+)/gmi;
while( (result = re.exec(data)) ) {
self.emit('device', result[1], result[2]);
}
}
});
hciToolScan.on("exit", function(code) {
self.emit('done',"hcitool scan: exited (code " + code + ")");
});
}
});
});
}
});
};
self.init(hcidev);
};
util.inherits(BluetoothScanner, EventEmitter);