diff --git a/lib/roles/device.js b/lib/roles/device.js index 0da81f0c..bf14666c 100644 --- a/lib/roles/device.js +++ b/lib/roles/device.js @@ -90,33 +90,23 @@ module.exports = function(options) { ]) }) .then(function() { - var port = 2870 - return adb.openTcpAsync(options.serial, port) - .then(function(conn) { - conn.end() - throw new Error(util.format('Old connection still lives on port %d', port)) - }) - .catch(function(err) { - if (err.message === 'closed') { - return adb.shellAsync(options.serial, [ - vendor.bin.dest - , '--lib', vendor.lib.dest - , '--listen-http', port - ]) - .then(function(out) { - out.pipe(require('split')()) - .on('data', function(chunk) { - log.info('remote: "%s"', chunk) - }) - .on('end', function() { - log.fatal('remote: Connection closed') - selfDestruct() - }) - }) - } - else { - throw err - } + return devutil.ensureUnusedPort(adb, options.serial, 2870) + .then(function(port) { + return adb.shellAsync(options.serial, [ + vendor.bin.dest + , '--lib', vendor.lib.dest + , '--listen-http', port + ]) + .then(function(out) { + out.pipe(require('split')()) + .on('data', function(chunk) { + log.info('remote: "%s"', chunk) + }) + .on('end', function() { + log.fatal('remote: Connection closed') + selfDestruct() + }) + }) }) }) .done(function() { diff --git a/lib/util/devutil.js b/lib/util/devutil.js index 8eaa221d..736452bb 100644 --- a/lib/util/devutil.js +++ b/lib/util/devutil.js @@ -26,6 +26,20 @@ devutil.vendorFiles = function(identity) { } } +devutil.ensureUnusedPort = function(adb, serial, port) { + function closedError(err) { + return err.message === 'closed' + } + return adb.openTcpAsync(serial, port) + .then(function(conn) { + conn.end() + throw new Error(util.format('Port "%d" should be unused', port)) + }) + .catch(closedError, function(err) { + return Promise.resolve(port) + }) +} + devutil.killProcsByComm = function(adb, serial, comm, bin) { return adb.shellAsync(serial, ['ps', comm]) .then(function(out) {