Run an adb commd on specified device, optionally printing the output
776554
def run_adb_command(command, device = nil)
      full_command = construct_adb_command command, device
      
      puts full_command
      pio = IO.popen(full_command, 'w')
      Process.wait(pio.pid)
    end
1299013
def shell(cmd):
    
    adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL, cmd]
    return _exec_command(adb_full_cmd)
833012
def print_device_info(dev_name):
    
    string_buffer = ctypes.create_string_buffer(1024)
    attributes = [pydaq.DAQmx_Dev_ProductType, pydaq.DAQmx_Dev_SerialNum,
                  pydaq.DAQmx_Dev_AO_PhysicalChans,
                  pydaq.DAQmx_Dev_CI_PhysicalChans,
                  pydaq.DAQmx_Dev_CO_PhysicalChans,
                  pydaq.DAQmx_Dev_DO_Lines]
    attribute_names = ['DAQmx_Dev_ProductType',
                       'DAQmx_Dev_SerialNum',
                       'DAQmx_Dev_AO_PhysicalChans',
                       'DAQmx_Dev_CI_PhysicalChans',
                       'DAQmx_Dev_CO_PhysicalChans',
                       'DAQmx_Dev_DO_Lines']
    ret_values = []
    for a in attributes:
        pydaq.DAQmxGetDeviceAttribute(dev_name, a, string_buffer)
        ret_values.append(str(string_buffer.value))

    print('Device Name:\t' + dev_name)
    for n, v in zip(attribute_names, ret_values):
        print '\t' + n + ':\t' + v
636970
public DeviceResult run(AndroidDebugBridge adb) {
    String testPackage = instrumentationInfo.getInstrumentationPackage();
    String testRunner = instrumentationInfo.getTestRunnerClass();

    logDebug(debug, "InstrumentationInfo: [%s]", instrumentationInfo);
    if (debug) {
      SpoonUtils.setDdmlibInternalLoggingLevel();
    }

    DeviceResult.Builder result = new DeviceResult.Builder();

    IDevice device = obtainRealDevice(adb, serial);
    logDebug(debug, "Got realDevice for [%s]", serial);

    // Get relevant device information.
    final DeviceDetails deviceDetails = DeviceDetails.createForDevice(device);
    result.setDeviceDetails(deviceDetails);
    logDebug(debug, "[%s] setDeviceDetails %s", serial, deviceDetails);

    DdmPreferences.setTimeOut((int) adbTimeout.toMillis());

    // Now install the main application and the instrumentation application.
    for (File otherApk : otherApks) {
      try {
        String extraArgument = getGrantAllExtraArgument(deviceDetails);
        device.installPackage(otherApk.getAbsolutePath(), true, extraArgument);
      } catch (InstallException e) {
        logInfo("InstallException while install other apk on device [%s]", serial);
        e.printStackTrace(System.out);
        return result.markInstallAsFailed("Unable to install other APK.").addException(e).build();
      }
    }
    try {
      String extraArgument = getGrantAllExtraArgument(deviceDetails);
      device.installPackage(testApk.getAbsolutePath(), true, extraArgument);
    } catch (InstallException e) {
      logInfo("InstallException while install test apk on device [%s]", serial);
      e.printStackTrace(System.out);
      return result.markInstallAsFailed("Unable to install instrumentation APK.")
          .addException(e)
          .build();
    }

    try {
      cleanScreenshotsDirectoriesOnDevice(device);
      cleanFilesDirectoriesOnDevice(device);
    } catch (Exception e) {
      logInfo("Exception while cleaning storage directories on device [%s]", serial);
      e.printStackTrace(System.out);
      return result.markInstallAsFailed(
          "Unable to delete storage directories").addException(e).build();
    }

    try {
      grantReadWriteExternalStorage(deviceDetails, device);
    } catch (Exception e) {
      logInfo("Exception while granting external storage access to application apk"
              + "on device [%s]", serial);
      e.printStackTrace(System.out);
      return result.markInstallAsFailed(
          "Unable to grant external storage access to application APK.").addException(e).build();
    }

    // Create the output directory, if it does not already exist.
    work.mkdirs();

    // Determine the test set that is applicable for this device.
    LogRecordingTestRunListener recorder;
    List<TestIdentifier> activeTests;
    List<TestIdentifier> ignoredTests;
    try {
      recorder = queryTestSet(testPackage, testRunner, device);
      activeTests = recorder.activeTests();
      ignoredTests = recorder.ignoredTests();
      logDebug(debug, "Active tests: %s", activeTests);
      logDebug(debug, "Ignored tests: %s", ignoredTests);
    } catch (Exception e) {
      return result
          .addException(e)
          .build();
    }

    // Initiate device logging.
    SpoonDeviceLogger deviceLogger = new SpoonDeviceLogger(device);

    List<ITestRunListener> listeners = new ArrayList<>();
    listeners.add(new SpoonTestRunListener(result, debug));
    listeners.add(new XmlTestRunListener(junitReport));
    if (testRunListeners != null) {
      listeners.addAll(testRunListeners);
    }

    result.startTests();
    if (singleInstrumentationCall) {
      try {
        logDebug(debug, "Running all tests in a single instrumentation call on [%s]", serial);
        RemoteAndroidTestRunner runner = createConfiguredRunner(testPackage, testRunner, device);
        runner.run(listeners);
      } catch (Exception e) {
        result.addException(e);
      }
    } else {
      MultiRunITestListener multiRunListener = new MultiRunITestListener(listeners);
      multiRunListener.multiRunStarted(recorder.runName(), recorder.testCount());

      for (TestIdentifier test : activeTests) {
        try {
          logDebug(debug, "Running %s on [%s]", test, serial);
          RemoteAndroidTestRunner runner = createConfiguredRunner(testPackage, testRunner, device);
          runner.removeInstrumentationArg("package");
          runner.removeInstrumentationArg("class");
          runner.setMethodName(test.getClassName(), test.getTestName());
          runner.run(listeners);
        } catch (Exception e) {
          result.addException(e);
        }
      }
      for (TestIdentifier ignoredTest : ignoredTests) {
        multiRunListener.testStarted(ignoredTest);
        multiRunListener.testIgnored(ignoredTest);
        multiRunListener.testEnded(ignoredTest, emptyMap());
      }

      multiRunListener.multiRunEnded();
    }
    result.endTests();

    mapLogsToTests(deviceLogger, result);

    try {
      logDebug(debug, "About to grab screenshots and prepare output for [%s]", serial);
      pullDeviceFiles(device);
      if (codeCoverage) {
        pullCoverageFile(device);
      }

      cleanScreenshotsDirectory(result);
      cleanFilesDirectory(result);

    } catch (Exception e) {
      result.addException(e);
    }
    logDebug(debug, "Done running for [%s]", serial);
    return result.build();
  }
