forked from viviedu/noble-winrt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bindings.js
229 lines (203 loc) · 8.02 KB
/
bindings.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
// noble-winrt
// Copyright (C) 2017, Uri Shaked
// License: MIT
const { spawn } = require('child_process');
const nativeMessage = require('chrome-native-messaging');
const events = require('events');
const debug = require('debug')('noble-winrt');
const path = require('path');
const BLE_SERVER_EXE = path.resolve(__dirname, 'prebuilt', 'BLEServer.exe').replace('app.asar', 'app.asar.unpacked');
function toWindowsUuid(uuid) {
return '{' + uuid + '}';
}
function fromWindowsUuid(uuid) {
return uuid.replace(/\{|\}/g, '');
}
const adTypeServiceData16BitUUID = 0x16;
class WinrtBindings extends events.EventEmitter {
init() {
this._deviceMap = {};
this._requestId = 0;
this._requests = {};
this._subscriptions = {};
this._bleServer = spawn(BLE_SERVER_EXE, ['']);
this._bleServer.stdout
.pipe(new nativeMessage.Input())
.on('data', (data) => {
this._processMessage(data);
});
this._bleServer.stderr.on('data', (data) => {
console.error('BLEServer:', data);
});
this._bleServer.on('close', (code) => {
this.state = 'poweredOff';
this.emit('stateChange', this.state);
});
}
startScanning() {
this._sendMessage({ cmd: 'scan' });
}
stopScanning() {
this._sendMessage({ cmd: 'stopScan' });
}
connect(address) {
this._sendRequest({ cmd: 'connect', 'address': address })
.then(result => {
this._deviceMap[address] = result;
this.emit('connect', address, null);
})
.catch(err => this.emit('connect', address, err));
}
disconnect(address) {
this._sendRequest({ cmd: 'disconnect', device: this._deviceMap[address] })
.then(result => {
this._deviceMap[address] = null;
this.emit('disconnect', address, null);
})
.catch(err => this.emit('disconnect', address, err));
}
discoverServices(address, filters = []) {
this._sendRequest({ cmd: 'services', device: this._deviceMap[address] })
.then(result => {
// TODO filters
this.emit('servicesDiscover', address, result.map(fromWindowsUuid));
})
.catch(err => this.emit('servicesDiscover', address, err));
}
discoverCharacteristics(address, service, filters = []) {
this._sendRequest({
cmd: 'characteristics',
device: this._deviceMap[address],
service: toWindowsUuid(service),
})
.then(result => {
// TODO filters
this.emit('characteristicsDiscover', address, service,
result.map(c => ({
uuid: fromWindowsUuid(c.uuid),
properties: Object.keys(c.properties).filter(p => c.properties[p])
})));
})
.catch(err => this.emit('characteristicsDiscover', address, service, err));
}
read(address, service, characteristic) {
this._sendRequest({
cmd: 'read',
device: this._deviceMap[address],
service: toWindowsUuid(service),
characteristic: toWindowsUuid(characteristic)
})
.then(result => {
this.emit('read', address, service, characteristic, Buffer.from(result), false);
})
.catch(err => this.emit('read', address, service, characteristic, err, false));
}
write(address, service, characteristic, data, withoutResponse) {
// TODO data, withoutResponse
this._sendRequest({
cmd: 'write',
device: this._deviceMap[address],
service: toWindowsUuid(service),
characteristic: toWindowsUuid(characteristic),
value: Array.from(data),
})
.then(result => {
this.emit('write', address, service, characteristic);
})
.catch(err => this.emit('write', address, service, characteristic, err));
}
notify(address, service, characteristic, notify) {
this._sendRequest({
cmd: notify ? 'subscribe' : 'unsubscribe',
device: this._deviceMap[address],
service: toWindowsUuid(service),
characteristic: toWindowsUuid(characteristic)
})
.then(result => {
if (notify) {
this._subscriptions[result] = { address, service, characteristic };
} else {
// TODO - remove from subscriptions
}
this.emit('notify', address, service, characteristic, notify);
})
.catch(err => this.emit('notify', address, service, characteristic, err));
}
_processMessage(message) {
debug('in:', message);
switch (message._type) {
case 'Start':
this.state = 'poweredOn';
this.emit('stateChange', this.state);
break;
case 'scanResult':
let advertisement = {
localName: message.localName,
txPowerLevel: 0,
manufacturerData: null,
serviceUuids: message.serviceUuids.map(fromWindowsUuid),
serviceData: this._retrieveServiceData(message.adStructures),
};
this.emit(
'discover',
message.bluetoothAddress.replace(/:/g, ''),
message.bluetoothAddress,
'public', // TODO address type
true, // TODO connectable
advertisement,
message.rssi);
break;
case 'response':
if (this._requests[message._id]) {
if (message.error) {
this._requests[message._id].reject(new Error(message.error));
} else {
this._requests[message._id].resolve(message.result);
}
delete this._requests[message._id];
}
break;
case 'disconnectEvent':
for (let address of Object.keys(this._deviceMap)) {
if (this._deviceMap[address] == message.device) {
this.emit('disconnect', address);
}
}
break;
case 'valueChangedNotification':
const { address, service, characteristic } = this._subscriptions[message.subscriptionId];
this.emit('read', address, service, characteristic, Buffer.from(message.value), true);
break;
}
}
// This will only retrieve service data with 16 bit UUIDs. If you need
// anything else, parse the relevant adStructures
_retrieveServiceData(adStructures) {
return adStructures
.filter((adStructure) => adStructure.type === adTypeServiceData16BitUUID)
.map((adStructure) => ({
uuid: this._toHex(adStructure.data[1]) + this._toHex(adStructure.data[0]),
data: Buffer.from(adStructure.data.slice(2))
}));
}
_sendMessage(message) {
debug('out:', message);
const dataBuf = Buffer.from(JSON.stringify(message), 'utf-8');
const lenBuf = Buffer.alloc(4);
lenBuf.writeInt32LE(dataBuf.length, 0);
this._bleServer.stdin.write(lenBuf);
this._bleServer.stdin.write(dataBuf);
}
_sendRequest(message) {
return new Promise((resolve, reject) => {
const requestId = this._requestId++;
this._requests[requestId] = { resolve, reject };
this._sendMessage(Object.assign({}, message, { _id: requestId }));
});
}
// converts a number in range 0-255 to a two byte hex code like "C4"
_toHex(number) {
return number.toString(16).padStart(2, '0').toUpperCase();
}
}
exports.WinrtBindings = WinrtBindings;