-
Notifications
You must be signed in to change notification settings - Fork 2
/
adafruit-ble-file-transfer.js
552 lines (505 loc) · 19 KB
/
adafruit-ble-file-transfer.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
const bleFileCharVersionUUID = 'adaf0100-4669-6c65-5472-616e73666572';
const bleFileCharTransferUUID = 'adaf0200-4669-6c65-5472-616e73666572';
const ANY_COMMAND = 0;
const THIS_COMMAND = 1;
const READ_COMMAND = 0x10;
const READ_DATA = 0x11;
const READ_PACING = 0x12;
const WRITE_COMMAND = 0x20;
const WRITE_PACING = 0x21;
const WRITE_DATA = 0x22;
const DELETE_COMMAND = 0x30;
const DELETE_STATUS = 0x31;
const MKDIR_COMMAND = 0x40;
const MKDIR_STATUS = 0x41;
const LISTDIR_COMMAND = 0x50;
const LISTDIR_ENTRY = 0x51;
const MOVE_COMMAND = 0x60;
const MOVE_STATUS = 0x61;
const STATUS_OK = 0x01;
const STATUS_ERROR = 0x02;
const STATUS_ERROR_USB_MOUNTED = 0x05;
// Flags
const FLAG_DIRECTORY = 0x01;
// 500 works on mac
const BYTES_PER_WRITE = 20;
class FileTransferClient {
constructor(bleDevice, bufferSize = 4096) {
this._resolve = null;
this._reject = null;
this._command = ANY_COMMAND;
this._offset = 0;
// We have a ton of memory so just buffer everything :-)
this._buffer = new Uint8Array(bufferSize);
this._transfer = null;
this._device = bleDevice;
this._raw = false;
bleDevice.addEventListener("gattserverdisconnected", this.onDisconnected.bind(this));
this._onTransferNotifty = this.onTransferNotifty.bind(this);
}
async onDisconnected() {
//ftc disconnected;
this._transfer = null;
if (this._reject != null) {
this._reject("disconnected");
this._reject = null;
this._resolve = null;
}
this._command = ANY_COMMAND;
this._offset = 0;
}
async checkConnection() {
if (this._reject != null) {
throw "Command in progress";
}
if (this._transfer != null) {
//connection ok
return;
}
try {
//check connection
let service = await this._device.gatt.getPrimaryService(0xfebb);
const versionChar = await service.getCharacteristic(bleFileCharVersionUUID);
let version = (await versionChar.readValue()).getUint32(0, true);
if (version != 4) {
return Promise.reject("Unsupported version: " + version);
}
//version ok
this._transfer = await service.getCharacteristic(bleFileCharTransferUUID);
this._transfer.removeEventListener('characteristicvaluechanged', this._onTransferNotifty);
this._transfer.addEventListener('characteristicvaluechanged', this._onTransferNotifty);
await this._transfer.startNotifications();
} catch (e) {
console.log("caught connection error", e, e.stack);
this.onDisconnected();
}
}
async _write(value) {
try {
if (value.byteLength < BYTES_PER_WRITE) {
await this._transfer.writeValueWithoutResponse(value);
return;
}
var offset = 0;
while (offset < value.byteLength) {
let len = Math.min(value.byteLength - offset, BYTES_PER_WRITE);
let chunk_contents = value.slice(offset, offset + len);
// Delay to ensure the last value was written to the device.
await this.sleep(100);
await this._transfer.writeValueWithoutResponse(chunk_contents);
offset += len;
}
} catch (e) {
console.log("caught write error", e, e.stack);
this.onDisconnected();
}
}
async bond() {
await this.checkConnection();
//bonded internally
}
async onTransferNotifty(event) {
this._buffer.set(new Uint8Array(event.target.value.buffer), this._offset);
this._command = this._buffer[0];
this._offset += event.target.value.byteLength;
if (this._command == READ_DATA) {
this._command = await this.processReadData(new DataView(this._buffer.buffer, 0, this._offset));
} else if (this._command == WRITE_PACING) {
this._command = await this.processWritePacing(new DataView(this._buffer.buffer, 0, this._offset));
} else if (this._command == LISTDIR_ENTRY) {
this._command = await this.processListDirEntry(new DataView(this._buffer.buffer, 0, this._offset));
} else if (this._command == MKDIR_STATUS) {
this._command = await this.processMkDirStatus(new DataView(this._buffer.buffer, 0, this._offset));
} else if (this._command == DELETE_STATUS) {
this._command = await this.processDeleteStatus(new DataView(this._buffer.buffer, 0, this._offset));
} else if (this._command == MOVE_STATUS) {
this._command = await this.processMoveStatus(new DataView(this._buffer.buffer, 0, this._offset));
} else {
console.log("Unknown Command: " + this._command);
}
if (this._command != THIS_COMMAND) {
//reset buffer
this._offset = 0;
}
}
async readFile(filename, raw = false) {
await this.checkConnection();
this._incomingFile = null;
this._incomingOffset = 0;
this._raw = raw;
var header = new ArrayBuffer(12);
var view = new DataView(header);
let encoded = new TextEncoder().encode(filename);
view.setUint8(0, READ_COMMAND);
// Offset 1 is reserved
view.setUint16(2, encoded.byteLength, true);
view.setUint32(4, 0, true);
view.setUint32(8, this._buffer.byteLength - 16, true);
await this._write(header);
await this._write(encoded);
//wrote read
let p = new Promise((resolve, reject) => {
//start read
this._resolve = resolve;
this._reject = reject;
});
//read return
return p;
}
async writeFile(path, offset, contents, modificationTime, raw = false) {
let encoder = new TextEncoder();
if (!raw) {
let same = contents.slice(0, offset);
let different = contents.slice(offset);
offset = encoder.encode(same).byteLength;
contents = encoder.encode(different);
} else if (!(contents instanceof Uint8Array)) {
contents = new Uint8Array(contents);
}
await this.checkConnection();
if (modificationTime === undefined) {
modificationTime = Date.now();
}
var header = new ArrayBuffer(20);
var view = new DataView(header);
let encoded = new TextEncoder().encode(path);
view.setUint8(0, WRITE_COMMAND);
// Offset 1 is reserved
view.setUint16(2, encoded.byteLength, true);
view.setUint32(4, offset, true);
view.setBigUint64(8, BigInt(modificationTime * 1000000), true);
view.setUint32(16, offset + contents.byteLength, true);
await this._write(header);
await this._write(encoded);
this._outgoingContents = contents;
this._outgoingOffset = offset;
//wrote write
let p = new Promise((resolve, reject) => {
//start write
this._resolve = resolve;
this._reject = reject;
});
//write return
return p;
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async processWritePacing(payload) {
let status = payload.getUint8(1);
// Two bytes of padding.
let chunkOffset = payload.getUint32(4, true);
let freeSpace = payload.getUint32(16, true);
if (status != STATUS_OK) {
if (status == STATUS_ERROR_USB_MOUNTED) {
this._reject("Unable to write while USB connected");
} else if (status == STATUS_ERROR) {
this._reject("Invalid Path");
} else {
this._reject("Unknown Status: " + status);
}
this._reject = null;
this._resolve = null;
return ANY_COMMAND;
}
if (freeSpace == 0) {
this._resolve();
this._reject = null;
this._resolve = null;
return ANY_COMMAND;
}
var header = new ArrayBuffer(12);
var view = new DataView(header);
view.setUint8(0, WRITE_DATA);
view.setUint8(1, STATUS_OK);
// Offsets 2 and 3 are reserved
view.setUint32(4, chunkOffset, true);
let remaining = Math.min(this._outgoingOffset + this._outgoingContents.byteLength - chunkOffset, freeSpace);
view.setUint32(8, remaining, true);
await this._write(header);
let baseOffset = chunkOffset - this._outgoingOffset;
await this._write(this._outgoingContents.subarray(baseOffset, baseOffset + remaining));
return WRITE_PACING;
}
async processReadData(payload) {
const headerSize = 16;
let status = payload.getUint8(1);
let chunkOffset = payload.getUint32(4, true);
let totalLength = payload.getUint32(8, true);
let chunkLength = payload.getUint32(12, true);
if (status != STATUS_OK) {
if (status == STATUS_ERROR_USB_MOUNTED) {
this._reject("Unable to read while USB connected");
} else if (status == STATUS_ERROR) {
this._reject("Invalid Path");
} else {
this._reject("Unknown Status: " + status);
}
this._resolve = null;
this._reject = null;
this._incomingFile = null;
this._incomingOffset = 0;
return ANY_COMMAND;
}
if (payload.byteLength < headerSize + chunkLength) {
// need more
return THIS_COMMAND;
}
// full payload
if (this._incomingFile == null) {
this._incomingFile = new Uint8Array(totalLength);
}
this._incomingFile.set(new Uint8Array(payload.buffer.slice(headerSize, payload.byteLength)), chunkOffset);
this._incomingOffset += chunkLength;
let remaining = this._incomingFile.byteLength - this._incomingOffset;
if (remaining == 0) {
if (this._raw) {
this._resolve(new Blob([this._incomingFile]));
} else {
this._resolve(new TextDecoder().decode(this._incomingFile));
}
this._resolve = null;
this._reject = null;
this._incomingFile = null;
this._incomingOffset = 0;
return ANY_COMMAND;
}
var header = new ArrayBuffer(12);
var view = new DataView(header);
view.setUint8(0, READ_PACING);
view.setUint8(1, STATUS_OK);
// Offsets 2 and 3 are reserved
view.setUint32(4, this._incomingOffset, true);
view.setUint32(8, Math.min(this._buffer.byteLength - 12, remaining), true);
await this._write(header);
return READ_DATA;
}
async processListDirEntry(payload, offset = 0) {
let paths = [];
let b = this._buffer.buffer;
const headerSize = 28;
let cmd, path;
let flags, modificationTime, fileSize;
let status = payload.getUint8(1);
let pathLength = payload.getUint16(2, true);
let i = payload.getUint32(4, true);
let totalItems = payload.getUint32(8, true);
if (status != STATUS_OK) {
if (status == STATUS_ERROR_USB_MOUNTED) {
this._reject("Unable to read while USB connected");
} else if (status == STATUS_ERROR) {
this._reject("Invalid Path");
} else {
this._reject("Unknown Status: " + status);
}
this._resolve = null;
this._reject = null;
return ANY_COMMAND;
}
// Figure out if complete
offset = 0;
while (offset < payload.byteLength) {
if (offset + headerSize + pathLength > payload.byteLength) {
break;
}
pathLength = payload.getUint16(offset + 2, true);
i = payload.getUint32(offset + 4, true);
totalItems = payload.getUint32(offset + 8, true);
offset += headerSize + pathLength;
}
// Check if we have all items and all expected data for last item
if (i < totalItems - 1 || payload.byteLength < offset + headerSize) {
// need more
return THIS_COMMAND;
}
// full payload, now process it
offset = 0;
while (offset < payload.byteLength) {
cmd = payload.getUint8(offset + 0);
status = payload.getUint8(offset + 1);
pathLength = payload.getUint16(offset + 2, true);
i = payload.getUint32(offset + 4, true);
totalItems = payload.getUint32(offset + 8, true);
flags = payload.getUint32(offset + 12, true);
modificationTime = payload.getBigUint64(offset + 16, true);
fileSize = payload.getUint32(offset + 24, true);
if (cmd != LISTDIR_ENTRY) {
throw new ProtocolError();
}
if (i >= totalItems) {
break;
}
if (offset + headerSize + pathLength > payload.byteLength) {
break;
}
path = String.fromCharCode.apply(null, new Uint8Array(b.slice(offset + headerSize, offset + headerSize + pathLength)));
paths.push({
path: path,
isDir: !!(flags & FLAG_DIRECTORY),
fileSize: fileSize,
fileDate: Number(modificationTime / BigInt(1000000)),
});
offset += headerSize + pathLength;
if (status != STATUS_OK) {
break;
}
}
this._resolve(paths);
this._resolve = null;
this._reject = null;
return ANY_COMMAND;
}
async processMkDirStatus(payload) {
const headerSize = 16;
let status = payload.getUint8(1);
if (payload.byteLength < headerSize) {
return THIS_COMMAND;
}
if (status != STATUS_OK) {
if (status == STATUS_ERROR_USB_MOUNTED) {
this._reject("Unable to write while USB connected");
} else if (status == STATUS_ERROR) {
this._reject("Invalid Path");
} else {
this._reject("Unknown Status: " + status);
}
} else {
this._resolve(true);
}
this._resolve = null;
this._reject = null;
return ANY_COMMAND;
}
async processDeleteStatus(payload) {
const headerSize = 2;
if (payload.byteLength < headerSize) {
return THIS_COMMAND;
}
let status = payload.getUint8(1);
if (status != STATUS_OK) {
if (status == STATUS_ERROR_USB_MOUNTED) {
this._reject("Unable to write while USB connected");
} else if (status == STATUS_ERROR) {
this._reject("File or Folder not found");
} else {
this._reject("Unknown Status: " + status);
}
} else {
this._resolve(true);
}
this._resolve = null;
this._reject = null;
return ANY_COMMAND;
}
async processMoveStatus(payload) {
const headerSize = 2;
if (payload.byteLength < headerSize) {
return THIS_COMMAND;
}
let status = payload.getUint8(1);
if (status != STATUS_OK) {
if (status == STATUS_ERROR_USB_MOUNTED) {
this._reject("Unable to write while USB connected");
} else if (status == STATUS_ERROR) {
this._reject("Unable to move file");
} else {
this._reject("Unknown Status: " + status);
}
} else {
this._resolve(true);
}
this._resolve = null;
this._reject = null;
return ANY_COMMAND;
}
// Makes the directory and any missing parents
async makeDir(path, modificationTime) {
await this.checkConnection();
if (modificationTime === undefined) {
modificationTime = Date.now();
}
let encoded = new TextEncoder().encode(path);
var header = new ArrayBuffer(16);
var view = new DataView(header);
view.setUint8(0, MKDIR_COMMAND);
// Offset 1 is reserved
view.setUint16(2, encoded.byteLength, true);
// Offsets 4-7 Reserved
view.setBigUint64(8, BigInt(modificationTime * 1000000), true);
await this._write(header);
await this._write(encoded);
let p = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
return p;
}
// Returns a list of tuples, one tuple for each file or directory in the given path
async listDir(path) {
await this.checkConnection();
let encoded = new TextEncoder().encode(path);
var header = new ArrayBuffer(4);
var view = new DataView(header);
view.setUint8(0, LISTDIR_COMMAND);
// Offset 1 is reserved
view.setUint16(2, encoded.byteLength, true);
await this._write(header);
await this._write(encoded);
let p = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
return p;
}
// Deletes the file or directory at the given path. Directories must be empty.
async delete(path) {
await this.checkConnection();
let encoded = new TextEncoder().encode(path);
var header = new ArrayBuffer(4);
var view = new DataView(header);
view.setUint8(0, DELETE_COMMAND);
// Offset 1 is reserved
view.setUint16(2, encoded.byteLength, true);
await this._write(header);
await this._write(encoded);
let p = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
return p;
}
// Moves the file or directory from oldPath to newPath.
async move(oldPath, newPath) {
await this.checkConnection();
let encodedOldPath = new TextEncoder().encode(oldPath);
let encodedNewPath = new TextEncoder().encode(newPath);
var header = new ArrayBuffer(6);
var view = new DataView(header);
view.setUint8(0, MOVE_COMMAND);
// Offset 1 is reserved
view.setUint16(2, encodedOldPath.byteLength, true);
view.setUint16(4, encodedNewPath.byteLength, true);
await this._write(header);
await this._write(encodedOldPath);
await this._write(new TextEncoder().encode(" "));
await this._write(encodedNewPath);
let p = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
return p;
}
}
class ProtocolError extends Error {
constructor(message) {
super(message);
this.name = "ProtocolError";
}
}
class ValueError extends Error {
constructor(message) {
super(message);
this.name = "ValueError";
}
}
export {FileTransferClient, ProtocolError, ValueError};