openstf / adbkit

A pure Node.js client for the Android Debug Bridge.
Other
834 stars 251 forks source link

adbkit

Warning

This project along with other ones in OpenSTF organisation is provided as is for community, without active development.

You can check any other forks that may be actively developed and offer new/different features here.

Active development has been moved to DeviceFarmer organisation.

Interested in helping to convert the CoffeeScript codebase to plain JavaScript? Help us!

adbkit is a pure Node.js client for the Android Debug Bridge server. It can be used either as a library in your own application, or simply as a convenient utility for playing with your device.

Most of the adb command line tool's functionality is supported (including pushing/pulling files, installing APKs and processing logs), with some added functionality such as being able to generate touch/key events and take screenshots. Some shims are provided for older devices, but we have not and will not test anything below Android 2.3.

Internally, we use this library to drive a multitude of Android devices from a variety of manufacturers, so we can say with a fairly high degree of confidence that it will most likely work with your device(s), too.

Requirements

Please note that although it may happen at some point, this project is NOT an implementation of the ADB server. The target host (where the devices are connected) must still have ADB installed and either already running (e.g. via adb start-server) or available in $PATH. An attempt will be made to start the server locally via the aforementioned command if the initial connection fails. This is the only case where we fall back to the adb binary.

When targeting a remote host, starting the server is entirely your responsibility.

Alternatively, you may want to consider using the Chrome ADB extension, as it includes the ADB server and can be started/stopped quite easily.

Getting started

Install via NPM:

npm install --save adbkit

We use debug, and our debug namespace is adb. Some of the dependencies may provide debug output of their own. To see the debug output, set the DEBUG environment variable. For example, run your program with DEBUG=adb:* node app.js.

Note that even though the module is written in CoffeeScript, only the compiled JavaScript is published to NPM, which means that it can easily be used with pure JavaScript codebases, too.

Examples

The examples may be a bit verbose, but that's because we're trying to keep them as close to real-life code as possible, with flow control and error handling taken care of.

Checking for NFC support

var Promise = require('bluebird')
var adb = require('adbkit')
var client = adb.createClient()