763476
def devop_write(self, args, bustype):
        ''''''
        usage = "Usage: devop write <spi|i2c> name bus address regstart count <bytes>"
        if len(args) < 5:
            print(usage)
            return
        name = args[0]
        bus = int(args[1],base=0)
        address = int(args[2],base=0)
        reg = int(args[3],base=0)
        count = int(args[4],base=0)
        args = args[5:]
        if len(args) < count:
            print(usage)
            return
        bytes = [0]*128
        for i in range(count):
            bytes[i] = int(args[i],base=0)
        self.master.mav.device_op_write_send(self.target_system,
                                             self.target_component,
                                             self.request_id,
                                             bustype,
                                             bus,
                                             address,
                                             name,
                                             reg,
                                             count,
                                             bytes)
        self.request_id += 1
480557
async def monitor_mode(self, poll_devices=False, device=None,
                           workdir=None):
        """"""
        print("Running monitor mode")
        await self.connect(poll_devices, device, workdir)
        self.plm.monitor_mode()
915976
def Devices(args):
    
    for d in adb_commands.AdbCommands.Devices():
        if args.output_port_path:
            print('%s\tdevice\t%s' % (
                d.serial_number, ','.join(str(p) for p in d.port_path)))
        else:
            print('%s\tdevice' % d.serial_number)
    return 0
881419
def open(self):
        
        self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True)

        if self.device is not None:
            print "Serial printer enabled"
        else:
            print "Unable to open serial printer on: %s" % self.devfile
