This repository has been archived by the owner on Jun 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 117
/
BleTransport.js
422 lines (369 loc) · 11.2 KB
/
BleTransport.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// @flow
/* eslint-disable prefer-template */
import Transport, { TransportError } from "@ledgerhq/hw-transport";
import {
BleManager,
ConnectionPriority,
BleErrorCode,
} from "react-native-ble-plx";
import Config from "react-native-config";
import { Observable, defer, merge, from } from "rxjs";
import {
share,
ignoreElements,
first,
map,
tap,
timeout,
} from "rxjs/operators";
import { CantOpenDevice } from "@ledgerhq/live-common/lib/errors";
import { logSubject } from "./debug";
import type { Device, Characteristic } from "./types";
import { sendAPDU } from "./sendAPDU";
import { receiveAPDU } from "./receiveAPDU";
import { monitorCharacteristic } from "./monitorCharacteristic";
import { awaitsBleOn } from "./awaitsBleOn";
const ServiceUuid = "d973f2e0-b19e-11e2-9e96-0800200c9a66";
const WriteCharacteristicUuid = "d973f2e2-b19e-11e2-9e96-0800200c9a66";
const NotifyCharacteristicUuid = "d973f2e1-b19e-11e2-9e96-0800200c9a66";
let connectOptions = {
requestMTU: 156,
};
const transportsCache = {};
const bleManager = new BleManager();
if (Config.BLE_LOG_LEVEL) bleManager.setLogLevel(Config.BLE_LOG_LEVEL);
/**
* react-native bluetooth BLE implementation
* @example
* import BluetoothTransport from "@ledgerhq/react-native-hw-transport-ble";
*/
export default class BluetoothTransport extends Transport<Device | string> {
static isSupported = (): Promise<boolean> =>
Promise.resolve(typeof BleManager === "function");
/**
* TODO could add this concept in all transports
* observe event with { available: bool, type: string } // available is generic, type is specific
* an event is emit once and then listened
*/
static observeState(observer: *) {
const emitFromState = type => {
observer.next({ type, available: type === "PoweredOn" });
};
bleManager.onStateChange(emitFromState, true);
return {
unsubscribe: () => {},
};
}
static list = (): * => {
throw new Error("not implemented");
};
static listen(observer: *) {
logSubject.next({
type: "verbose",
message: `listen...`,
});
let unsubscribed;
const stateSub = bleManager.onStateChange(async state => {
if (state === "PoweredOn") {
stateSub.remove();
const devices = await bleManager.connectedDevices([ServiceUuid]);
if (unsubscribed) return;
await Promise.all(
devices.map(d => BluetoothTransport.disconnect(d.id).catch(() => {})),
);
if (unsubscribed) return;
bleManager.startDeviceScan([ServiceUuid], null, (bleError, device) => {
if (bleError) {
observer.error(bleError);
unsubscribe();
return;
}
observer.next({ type: "add", descriptor: device });
});
}
}, true);
const unsubscribe = () => {
unsubscribed = true;
bleManager.stopDeviceScan();
stateSub.remove();
logSubject.next({
type: "verbose",
message: `done listening.`,
});
};
return { unsubscribe };
}
static async open(deviceOrId: Device | string, _timeout: number = 30000) {
// TODO implement timeout
let device;
if (typeof deviceOrId === "string") {
if (transportsCache[deviceOrId]) {
logSubject.next({
type: "verbose",
message: "Transport in cache, using that.",
});
return transportsCache[deviceOrId];
}
logSubject.next({ type: "verbose", message: `open(${deviceOrId})` });
await awaitsBleOn(bleManager);
if (!device) {
// works for iOS but not Android
const devices = await bleManager.devices([deviceOrId]);
logSubject.next({
type: "verbose",
message: `found ${devices.length} devices`,
});
[device] = devices;
}
if (!device) {
const connectedDevices = await bleManager.connectedDevices([
ServiceUuid,
]);
const connectedDevicesFiltered = connectedDevices.filter(
d => d.id === deviceOrId,
);
logSubject.next({
type: "verbose",
message: `found ${connectedDevicesFiltered.length} connected devices`,
});
[device] = connectedDevicesFiltered;
}
if (!device) {
logSubject.next({
type: "verbose",
message: `connectToDevice(${deviceOrId})`,
});
try {
device = await bleManager.connectToDevice(deviceOrId, connectOptions);
} catch (e) {
if (e.errorCode === BleErrorCode.DeviceMTUChangeFailed) {
connectOptions = {};
device = await bleManager.connectToDevice(deviceOrId);
} else {
throw e;
}
}
}
if (!device) {
throw new CantOpenDevice();
}
} else {
device = deviceOrId;
}
if (!(await device.isConnected())) {
logSubject.next({
type: "verbose",
message: "not connected. connecting...",
});
try {
await device.connect(connectOptions);
} catch (e) {
if (e.errorCode === BleErrorCode.DeviceMTUChangeFailed) {
connectOptions = {};
await device.connect();
} else {
throw e;
}
}
}
await device.discoverAllServicesAndCharacteristics();
const characteristics = await device.characteristicsForService(ServiceUuid);
if (!characteristics) {
throw new TransportError("service not found", "BLEServiceNotFound");
}
let writeC;
let notifyC;
for (const c of characteristics) {
if (c.uuid === WriteCharacteristicUuid) {
writeC = c;
} else if (c.uuid === NotifyCharacteristicUuid) {
notifyC = c;
}
}
if (!writeC) {
throw new TransportError(
"write characteristic not found",
"BLEChracteristicNotFound",
);
}
if (!notifyC) {
throw new TransportError(
"notify characteristic not found",
"BLEChracteristicNotFound",
);
}
if (!writeC.isWritableWithResponse) {
throw new TransportError(
"write characteristic not writableWithResponse",
"BLEChracteristicInvalid",
);
}
if (!notifyC.isNotifiable) {
throw new TransportError(
"notify characteristic not notifiable",
"BLEChracteristicInvalid",
);
}
logSubject.next({ type: "verbose", message: `device.mtu=${device.mtu}` });
const notifyObservable = monitorCharacteristic(notifyC).pipe(
tap(value => {
logSubject.next({
type: "ble-frame-read",
message: value.toString("hex"),
});
}),
share(),
);
const notif = notifyObservable.subscribe();
const transport = new BluetoothTransport(device, writeC, notifyObservable);
transportsCache[transport.id] = transport;
const disconnectedSub = device.onDisconnected(e => {
transport.notYetDisconnected = false;
notif.unsubscribe();
disconnectedSub.remove();
delete transportsCache[transport.id];
logSubject.next({
type: "verbose",
message: `BleTransport(${transport.id}) disconnected`,
});
transport.emit("disconnect", e);
});
await transport.inferMTU();
return transport;
}
static disconnect = async (id: *) => {
logSubject.next({
type: "verbose",
message: `user disconnect(${id})`,
});
await bleManager.cancelDeviceConnection(id);
};
id: string;
device: Device;
mtuSize: number = 20;
writeCharacteristic: Characteristic;
notifyObservable: Observable<Buffer>;
notYetDisconnected = true;
constructor(
device: Device,
writeCharacteristic: Characteristic,
notifyObservable: Observable<Buffer>,
) {
super();
this.id = device.id;
this.device = device;
this.writeCharacteristic = writeCharacteristic;
this.notifyObservable = notifyObservable;
logSubject.next({
type: "verbose",
message: `BleTransport(${String(this.id)}) new instance`,
});
}
exchange = (apdu: Buffer): Promise<Buffer> =>
this.atomic(async () => {
try {
const { debug } = this;
const msgIn = apdu.toString("hex");
if (debug) debug(`=> ${msgIn}`); // eslint-disable-line no-console
logSubject.next({ type: "ble-apdu-write", message: msgIn });
const data = await merge(
this.notifyObservable.pipe(receiveAPDU),
sendAPDU(bleManager, this.write, apdu, this.mtuSize),
).toPromise();
const msgOut = data.toString("hex");
logSubject.next({ type: "ble-apdu-read", message: msgOut });
if (debug) debug(`<= ${msgOut}`); // eslint-disable-line no-console
return data;
} catch (e) {
logSubject.next({
type: "ble-error",
message: "exchange got " + String(e),
});
if (this.notYetDisconnected) {
// in such case we will always disconnect because something is bad.
await bleManager.cancelDeviceConnection(this.id).catch(() => {}); // but we ignore if disconnect worked.
}
throw e;
}
});
// TODO we probably will do this at end of open
async inferMTU() {
let { mtu } = this.device;
if (mtu <= 23) {
await this.atomic(async () => {
try {
mtu =
(await merge(
this.notifyObservable.pipe(
first(buffer => buffer.readUInt8(0) === 0x08),
map(buffer => buffer.readUInt8(5)),
timeout(30000),
),
defer(() =>
from(this.write(Buffer.from([0x08, 0, 0, 0, 0]))),
).pipe(ignoreElements()),
).toPromise()) + 3;
} catch (e) {
logSubject.next({
type: "ble-error",
message: "inferMTU got " + String(e),
});
await bleManager.cancelDeviceConnection(this.id).catch(() => {}); // but we ignore if disconnect worked.
throw e;
}
});
}
if (mtu > 23) {
const mtuSize = mtu - 3;
logSubject.next({
type: "verbose",
message: `BleTransport(${String(this.id)}) mtu set to ${String(
mtuSize,
)}`,
});
this.mtuSize = mtuSize;
}
return this.mtuSize;
}
async requestConnectionPriority(
connectionPriority: "Balanced" | "High" | "LowPower",
) {
await this.device.requestConnectionPriority(
ConnectionPriority[connectionPriority],
);
}
setScrambleKey() {}
write = async (buffer: Buffer, txid?: ?string) => {
logSubject.next({
type: "ble-frame-write",
message: buffer.toString("hex"),
});
await this.writeCharacteristic.writeWithResponse(
buffer.toString("base64"),
txid,
);
};
busy: ?Promise<void>;
atomic = async <R>(f: () => Promise<R>): Promise<R> => {
if (this.busy) {
throw new TransportError("BLE Transport race condition", "RaceCondition");
}
let resolveBusy;
const busyPromise = new Promise(r => {
resolveBusy = r;
});
this.busy = busyPromise;
try {
const res = await f();
return res;
} finally {
if (resolveBusy) resolveBusy();
this.busy = null;
}
};
async close() {
if (this.busy) {
await this.busy;
}
}
}