client.listDevices()
  .then(function(devices) {
    return Promise.filter(devices, function(device) {
      return client.getFeatures(device.id)
        .then(function(features) {
          return features['android.hardware.nfc']
        })
    })
  })
  .then(function(supportedDevices) {
    console.log('The following devices support NFC:', supportedDevices)
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

Installing an APK

var Promise = require('bluebird')
var adb = require('adbkit')
var client = adb.createClient()
var apk = 'vendor/app.apk'

client.listDevices()
  .then(function(devices) {
    return Promise.map(devices, function(device) {
      return client.install(device.id, apk)
    })
  })
  .then(function() {
    console.log('Installed %s on all connected devices', apk)
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

Tracking devices

var adb = require('adbkit')
var client = adb.createClient()

client.trackDevices()
  .then(function(tracker) {
    tracker.on('add', function(device) {
      console.log('Device %s was plugged in', device.id)
    })
    tracker.on('remove', function(device) {
      console.log('Device %s was unplugged', device.id)
    })
    tracker.on('end', function() {
      console.log('Tracking stopped')
    })
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

Pulling a file from all connected devices

var Promise = require('bluebird')
var fs = require('fs')
var adb = require('adbkit')
var client = adb.createClient()

client.listDevices()
  .then(function(devices) {
    return Promise.map(devices, function(device) {
      return client.pull(device.id, '/system/build.prop')
        .then(function(transfer) {
          return new Promise(function(resolve, reject) {
            var fn = '/tmp/' + device.id + '.build.prop'
            transfer.on('progress', function(stats) {
              console.log('[%s] Pulled %d bytes so far',
                device.id,
                stats.bytesTransferred)
            })
            transfer.on('end', function() {
              console.log('[%s] Pull complete', device.id)
              resolve(device.id)
            })
            transfer.on('error', reject)
            transfer.pipe(fs.createWriteStream(fn))
          })
        })
    })
  })
  .then(function() {
    console.log('Done pulling /system/build.prop from all connected devices')
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

Pushing a file to all connected devices

var Promise = require('bluebird')
var adb = require('adbkit')
var client = adb.createClient()

client.listDevices()
  .then(function(devices) {
    return Promise.map(devices, function(device) {
      return client.push(device.id, 'temp/foo.txt', '/data/local/tmp/foo.txt')
        .then(function(transfer) {
          return new Promise(function(resolve, reject) {
            transfer.on('progress', function(stats) {
              console.log('[%s] Pushed %d bytes so far',
                device.id,
                stats.bytesTransferred)
            })
            transfer.on('end', function() {
              console.log('[%s] Push complete', device.id)
              resolve()
            })
            transfer.on('error', reject)
          })
        })
    })
  })
  .then(function() {
    console.log('Done pushing foo.txt to all connected devices')
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

List files in a folder

var Promise = require('bluebird')
var adb = require('adbkit')
var client = adb.createClient()

client.listDevices()
  .then(function(devices) {
    return Promise.map(devices, function(device) {
      return client.readdir(device.id, '/sdcard')
        .then(function(files) {
          // Synchronous, so we don't have to care about returning at the
          // right time
          files.forEach(function(file) {
            if (file.isFile()) {
              console.log('[%s] Found file "%s"', device.id, file.name)
            }
          })
        })
    })
  })
  .then(function() {
    console.log('Done checking /sdcard files on connected devices')
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

API

ADB

adb.createClient([options])

Creates a client instance with the provided options. Note that this will not automatically establish a connection, it will only be done when necessary.

adb.util.parsePublicKey(androidKey[, callback])

Parses an Android-formatted mincrypt public key (e.g. ~/.android/adbkey.pub).

adb.util.readAll(stream[, callback])

Takes a Stream and reads everything it outputs until the stream ends. Then it resolves with the collected output. Convenient with client.shell().

Client

client.clear(serial, pkg[, callback])

Deletes all data associated with a package from the device. This is roughly analogous to adb shell pm clear <pkg>.

client.connect(host[, port][, callback])

Connects to the given device, which must have its ADB daemon running in tcp mode (see client.tcpip()) and be accessible on the same network. Same as adb connect <host>:<port>.

Example - switch to TCP mode and set up a forward for Chrome devtools

Note: be careful with using client.listDevices() together with client.tcpip() and other similar methods that modify the connection with ADB. You might have the same device twice in your device list (i.e. one device connected via both USB and TCP), which can cause havoc if run simultaneously.

var Promise = require('bluebird')
var client = require('adbkit').createClient()

client.listDevices()
  .then(function(devices) {
    return Promise.map(devices, function(device) {
      return client.tcpip(device.id)
        .then(function(port) {
          // Switching to TCP mode causes ADB to lose the device for a
          // moment, so let's just wait till we get it back.
          return client.waitForDevice(device.id).return(port)
        })
        .then(function(port) {
          return client.getDHCPIpAddress(device.id)
            .then(function(ip) {
              return client.connect(ip, port)
            })
            .then(function(id) {
              // It can take a moment for the connection to happen.
              return client.waitForDevice(id)
            })
            .then(function(id) {
              return client.forward(id, 'tcp:9222', 'localabstract:chrome_devtools_remote')
                .then(function() {
                  console.log('Setup devtools on "%s"', id)
                })
            })
        })
    })
  })

client.disconnect(host[, port][, callback])

Disconnects from the given device, which should have been connected via client.connect() or just adb connect <host>:<port>.

client.forward(serial, local, remote[, callback])

Forwards socket connections from the ADB server host (local) to the device (remote). This is analogous to adb forward <local> <remote>. It's important to note that if you are connected to a remote ADB server, the forward will be created on that host.

client.framebuffer(serial[, format][, callback])

Fetches the current raw framebuffer (i.e. what is visible on the screen) from the device, and optionally converts it into something more usable by using GraphicsMagick's gm command, which must be available in $PATH if conversion is desired. Note that we don't bother supporting really old framebuffer formats such as RGB_565. If for some mysterious reason you happen to run into a >=2.3 device that uses RGB_565, let us know.

Note that high-resolution devices can have quite massive framebuffers. For example, a device with a resolution of 1920x1080 and 32 bit colors would have a roughly 8MB (1920*1080*4 byte) RGBA framebuffer. Empirical tests point to about 5MB/s bandwidth limit for the ADB USB connection, which means that it can take ~1.6 seconds for the raw data to arrive, or even more if the USB connection is already congested. Using a conversion will further slow down completion.

client.getDevicePath(serial[, callback])

Gets the device path of the device identified by the given serial number.

client.getDHCPIpAddress(serial[, iface][, callback])

Attemps to retrieve the IP address of the device. Roughly analogous to adb shell getprop dhcp.<iface>.ipaddress.

client.getFeatures(serial[, callback])

Retrieves the features of the device identified by the given serial number. This is analogous to adb shell pm list features. Useful for checking whether hardware features such as NFC are available (you'd check for 'android.hardware.nfc').

client.getPackages(serial[, callback])

Retrieves the list of packages present on the device. This is analogous to adb shell pm list packages. If you just want to see if something's installed, consider using client.isInstalled() instead.

client.getProperties(serial[, callback])

Retrieves the properties of the device identified by the given serial number. This is analogous to adb shell getprop.

client.getSerialNo(serial[, callback])

Gets the serial number of the device identified by the given serial number. With our API this doesn't really make much sense, but it has been implemented for completeness. FYI: in the raw ADB protocol you can specify a device in other ways, too.

client.getState(serial[, callback])

Gets the state of the device identified by the given serial number.

client.install(serial, apk[, callback])

Installs the APK on the device, replacing any previously installed version. This is roughly analogous to adb install -r <apk>.

Note that if the call seems to stall, you may have to accept a dialog on the phone first.

Example - install an APK from a URL

This example requires the request module. It also doesn't do any error handling (404 responses, timeouts, invalid URLs etc).

var client = require('adbkit').createClient()
var request = require('request')
var Readable = require('stream').Readable

// The request module implements old-style streams, so we have to wrap it.
client.install('<serial>', new Readable().wrap(request('http://example.org/app.apk')))
  .then(function() {
    console.log('Installed')
  })

client.installRemote(serial, apk[, callback])

Installs an APK file which must already be located on the device file system, and replaces any previously installed version. Useful if you've previously pushed the file to the device for some reason (perhaps to have direct access to client.push()'s transfer stats). This is roughly analogous to adb shell pm install -r <apk> followed by adb shell rm -f <apk>.

Note that if the call seems to stall, you may have to accept a dialog on the phone first.

client.isInstalled(serial, pkg[, callback])

Tells you if the specific package is installed or not. This is analogous to adb shell pm path <pkg> and some output parsing.

client.kill([callback])

This kills the ADB server. Note that the next connection will attempt to start the server again when it's unable to connect.

client.listDevices([callback])

Gets the list of currently connected devices and emulators.

client.listDevicesWithPaths([callback])

Like client.listDevices(), but includes the "path" of every device.

client.listForwards(serial[, callback])

Lists forwarded connections on the device. This is analogous to adb forward --list.

client.listReverses(serial[, callback])

Lists forwarded connections on the device. This is analogous to adb reverse --list.

client.openLocal(serial, path[, callback])

Opens a direct connection to a unix domain socket in the given path.

client.openLog(serial, name[, callback])

Opens a direct connection to a binary log file, providing access to the raw log data. Note that it is usually much more convenient to use the client.openLogcat() method, described separately.

client.openLogcat(serial[, options][, callback])

Calls the logcat utility on the device and hands off the connection to adbkit-logcat, a pure Node.js Logcat client. This is analogous to adb logcat -B, but the event stream will be parsed for you and a separate event will be emitted for every log entry, allowing for easy processing.

For more information, check out the adbkit-logcat documentation.

client.openMonkey(serial[, port][, callback])

Starts the built-in monkey utility on the device, connects to it using client.openTcp() and hands the connection to adbkit-monkey, a pure Node.js Monkey client. This allows you to create touch and key events, among other things.

For more information, check out the adbkit-monkey documentation.

client.openProcStat(serial[, callback])

Tracks /proc/stat and emits useful information, such as CPU load. A single sync service instance is used to download the /proc/stat file for processing. While doing this does consume some resources, it is very light and should not be a problem.

client.openTcp(serial, port[, host][, callback])

Opens a direct TCP connection to a port on the device, without any port forwarding required.

client.pull(serial, path[, callback])

A convenience shortcut for sync.pull(), mainly for one-off use cases. The connection cannot be reused, resulting in poorer performance over multiple calls. However, the Sync client will be closed automatically for you, so that's one less thing to worry about.

client.push(serial, contents, path[, mode][, callback])

A convenience shortcut for sync.push(), mainly for one-off use cases. The connection cannot be reused, resulting in poorer performance over multiple calls. However, the Sync client will be closed automatically for you, so that's one less thing to worry about.

client.readdir(serial, path[, callback])

A convenience shortcut for sync.readdir(), mainly for one-off use cases. The connection cannot be reused, resulting in poorer performance over multiple calls. However, the Sync client will be closed automatically for you, so that's one less thing to worry about.

client.reboot(serial[, callback])

Reboots the device. Similar to adb reboot. Note that the method resolves when ADB reports that the device has been rebooted (i.e. the reboot command was successful), not when the device becomes available again.

client.remount(serial[, callback])

Attempts to remount the /system partition in read-write mode. This will usually only work on emulators and developer devices.

client.reverse(serial, remote, local[, callback])

Reverses socket connections from the device (remote) to the ADB server host (local). This is analogous to adb reverse <remote> <local>. It's important to note that if you are connected to a remote ADB server, the reverse will be created on that host.

client.root(serial[, callback])

Puts the device into root mode which may be needed by certain shell commands. A remount is generally required after a successful root call. Note that this will only work if your device supports this feature. Production devices almost never do.

client.screencap(serial[, callback])

Takes a screenshot in PNG format using the built-in screencap utility. This is analogous to adb shell screencap -p. Sadly, the utility is not available on most Android <=2.3 devices, but a silent fallback to the client.framebuffer() command in PNG mode is attempted, so you should have its dependencies installed just in case.

Generating the PNG on the device naturally requires considerably more processing time on that side. However, as the data transferred over USB easily decreases by ~95%, and no conversion being required on the host, this method is usually several times faster than using the framebuffer. Naturally, this benefit does not apply if we're forced to fall back to the framebuffer.

For convenience purposes, if the screencap command fails (e.g. because it doesn't exist on older Androids), we fall back to client.framebuffer(serial, 'png'), which is slower and has additional installation requirements.

client.shell(serial, command[, callback])

Runs a shell command on the device. Note that you'll be limited to the permissions of the shell user, which ADB uses.

Example
var Promise = require('bluebird')
var adb = require('adbkit')
var client = adb.createClient()

client.listDevices()
  .then(function(devices) {
    return Promise.map(devices, function(device) {
      return client.shell(device.id, 'echo $RANDOM')
        // Use the readAll() utility to read all the content without
        // having to deal with the events. `output` will be a Buffer
        // containing all the output.
        .then(adb.util.readAll)
        .then(function(output) {
          console.log('[%s] %s', device.id, output.toString().trim())
        })
    })
  })
  .then(function() {
    console.log('Done.')
  })
  .catch(function(err) {
    console.error('Something went wrong:', err.stack)
  })

client.startActivity(serial, options[, callback])

Starts the configured activity on the device. Roughly analogous to adb shell am start <options>.

client.startService(serial, options[, callback])

Starts the configured service on the device. Roughly analogous to adb shell am startservice <options>.

client.stat(serial, path[, callback])

A convenience shortcut for sync.stat(), mainly for one-off use cases. The connection cannot be reused, resulting in poorer performance over multiple calls. However, the Sync client will be closed automatically for you, so that's one less thing to worry about.

client.syncService(serial[, callback])

Establishes a new Sync connection that can be used to push and pull files. This method provides the most freedom and the best performance for repeated use, but can be a bit cumbersome to use. For simple use cases, consider using client.stat(), client.push() and client.pull().

client.tcpip(serial, port[, callback])

Puts the device's ADB daemon into tcp mode, allowing you to use adb connect or client.connect() to connect to it. Note that the device will still be visible to ADB as a regular USB-connected device until you unplug it. Same as adb tcpip <port>.

client.trackDevices([callback])

Gets a device tracker. Events will be emitted when devices are added, removed, or their type changes (i.e. to/from offline). Note that the same events will be emitted for the initially connected devices also, so that you don't need to use both client.listDevices() and client.trackDevices().

Note that as the tracker will keep a connection open, you must call tracker.end() if you wish to stop tracking devices.

client.trackJdwp(serial[, callback])

Starts a JDWP tracker for the given device.

Note that as the tracker will keep a connection open, you must call tracker.end() if you wish to stop tracking JDWP processes.

client.uninstall(serial, pkg[, callback])

Uninstalls the package from the device. This is roughly analogous to adb uninstall <pkg>.

client.usb(serial[, callback])

Puts the device's ADB daemon back into USB mode. Reverses client.tcpip(). Same as adb usb.

client.version([callback])

Queries the ADB server for its version. This is mainly useful for backwards-compatibility purposes.

client.waitBootComplete(serial[, callback])

Waits until the device has finished booting. Note that the device must already be seen by ADB. This is roughly analogous to periodically checking adb shell getprop sys.boot_completed.

client.waitForDevice(serial[, callback])

Waits until ADB can see the device. Note that you must know the serial in advance. Other than that, works like adb -s serial wait-for-device. If you're planning on reacting to random devices being plugged in and out, consider using client.trackDevices() instead.

Sync

sync.end()

Closes the Sync connection, allowing Node to quit (assuming nothing else is keeping it alive, of course).

sync.pull(path)

Pulls a file from the device as a PullTransfer Stream.

sync.push(contents, path[, mode])

Attempts to identify contents and calls the appropriate push* method for it.

sync.pushFile(file, path[, mode])

Pushes a local file to the given path. Note that the path must be writable by the ADB user (usually shell). When in doubt, use '/data/local/tmp' with an appropriate filename.

sync.pushStream(stream, path[, mode])

Pushes a Stream to the given path. Note that the path must be writable by the ADB user (usually shell). When in doubt, use '/data/local/tmp' with an appropriate filename.

sync.readdir(path[, callback])

Retrieves a list of directory entries (e.g. files) in the given path, not including the . and .. entries, just like fs.readdir. If given a non-directory path, no entries are returned.

sync.stat(path[, callback])

Retrieves information about the given path.

sync.tempFile(path)

A simple helper method for creating appropriate temporary filenames for pushing files. This is essentially the same as taking the basename of the file and appending it to '/data/local/tmp/'.

PushTransfer

A simple EventEmitter, mainly for keeping track of the progress.

List of events:

pushTransfer.cancel()

Cancels the transfer by ending both the stream that is being pushed and the sync connection. This will most likely end up creating a broken file on your device. Use at your own risk. Also note that you must create a new sync connection if you wish to continue using the sync service.

PullTransfer

PullTransfer is a Stream. Use fs.createWriteStream() to pipe the stream to a file if necessary.

List of events:

pullTransfer.cancel()

Cancels the transfer by ending the connection. Can be useful for reading endless streams of data, such as /dev/urandom or /dev/zero, perhaps for benchmarking use. Note that you must create a new sync connection if you wish to continue using the sync service.

Incompatible changes in version 2.x

Previously, we made extensive use of callbacks in almost every feature. While this normally works okay, ADB connections can be quite fickle, and it was starting to become difficult to handle every possible error. For example, we'd often fail to properly clean up after ourselves when a connection suddenly died in an unexpected place, causing memory and resource leaks.

In version 2, we've replaced nearly all callbacks with Promises (using Bluebird), allowing for much more reliable error propagation and resource cleanup (thanks to .finally()). Additionally, many commands can now be cancelled on the fly, and although unimplemented at this point, we'll also be able to report progress on long-running commands without any changes to the API.

Unfortunately, some API changes were required for this change. client.framebuffer()'s callback, for example, previously accepted more than one argument, which doesn't translate into Promises so well. Thankfully, it made sense to combine the arguments anyway, and we were able to do it quite cleanly.

Furthermore, most API methods were returning the current instance for chaining purposes. While perhaps useful in some contexts, most of the time it probably didn't quite do what users expected, as chained calls were run in parallel rather than in serial fashion. Now every applicable API method returns a Promise, which is an incompatible but welcome change. This will also allow you to hook into yield and coroutines in Node 0.12.

However, all methods still accept (and will accept in the future) callbacks for those who prefer them.

Test coverage was also massively improved, although we've still got ways to go.

More information

Contributing

See CONTRIBUTING.md.

License

See LICENSE.

Copyright © The OpenSTF Project. All Rights Reserved.