Read input device capability data from sysfs
771907
static Map<String, BitSet> readCapabilities(File sysPath) {
        Map<String, BitSet> capsMap = new HashMap<String, BitSet>();
        File[] capsFiles = new File(sysPath, "device/capabilities").listFiles();
        if (capsFiles == null) {
            return capsMap;
        }
        for (int i = 0; i < capsFiles.length; i++) {
            try {
                BufferedReader r = new BufferedReader(new FileReader(capsFiles[i]));
                String s = r.readLine();
                r.close();
                if (s == null) {
                    continue;
                }
                String[] elements = s.split(" ");
                if (elements == null) {
                    continue;
                }
                byte[] b = new byte[elements.length * (LinuxArch.is64Bit() ? 8 : 4)];
                ByteBuffer bb = ByteBuffer.wrap(b);
                bb.order(ByteOrder.LITTLE_ENDIAN);
                for (int j = elements.length - 1; j >= 0; j--) {
                    if (LinuxArch.is64Bit()) {
                        bb.putLong(Long.parseUnsignedLong(elements[j], 16));
                    } else {
                        bb.putInt(Integer.parseUnsignedInt(elements[j], 16));
                    }
                }
                capsMap.put(capsFiles[i].getName(), BitSet.valueOf(b));
            } catch (IOException | RuntimeException e) {
                e.printStackTrace();
            }
        }
        return capsMap;
    }
795728
function parseChassisData(statusData) {
        // sample data : 20 00 60 71 or 20 00 60
        var numStr = statusData.replace(/\s/g, '');
        assert.ok(numStr.match(/^[0-9A-Fa-f]{8}$|^[0-9A-Fa-f]{6}$/),
                  "Invalid chassis status output : " + statusData);
        var uidCode = parseInt(numStr[4], 16);
        var powerCode = parseInt(numStr[1], 16);

        // UID status need last 2 bit , so use mask 0x3(0011)
        // Power status need last bit , so use mask 0x1(0001)
        return {
            uid: uidStatus[uidCode & 0x3],
            power: (powerCode & 0x1) === 1
        };
    }
982506
def device_info(self):
        """"""
        return {
            'connections': {('mac', self.device['device_mac'])},
            'identifieres': self.device['device_id'],
            'manufacturer': 'Minut',
            'model': 'Point v{}'.format(self.device['hardware_version']),
            'name': self.device['description'],
            'sw_version': self.device['firmware']['installed'],
        }
822603
public void readData(DataInput din) throws IOException {

        // Get the size of any device-specific data.
        m_length = din.readUnsignedByte();
        if (m_length < 2 || m_length > 255) {
            return;
        }

        // Get the run status and device identifier.
        m_slaveId = din.readUnsignedByte();
        m_status = din.readUnsignedByte();

        /*
         * The device-specific data is two bytes shorter than the
         * length read previously.  That length includes the run status
         * and slave ID.
         */
        m_data = new byte[m_length - 2];
        if (m_length > 2) {
            din.readFully(m_data, 0, m_length - 2);
        }
    }
1252255
def device_info(self):
        
        info = {
            'serial': self.serial,
            'model': self.model,
            'build_info': self.build_info,
            'user_added_info': self._user_added_device_info
        }
        return info
743423
def _GetHWInfos(client_list, batch_size=10000, token=None):
  """"""

  # This function returns a dict mapping each client_id to a set of reported
  # hardware serial numbers reported by this client.
  hw_infos = {}

  logging.info("%d clients to process.", len(client_list))

  c = 0

  for batch in collection.Batch(client_list, batch_size):
    logging.info("Processing batch: %d-%d", c, c + batch_size)
    c += len(batch)

    client_objs = aff4.FACTORY.MultiOpen(batch, age=aff4.ALL_TIMES, token=token)

    for client in client_objs:
      hwi = client.GetValuesForAttribute(client.Schema.HARDWARE_INFO)

      hw_infos[client.urn] = set(["%s" % x.serial_number for x in hwi])

  return hw_infos
