-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
95 lines (69 loc) · 2.21 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
function makePlugin(opts) {
let bluetoothManager = opts.bluetoothManager;
let ownMacAddress = null;
const name = "bluetooth"
function scope() {
return opts.scope || 'public';
}
function parse (addr) {
if (!addr.startsWith("bt:")) return null;
return addr.replace("bt:", "");
}
/**
* The multiserver address format does not allow : symbols to be used, so we omit them internally.
* This function adds them back in.
*
* @param {} internalRepresentation the internal representation (e.g. 65D900DDB353)
* @returns the bluetooth mac address implementation (e.g. 65:D9:00:DD:B3:53)
*/
function toMacAddress(internalRepresentation) {
const parts = [];
// Take a copy of the string
let btInternalRepresentation = internalRepresentation.slice();
do {
parts.push(btInternalRepresentation.substring(0, 2))
}
while( (btInternalRepresentation = btInternalRepresentation.substring(2, btInternalRepresentation.length)) != "" );
return parts.join(":");
}
function toInternalAddress(macAddress) {
return macAddress.split(":").join("");
}
function client (address, cb) {
const macAddress = toMacAddress(address);
bluetoothManager.connect(macAddress, cb);
return function() {
bluetoothManager.disconnect(address);
}
}
function server (onConnection, startedCb) {
bluetoothManager.getOwnMacAddress((err, address) => {
ownMacAddress = address;
// The bluetooth manager calls back with a duplex stream on a new connection
// which we can then call back onConnection with
bluetoothManager.listenForIncomingConnections(
(err, connection) => onConnection(connection)
)
if (startedCb) {
// Call back to let multiserver know that we're ready to accept incoming connections
startedCb(err, address);
}
})
return function() {
bluetoothManager.stopServer();
}
}
function stringify (s) {
if (s !== scope()) return;
return ['bt', toInternalAddress(ownMacAddress)].join(':')
}
return {
name: name,
scope: scope,
parse: parse,
client: client,
server: server,
stringify: stringify
}
}
module.exports = makePlugin;