forked from flier/adb.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadb.js
564 lines (430 loc) · 15.4 KB
/
adb.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
553
554
555
556
557
558
559
560
561
562
563
564
var console = require('console');
var net = require('net');
var events = require('events');
var util = require('util');
var DebugBridge = exports.DebugBridge = function () {
if (!DebugBridge.initialized) {
DebugBridge.initialize();
DebugBridge.initialized = true;
}
this.autoStartDaemon = true;
};
util.inherits(DebugBridge, events.EventEmitter);
var DebugSession = function (adb, sock) {
this.adb = adb;
this.sock = sock;
};
util.inherits(DebugSession, events.EventEmitter);
DebugBridge.DEFAULT_PORT = 5037;
DebugBridge.initialized = false;
DebugBridge.initialize = function () {
process.on('uncaughtException', function (err) {
console.error('Caught exception: ' + err);
console.error(err.stack);
});
process.on('SIGINT', function () {
console.log('Got SIGINT, exiting...');
process.exit(0);
});
process.on('exit', function () {
console.log('About to exit.');
});
};
DebugBridge.start_server = function (callback /* (code: number) */) {
var spawn = require('child_process').spawn;
var adb = spawn('./' + require('os').platform() + '/adb', ['start-server']);
adb.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
adb.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
adb.on('exit', function (code) {
callback(code);
});
adb.stdin.end();
};
DebugBridge.kill_server = function () {
};
DebugBridge.prototype.connect = function (callback /* (session: DebugSession) */) {
var adb = this;
var sock = net.connect({ port: DebugBridge.DEFAULT_PORT }, function () {
console.log('client connected to %s:%d', sock.remoteAddress, sock.remotePort);
sock.session = new DebugSession(adb, sock);
adb.emit('connected', sock.session);
callback(sock.session);
});
sock.setKeepAlive(true);
sock.setNoDelay(true);
sock.on('end', function () {
console.log('client disconnected');
sock.session.emit('disconnected');
sock.end();
});
sock.on('timeout', function () {
console.log('client timeout');
});
sock.on('error', function (err) {
if ('ECONNREFUSED' == err.errno) {
console.log('client connect refused, restarting adb daemon...');
if (adb.autoStartDaemon) {
DebugBridge.start_server(function (code) {
console.log('start adb daemon: %d', code);
if (code == 0) {
adb.connect(callback);
}
});
return;
}
} else {
console.error('client caught exception: ' + err);
}
throw err;
});
};
function encodeNumber(len) {
var buf = '';
for (var i=3; i>=0; i--) {
buf += '0123456789ABCDEF'.charAt((len >> 4*i) & 0xF);
}
return buf;
}
function decodeNumber(str) {
var num = 0;
for (var i=0; i<str.length; i++) {
num = num * 16 + '0123456789ABCDEF'.indexOf(String.fromCharCode(str[i]).toUpperCase());
}
return num;
}
DebugSession.prototype.sendData = function (data) {
var buf = encodeNumber(data.length) + data;
console.log('send %d bytes: %s', buf.length, buf);
this.sock.write(buf);
};
DebugSession.prototype.parseCmdResult = function (data, callback /* (data: buffer) */) {
var code = data.slice(0, 4).toString();
if (code == 'OKAY') {
console.log('exec command succeeded');
this.parseData(data.slice(4), callback);
} else if (code == 'FAIL') {
console.log('exec command failed');
this.parseData(data.slice(4), function (msg) {
throw new Error(msg);
});
} else {
throw new Error('Unknown result code - ' + code);
}
return code;
}
DebugSession.prototype.parseData = function (data, callback /* (data: buffer) */) {
var session = this;
if (data.length == 0) {
callback(null);
return;
}
var len = decodeNumber(data.slice(0, 4));
console.log('found %d bytes data: %s', len, data.slice(4, 4+len));
if (data.length < len+4) {
// TODO wait for the remaining data
} else {
callback(data.slice(4, 4+len));
if (data.length > 4+len) {
session.parseData(data.slice(4+len), callback);
}
}
};
DebugSession.prototype.waitCmdResult = function (callback /* (data: buffer) */) {
var session = this;
this.sock.once('data', function (data) {
console.log('recv %d bytes data: %s', data.length, data);
session.parseCmdResult(data, callback);
});
};
DebugSession.prototype.recvData = function (callback /* (data: buffer) */) {
this.sock.on('data', callback);
};
DebugBridge.prototype.execCommand = function (cmd, callback /* (data: buffer) */, repeat) {
this.connect(function (session) {
session.waitCmdResult(callback, repeat);
session.sendData(cmd);
});
};
DebugBridge.TRANSPORT_USB = 'host:transport-usb';
DebugBridge.TRANSPORT_LOCAL = 'host:transport-local';
DebugBridge.TRANSPORT_ANY = 'host:transport-any';
DebugBridge.prototype.prepareTransport = function (sn_or_type, callback) {
this.connect(function (session) {
session.waitCmdResult(function (data) {
callback(session);
});
var cmd;
if (sn_or_type.indexOf('host:transport-') == 0) {
cmd = sn_or_type;
} else {
cmd = 'host:transport:' + sn_or_type;
}
session.sendData(cmd);
});
};
DebugBridge.prototype.getVersion = function (callback /* (version: number) */) {
this.execCommand('host:version', function (data) {
callback(decodeNumber(data));
});
};
function parseDevices(adb, data) {
var lines = data.toString().split('\n');
var devices = [];
for (var i=0; i<lines.length; i++) {
var o = lines[i].split('\t');
if (o.length == 2) {
devices.push(new AndroidDevice(adb, o[0], o[1]));
}
}
return devices;
}
DebugBridge.prototype.listDevices = function (callback /* (devices: AndroidDevice[]) */) {
var adb = this;
this.execCommand('host:devices', function (data) {
callback(parseDevices(adb, data));
});
};
DebugBridge.prototype.traceDevice = function (callback /* (devices: AndroidDevice[]) */) {
var adb = this;
this.execCommand('host:track-devices', function (data) {
callback(parseDevices(adb, data));
}, true);
};
var AndroidDevice = function (adb, id, type) {
this.adb = adb;
this.id = id;
this.type = type;
};
AndroidDevice.prototype.toString = function () {
return util.format('<%s %s>', this.type, this.id);
};
Object.defineProperty(AndroidDevice.prototype, 'isEmulator', {
get: function () {
return this.id.indexOf("emulator-") == 0;
}
});
AndroidDevice.prototype.takeSnapshot = function (callback /* (frame: Framebuffer) */) {
this.adb.prepareTransport(this.id, function (session) {
session.waitCmdResult(function (data) {
session.recvData(function (data) {
if (!session.frame) {
session.frame = new AndroidFrame();
}
session.frame.parseData(data);
if (session.frame.isFinished) {
var frame = session.frame;
session.frame = null;
callback(frame);
}
}, true);
});
session.sendData('framebuffer:');
});
};
AndroidDevice.prototype.getSyncService = function (callback /* (svc: SyncService) */) {
this.adb.prepareTransport(this.id, function (session) {
session.waitCmdResult(function (data) {
callback(new SyncService(session));
});
session.sendData('sync:');
});
};
var AndroidFrame = function () {
};
AndroidFrame.prototype.toString = function () {
return util.format('<frame %dx%d@%d with %d bytes>', this.width, this.height, this.depth, this.size);
};
Object.defineProperty(AndroidFrame.prototype, 'isFinished', {
get: function () {
return this.pixels && (this.size == this.pixels.length);
}
});
function getMask(length) {
return (1 << length) - 1;
}
AndroidFrame.prototype.convertRGB565toARGB = function (pixels) {
var buf = new Buffer(this.width * this.height * 4);
for (var x=0; x<this.width; x++) {
for (var y=0; y<this.height; y++) {
var idx = (y * this.width + x) * 2;
var value = (pixels[idx] & 0xFF) | ((pixels[idx+1] << 8) & 0xFF00);
var r = ((value >>> this.red_offset) & getMask(this.red_length)) << (8 - this.red_length);
var g = ((value >>> this.green_offset) & getMask(this.green_length)) << (8 - this.green_length);
var b = ((value >>> this.blue_offset) & getMask(this.blue_length)) << (8 - this.blue_length);
idx = (y * this.width + x) * 4;
buf[idx++] = b;
buf[idx++] = g;
buf[idx++] = r;
buf[idx] = a;
}
}
return buf;
};
AndroidFrame.prototype.parseFrameHeader = function (data) {
var version = this.pixels.readUInt32LE(0);
if (version == 1) {
this.depth = this.pixels.readUInt32LE(4);
this.size = this.pixels.readUInt32LE(8);
this.width = this.pixels.readUInt32LE(12);
this.height = this.pixels.readUInt32LE(16);
// create default values for the rest. Format is 565
this.red_offset = this.pixels.readUInt32LE(20);
this.red_length = this.pixels.readUInt32LE(24);
this.green_offset = this.pixels.readUInt32LE(28);
this.green_length = this.pixels.readUInt32LE(32);
this.blue_offset = this.pixels.readUInt32LE(36);
this.blue_length = this.pixels.readUInt32LE(40);
this.alpha_offset = this.pixels.readUInt32LE(44);
this.alpha_length = this.pixels.readUInt32LE(48);
this.pixels = this.pixels.slice(13*4);
} else if (version == 16) {
this.depth = 16;
this.size = this.pixels.readUInt32LE(4);
this.width = this.pixels.readUInt32LE(8);
this.height = this.pixels.readUInt32LE(12);
// create default values for the rest. Format is 565
this.red_offset = 11;
this.red_length = 5;
this.green_offset = 5;
this.green_length = 6;
this.blue_offset = 0;
this.blue_length = 5;
this.alpha_offset = 0;
this.alpha_length = 0;
this.pixels = this.pixels.slice(16);
}
console.log('found a %dx%d@%d frame with %d bytes', this.width, this.height, this.depth, this.size);
};
AndroidFrame.prototype.parseData = function (data) {
if (this.pixels) {
// console.log("append %d bytes: %s", data.length, data.inspect());
this.pixels = Buffer.concat([this.pixels, data], this.pixels.length + data.length);
if (this.pixels.length == this.size && this.depth == 16) {
this.pixels = this.convertRGB565toARGB(this.pixels);
this.size = this.pixels.length;
}
} else {
this.pixels = data;
}
if (!this.size && this.pixels.length >= 16) {
this.parseFrameHeader(data);
}
};
AndroidFrame.prototype.writeImageFile = function (filename) {
console.log("generating %dx%d image from %d bytes buffer ...", this.width, this.height, this.pixels.length);
var ext = require('path').extname(filename);
var Image;
if (ext == '.png') {
Image = require('png').Png;
} else if (ext == '.jpg') {
Image = require('jpeg').Jpeg;
} else if (ext == '.gif') {
Image = require('gif').Gif;
} else {
throw new Error("unknown image type - " + ext);
}
img = new Image(this.pixels, this.width, this.height, 'rgba');
img.encode(function (image, err) {
console.log("writing %d bytes Image file ...", image.length);
if (err) { throw new Error(err); }
require('fs').writeFile(filename, image.toString('binary'), 'binary', function (err) {
if (err) {
console.error(err);
} else {
var spawn = require('child_process').spawn;
spawn('open', [filename]);
}
});
});
};
var SyncService = function (session) {
this.session = session;
};
util.inherits(SyncService, events.EventEmitter);
SyncService.REMOTE_PATH_MAX_LENGTH = 1024;
SyncService.ID_OKAY = 'OKAY';
SyncService.ID_FAIL = 'FAIL';
SyncService.ID_STAT = 'STAT';
SyncService.ID_RECV = 'RECV';
SyncService.ID_DATA = 'DATA';
SyncService.ID_DONE = 'DONE';
SyncService.ID_SEND = 'SEND';
SyncService.ID_LIST = 'LIST';
SyncService.ID_DENT = 'DENT';
SyncService.ID_ULNK = 'ULNK';
SyncService.ID_QUIT = 'QUIT';
SyncService.prototype.createFileReq = function (cmd, path) {
var buf = new Buffer(8 + path.length);
buf.write(cmd, 0, 4, 'binary');
buf.writeUInt32LE(path.length, 4);
buf.write(path, 8, path.length, 'binary');
return buf;
};
SyncService.prototype.sendFileReq = function (cmd, path) {
var req = this.createFileReq(cmd, path);
console.log("send file %s request %s", cmd, req.inspect());
this.session.sock.write(req);
};
var StreamWriter = function (filename) {
this.stream = require('fs').createWriteStream(filename, { encoding: 'binary'});
this.ts = new Date().getTime();
this.totalSize = 0;
this.chunkSize = 0;
this.closed = false;
};
StreamWriter.prototype.close = function () {
this.stream.end();
this.closed = true;
};
StreamWriter.prototype.parseData = function (data) {
if (this.chunkSize > 0) {
var buf = data.length > this.chunkSize ? data.slice(0, this.chunkSize) : data;
var remaining = data.length > this.chunkSize ? data.slice(this.chunkSize) : null;
this.stream.write(buf);
this.totalSize += buf.length;
this.chunkSize -= buf.length;
if (remaining) this.parseData(remaining);
} else {
var id = data.slice(0, 4).toString();
var size = data.readUInt32LE(4);
//console.log("found id <%s> with %d bytes", id, size);
if (id == SyncService.ID_DATA) {
this.chunkSize = size;
this.parseData(data.slice(8));
} else if (id == SyncService.ID_DONE) {
console.log("receiving %d bytes file in %d KB/s", this.totalSize, this.recvSpeed);
this.close();
} else if (id == SyncService.ID_FAIL) {
var msg = data.slice(8, size).toString();
throw new Error('Adb Transfer Protocol Error, ' + msg);
} else {
throw new Error('Adb Transfer Protocol Error, unknown id - ' + id);
}
}
};
Object.defineProperty(StreamWriter.prototype, 'recvTimes', {
get: function () {
return new Date().getTime() - this.ts;
}
});
Object.defineProperty(StreamWriter.prototype, 'recvSpeed', {
get: function () {
return Math.round(new Number(this.totalSize) * 1000 / this.recvTimes / 1024 * 100) / 100;
}
});
SyncService.prototype.pullFile = function (remotePath, localPath, callback /* (size) */) {
if (remotePath.length > SyncService.REMOTE_PATH_MAX_LENGTH) {
throw new Error('Remote path is too long.');
}
var writer = new StreamWriter(localPath);
this.session.sock.on('data', function (data) {
//console.log("recv %d bytes %s", data.length, data.inspect());
writer.parseData(data);
if (writer.closed) callback(writer.totalSize);
});
this.sendFileReq(SyncService.ID_RECV, remotePath);
};