70207
def serial_number():
    """"""
    sdata = {}
    if os.getuid() == 0:
        try:
            sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \
                .read().strip()
        except:
            for line in os.popen('/usr/sbin/dmidecode -s system-serial-number'):
                sdata['Serial'] = line.strip()
    return sdata
821535
def _resolve_hardware_count(self):
        
        length = len([d for d in self._dut_requirements if d.get("type") in ["hardware",
                                                                             "serial", "mbed"]])
        self._hardware_count = length
563930
def _parse_udevadm_info(udev_info):
    '''
    
    '''
    devices = []
    dev = {}

    for line in (line.strip() for line in udev_info.splitlines()):
        if line:
            line = line.split(':', 1)
            if len(line) != 2:
                continue
            query, data = line
            if query == 'E':
                if query not in dev:
                    dev[query] = {}
                key, val = data.strip().split('=', 1)

                try:
                    val = int(val)
                except ValueError:
                    try:
                        val = float(val)
                    except ValueError:
                        pass  # Quiet, this is not a number.

                dev[query][key] = val
            else:
                if query not in dev:
                    dev[query] = []
                dev[query].append(data.strip())
        else:
            if dev:
                devices.append(_normalize_info(dev))
                dev = {}
    if dev:
        _normalize_info(dev)
        devices.append(_normalize_info(dev))

    return devices
1087941
def info(device):
    '''
    
    '''
    out = __salt__['cmd.run_all']("xfs_info {0}".format(device))
    if out.get('stderr'):
        raise CommandExecutionError(out['stderr'].replace("xfs_info:", "").strip())
    return _parse_xfs_info(out['stdout'])
566380
def devices():
    '''
    
    '''
    out = __salt__['cmd.run_all']("blkid -o export")
    salt.utils.fsutils._verify_run(out)

    return salt.utils.fsutils._blkid_output(out['stdout'], fs_type='btrfs')
1238569
def load_capabilities(caps)
      device = @server.device_data
      unless device.nil?
        caps[:caps][:udid] = device.fetch('udid', nil)
        caps[:caps][:platformVersion] = device.fetch('os', caps[:caps][:platformVersion])
        caps[:caps][:deviceName] = device.fetch('name', caps[:caps][:deviceName])
        caps[:caps][:wdaLocalPort] = device.fetch('wdaPort', nil)
        caps[:caps][:avd] = device.fetch('avd', nil)
      end

      caps[:appium_lib][:server_url] = ENV['SERVER_URL']
      caps
    end
1243281
def begin(self):
		
		# Check manufacturer and device ID match expected values.
		mid = self._device.readU16BE(MCP9808_REG_MANUF_ID)
		did = self._device.readU16BE(MCP9808_REG_DEVICE_ID)
		self._logger.debug('Read manufacturer ID: {0:04X}'.format(mid))
		self._logger.debug('Read device ID: {0:04X}'.format(did))
		return mid == 0x0054 and did == 0x0400
