main.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict'
  2. var Promise = require('bluebird')
  3. var adb = require('adbkit')
  4. var client = adb.createClient()
  5. var util = require('util')
  6. const { spawn } = require("child_process")
  7. var argv = require('minimist')(process.argv.slice(2))
  8. const serverAddr = argv.server; // Usage: node main.js --server $SERVER_ADDR
  9. function initDevice(device) {
  10. if (device.type != 'device') {
  11. return
  12. }
  13. client.shell(device.id, 'am start -a android.intent.action.VIEW -d http://www.stackoverflow.com')
  14. .then(adb.util.readAll)
  15. .then(function(output) {
  16. var args = ["-m", "uiautomator2", "init", "--serial", device.id]
  17. if (serverAddr) {
  18. args.push("--server", serverAddr);
  19. }
  20. const child = spawn("python", args);
  21. child.stdout.on("data", data => {
  22. process.stdout.write(data)
  23. })
  24. child.stderr.on("data", data => {
  25. process.stderr.write(data)
  26. })
  27. child.on('close', code => {
  28. util.log(`child process exited with code ${code}`);
  29. });
  30. })
  31. }
  32. util.log("tracking device")
  33. if (serverAddr) {
  34. util.log("server %s", serverAddr)
  35. }
  36. client.trackDevices()
  37. .then(function(tracker) {
  38. tracker.on('add', function(device) {
  39. util.log("Device %s(%s) was plugged in", device.id, device.type)
  40. initDevice(device)
  41. })
  42. tracker.on('remove', function(device) {
  43. util.log('Device %s was unplugged', device.id)
  44. })
  45. tracker.on("change", function(device) {
  46. util.log('Device %s was changed to %s', device.id, device.type)
  47. initDevice(device)
  48. })
  49. tracker.on('end', function() {
  50. util.log('Tracking stopped')
  51. })
  52. })