496857
def Shell(device, *command):
    
    if command:
        return device.StreamingShell(' '.join(command))
    else:
        # Retrieve the initial terminal prompt to use as a delimiter for future reads
        terminal_prompt = device.InteractiveShell()
        print(terminal_prompt.decode('utf-8'))

        # Accept user input in a loop and write that into the interactive shells stdin, then print output
        while True:
            cmd = input('> ')
            if not cmd:
                continue
            elif cmd == 'exit':
                break
            else:
                stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
                if stdout:
                    if isinstance(stdout, bytes):
                        stdout = stdout.decode('utf-8')
                        print(stdout)

        device.Close()
481234
def _write_device(self):
        """"""
        if not self._write_file:
            if not NIX:
                return None
            try:
                self._write_file = io.open(
                    self._character_device_path, 'wb')
            except PermissionError:
                # Python 3
                raise PermissionError(PERMISSIONS_ERROR_TEXT)
            except IOError as err:
                # Python 2 only
                if err.errno == 13:  # pragma: no cover
                    raise PermissionError(PERMISSIONS_ERROR_TEXT)
                else:
                    raise

        return self._write_file
73563
def root_adb(self):
        
        self.adb.root()
        self.adb.wait_for_device(
            timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND)
1087389
async def load_device_aldb(self, addr, clear=True):
        """"""
        dev_addr = Address(addr)
        device = None
        if dev_addr == self.plm.address:
            device = self.plm
        else:
            device = self.plm.devices[dev_addr.id]
        if device:
            if clear:
                device.aldb.clear()
            device.read_aldb()
            await asyncio.sleep(1, loop=self.loop)
            while device.aldb.status == ALDBStatus.LOADING:
                await asyncio.sleep(1, loop=self.loop)
            if device.aldb.status == ALDBStatus.LOADED:
                _LOGGING.info('ALDB loaded for device %s', addr)
            self.print_device_aldb(addr)
        else:
            _LOGGING.error('Could not find device %s', addr)
655238
def _write_to_device_and_return(cmd, ack, device_connection):
    ''''''
    log.debug('Write -> {}'.format(cmd.encode()))
    device_connection.write(cmd.encode())
    response = device_connection.read_until(ack.encode())
    log.debug('Read <- {}'.format(response))
    if ack.encode() not in response:
        raise SerialNoResponse(
            'No response from serial port after {} second(s)'.format(
                device_connection.timeout))
    clean_response = _parse_serial_response(response, ack.encode())
    if clean_response:
        return clean_response.decode()
    return ''
846194
def stdout_display():
    
    if sys.version_info[0] == 2:
        yield SmartBuffer(sys.stdout)
    else:
        yield SmartBuffer(sys.stdout.buffer)
1282174
function getAvailableCPUs(adbPath: string, device: string): Array<string> {
  try {
    const baseArgs = ['-s', device, 'shell', 'getprop'];

    let cpus = execFileSync(
      adbPath,
      baseArgs.concat(['ro.product.cpu.abilist']),
    ).toString();

    // pre-Lollipop
    if (!cpus || cpus.trim().length === 0) {
      cpus = execFileSync(
        adbPath,
        baseArgs.concat(['ro.product.cpu.abi']),
      ).toString();
    }

    return (cpus || '').trim().split(',');
  } catch (e) {
    return [];
  }
}
928377
async def write_aldb(self, addr, mem_addr: int, mode: str, group: int,
                         target, data1=0x00, data2=0x00, data3=0x00):
        """"""
        dev_addr = Address(addr)
        target_addr = Address(target)
        device = self.plm.devices[dev_addr.id]
        if device:
            _LOGGING.debug('calling device write_aldb')
            device.write_aldb(mem_addr, mode, group, target_addr,
                              data1, data2, data3)
            await asyncio.sleep(1, loop=self.loop)
            while device.aldb.status == ALDBStatus.LOADING:
                await asyncio.sleep(1, loop=self.loop)
            self.print_device_aldb(addr)
944699
def dump(device, args=None):
    '''
    
    '''
    cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
          '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
    ret = {}
    opts = [c[2:] for c in cmd.split() if c.startswith('--')]
    out = __salt__['cmd.run_all'](cmd, python_shell=False)
    if out['retcode'] == 0:
        lines = [line for line in out['stdout'].splitlines() if line]
        count = 0
        for line in lines:
            ret[opts[count]] = line
            count = count+1
        if args:
            temp_ret = {}
            for arg in args:
                temp_ret[arg] = ret[arg]
            return temp_ret
        else:
            return ret
    else:
        return False