487094
def get_server_capabilities(self):
        
        capabilities = {}

        sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
        sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
        try:
            count = len(sushy_system.pci_devices.gpu_devices)
            boot_mode = rf_utils.get_supported_boot_mode(
                sushy_system.supported_boot_mode)
            capabilities.update(
                {'pci_gpu_devices': count,
                 'ilo_firmware_version': sushy_manager.firmware_version,
                 'rom_firmware_version': sushy_system.rom_version,
                 'server_model': sushy_system.model,
                 'nic_capacity': sushy_system.pci_devices.max_nic_capacity,
                 'boot_mode_bios': boot_mode.boot_mode_bios,
                 'boot_mode_uefi': boot_mode.boot_mode_uefi})

            tpm_state = sushy_system.bios_settings.tpm_state
            all_key_to_value_expression_tuples = [
                ('sriov_enabled',
                 sushy_system.bios_settings.sriov == sys_cons.SRIOV_ENABLED),
                ('cpu_vt',
                 sushy_system.bios_settings.cpu_vt == (
                     sys_cons.CPUVT_ENABLED)),
                ('trusted_boot',
                 (tpm_state == sys_cons.TPM_PRESENT_ENABLED
                  or tpm_state == sys_cons.TPM_PRESENT_DISABLED)),
                ('secure_boot', self._has_secure_boot()),
                ('iscsi_boot',
                 (sushy_system.bios_settings.iscsi_resource.
                  is_iscsi_boot_supported())),
                ('hardware_supports_raid',
                 len(sushy_system.smart_storage.array_controllers.
                     members_identities) > 0),
                ('has_ssd',
                 common_storage.has_ssd(sushy_system)),
                ('has_rotational',
                 common_storage.has_rotational(sushy_system)),
                ('has_nvme_ssd',
                 common_storage.has_nvme_ssd(sushy_system))
                ]

            all_key_to_value_expression_tuples += (
                [('logical_raid_level_' + x, True)
                 for x in sushy_system.smart_storage.logical_raid_levels])

            all_key_to_value_expression_tuples += (
                [('drive_rotational_' + str(x) + '_rpm', True)
                 for x in
                 common_storage.get_drive_rotational_speed_rpm(sushy_system)])

            capabilities.update(
                {key: 'true'
                 for (key, value) in all_key_to_value_expression_tuples
                 if value})

            memory_data = sushy_system.memory.details()

            if memory_data.has_nvdimm_n:
                capabilities.update(
                    {'persistent_memory': (
                     json.dumps(memory_data.has_persistent_memory)),
                     'nvdimm_n': (
                     json.dumps(memory_data.has_nvdimm_n)),
                     'logical_nvdimm_n': (
                     json.dumps(memory_data.has_logical_nvdimm_n))})

        except sushy.exceptions.SushyError as e:
            msg = (self._("The Redfish controller is unable to get "
                          "resource or its members. Error "
                          "%(error)s)") % {'error': str(e)})
            LOG.debug(msg)
            raise exception.IloError(msg)
        return capabilities
754447
def _detect_hardware_and_os(self, ssh):
        

        info = {
            'series': '',
            'arch': '',
            'cpu-cores': '',
            'mem': '',
        }

        stdout, stderr = self._run_command(
            ssh,
            ["sudo", "/bin/bash -c " + shlex.quote(DETECTION_SCRIPT)],
            pty=True,
        )

        lines = stdout.split("\n")
        info['series'] = lines[0].strip()
        info['arch'] = normalize_arch(lines[1].strip())

        memKb = re.split(r'\s+', lines[2])[1]

        # Convert megabytes -> kilobytes
        info['mem'] = round(int(memKb) / 1024)

        # Detect available CPUs
        recorded = {}
        for line in lines[3:]:
            physical_id = ""
            print(line)

            if line.find("physical id") == 0:
                physical_id = line.split(":")[1].strip()
            elif line.find("cpu cores") == 0:
                cores = line.split(":")[1].strip()

                if physical_id not in recorded.keys():
                    info['cpu-cores'] += cores
                    recorded[physical_id] = True

        return info
1190056
def get_memory_info(self) -> str:
        ''''''
        output, _ = self._execute(
            '-s', self.device_sn, 'shell', 'cat', '/proc/meminfo')
        return output
166164
def cmd_output_sysid(self, args):
        ''''''
        sysid = int(args[0])
        device = args[1]
        print("Adding output %s for sysid %u" % (device, sysid))
        try:
            conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
            conn.mav.srcComponent = self.settings.source_component
        except Exception:
            print("Failed to connect to %s" % device)
            return
        try:
            mp_util.child_fd_list_add(conn.port.fileno())
        except Exception:
            pass
        if sysid in self.mpstate.sysid_outputs:
            self.mpstate.sysid_outputs[sysid].close()
        self.mpstate.sysid_outputs[sysid] = conn