Ensures the HID function in the USB Android gadget driver is active
6689
async function enableHID() {
  const usbConfig = getstrprop('sys.usb.state');
  if (!usbConfig.startsWith('hid,')) {
    log.warn('HID function does not seem to be enabled.');
    const usbConfigWithHid = `hid,${usbConfig}`;
    log.info(`changing USB config to ${usbConfigWithHid}`);

    // WARNING!  If this device is not Kenzo or this otherwise fails, it's likely
    // that adb access will be lost until the next reboot
    setprop('sys.usb.config', usbConfigWithHid);

    // Wait for USB to be reconfigured.
    await sleep(1000);

    const newUsbConfig = getstrprop('sys.usb.state');
    if (newUsbConfig !== usbConfigWithHid) {
      throw new Error(`USB config expected to be ${usbConfigWithHid}, but it was ${newUsbConfig}`);
    }
  }

  // Ensure the two HID devices are present
  Promise.all(
    ['/dev/hidg0', '/dev/hidg1'].map(
      file => fs.access(file, fs.constants.R_OK | fs.constants.W_OK)
    )
  );
}
1268595
def _open(self, skip=0):
        
        usb_device = self._get_usb_device(skip)

        if usb_device:
            usb_conf = usb_device.configurations[0]
            self._usb_int = usb_conf.interfaces[0][0]
        else:
            raise YubiKeyUSBHIDError('No USB YubiKey found')

        try:
            self._usb_handle = usb_device.open()
            self._usb_handle.detachKernelDriver(0)
        except Exception as error:
            if 'could not detach kernel driver from interface' in str(error):
                self._debug('The in-kernel-HID driver has already been detached\n')
            else:
                self._debug("detachKernelDriver not supported!\n")

        try:
            self._usb_handle.setConfiguration(1)
        except usb.USBError:
            self._debug("Unable to set configuration, ignoring...\n")
        self._usb_handle.claimInterface(self._usb_int)
        return True
476722
function closeInactiveDevices(bundle) {
        debugSS('in closeInactiveDevices');
        var defered = q.defer();

        self.deviceManager.closeDevicesOpenedByScanner()
        .then(function() {
            defered.resolve(bundle);
        })
        .catch(function() {
            defered.resolve(bundle);
        });
        return defered.promise;
    }
1271450
def status_light(self):
        
        result = self.deviceProperties.GetLEDState()
        LEDState = result["CurrentLEDState"]  # pylint: disable=invalid-name
        return True if LEDState == "On" else False
158477
function turnOff(device) {
    return api.request('/device/turnOff?' + querystring.stringify({id: device.id || device}));
  }
257173
def device_not_active(self, addr):
        """"""
        self.aldb_device_handled(addr)
        for callback in self._cb_device_not_active:
            callback(addr)
47451
def _lock(self):
        """"""
        if not self.locked:
            self.device.cu.lock()
            self.locked = True
544103
def visibility_changed(self, enable):
        """"""
        SpyderPluginWidget.visibility_changed(self, enable)
        if self.dockwidget is None:
            return
        if self.dockwidget.isWindow():
            self.dock_toolbar.show()
        else:
            self.dock_toolbar.hide()
        if enable:
            self.refresh_plugin()
        self.sig_update_plugin_title.emit()
75793
def click_signal(target_usage, target_vendor_id):
    """"""
    # usually you'll find and open the target device, here we'll browse for the
    # current connected devices
    all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()

    if not all_devices:
        print("Can't find target device (vendor_id = 0x%04x)!" % target_vendor_id)
    else:
        # search for our target usage
        # target pageId, usageId

        for device in all_devices:
            try:
                device.open()
                # browse output reports, we could search over feature reports also,
                # changing find_output_reports() to find_feature_reports()
                for report in device.find_output_reports():
                    if target_usage in report:
                        # found out target!
                        report[target_usage] = 1 # yes, changing values is that easy
                        # at this point you could change different usages at a time...
                        # and finally send the prepared output report
                        report.send()
                        # now toggle back the signal
                        report[target_usage] = 0
                        report.send()
                        print("\nUsage clicked!\n")
                        return
            finally:
                device.close()
        print("The target device was found, but the requested usage does not exist!\n")
46821
def toggle(self):
        
        for device in self:
            if isinstance(device, (OutputDevice, CompositeOutputDevice)):
                device.toggle()
874221
def activate(self):
        
        response = self.api_interface.set_device_state(self, None)
        self._update_state_from_response(response)
619807
protected function _usb()
    {
        if (CommonFunctions::executeProgram('listusb', '', $bufr, PSI_DEBUG)) {
            $devices = preg_split("/\n/", $bufr);
            foreach ($devices as $device) {
                if (preg_match("/^\S+\s+\S+\s+\"(.*)\"\s+\"(.*)\"/", $device, $ar_buf)) {
                    $dev = new HWDevice();
                    $dev->setName(trim($ar_buf[1]." ".$ar_buf[2]));
                    $this->sys->setUSBDevices($dev);
                }
            }
        }
    }
298087
def claim_interface
			devices = usb.devices(:idVendor => VENDOR_ID, :idProduct => PRODUCT_ID)

			unless devices.first then
				return
			end

			@device = devices.first
			@handle = @device.open
			
			@handle.detach_kernel_driver(HID_INTERFACE)
			@handle.claim_interface( HID_INTERFACE )
		end
542773
function markAndAddActiveDevices(bundle) {
        debugSS('in markAndAddActiveDevices');
        debugLFDS('in markAndAddActiveDevices');
        var defered = q.defer();

        // self.cachedScanBundle.scannedData
        debugMACT('Checking for any previously marked active devices in the last scan cache');

        function isDeviceStillActive(sn) {
            var isActive = false;
            self.cachedCurrentDevices.forEach(function(cachedDevice) {
                var savedAttributes = cachedDevice.savedAttributes;
                var serialNumber = savedAttributes.serialNumber;
                if(sn === serialNumber) {
                    isActive = true;
                }
            });
            return isActive;
        }
        // We need to un-mark any active devices that are no longer active.

        if(self.cachedScanBundle) {
            if(self.cachedScanBundle.scannedData) {
                // debugMACT('We have previously found scanned data', self.cachedScanBundle.scannedData);
                debugMACT('We have previously found scanned data');
                debugPrintFlatScannedData(self.cachedScanBundle.scannedData, debugMACT);
                var scannedData = self.cachedScanBundle.scannedData;
                var dKeys = Object.keys(self.cachedScanBundle.scannedData);
                dKeys.forEach(function(dKey) {
                    var dInfo = scannedData[dKey];
                    var isDeviceActive = dInfo.isActive;
                    var isActuallyActive = isDeviceStillActive(dInfo.serialNumber);
                    debugMACT('SN', dInfo.serialNumber, 'active?',isActuallyActive);
                    // Check to see if the device has the correct active state
                    if(dInfo.isActive != isActuallyActive) {
                        // The device is not actually active...
                        dInfo.isActive = false;
                        // loop through the connection types & fix the active connection.
                        var ctKeys = Object.keys(dInfo.connectionTypes);
                        ctKeys.forEach(function(ctKey) {
                            if(dInfo.connectionTypes[ctKey].isActive) {
                                dInfo.connectionTypes[ctKey].isActive = false;
                                dInfo.connectionTypes[ctKey].insertionMethod = 'scan';
                            }
                        });
                    }
                });
            }
        }

        var promises = self.deviceManager.addCuratedDevices(
            self.cachedCurrentDevices
        );
        
        // Wait for all of the curated devices to get added.
        q.allSettled(promises)
        .then(function() {
            defered.resolve(bundle);
        }, function() {
            defered.resolve(bundle);
        });

        return defered.promise;
    }
464090
def deactivate(self):
        
        if self._driver and self._driver.is_connected():
            self._driver.deactivate()
1032952
def show_hids(target_vid = 0, target_pid = 0, output = None):
    """"""
    # first be kind with local encodings
    if not output:
        # beware your script should manage encodings
        output = sys.stdout
    # then the big cheese...
    from . import tools
    all_hids = None
    if target_vid:
        if target_pid:
            # both vendor and product Id provided
            device_filter = HidDeviceFilter(vendor_id = target_vid,
                    product_id = target_pid)
        else:
            # only vendor id
            device_filter = HidDeviceFilter(vendor_id = target_vid)

        all_hids = device_filter.get_devices()
    else:
        all_hids = find_all_hid_devices()
    if all_hids:
        print("Found HID class devices!, writting details...")
        for dev in all_hids:
            device_name = str(dev)
            output.write(device_name)
            output.write('\n\n  Path:      %s\n' % dev.device_path)
            output.write('\n  Instance:  %s\n' % dev.instance_id)
            output.write('\n  Port (ID): %s\n' % dev.get_parent_instance_id())
            output.write('\n  Port (str):%s\n' % str(dev.get_parent_device()))
            #
            try:
                dev.open()
                tools.write_documentation(dev, output)
            finally:
                dev.close()
        print("done!")
    else:
        print("There's not any non system HID class device available")
1037906
private void updateConnectedDevices(final List<USBStorageDevice> currentConnectedDevices) {
        final List<USBStorageDevice> removedDevices = new ArrayList<>();

        synchronized (this) {
            final Iterator<USBStorageDevice> itConnectedDevices = connectedDevices.iterator();

            while (itConnectedDevices.hasNext()) {
                final USBStorageDevice device = itConnectedDevices.next();

                if (currentConnectedDevices.contains(device)) {
                    currentConnectedDevices.remove(device);
                } else {
                    removedDevices.add(device);

                    itConnectedDevices.remove();
                }
            }

            connectedDevices.addAll(currentConnectedDevices);
        }

        currentConnectedDevices.forEach(device ->
                sendEventToListeners(new USBStorageEvent(device, DeviceEventType.CONNECTED)));

        removedDevices.forEach(device ->
                sendEventToListeners(new USBStorageEvent(device, DeviceEventType.REMOVED)));
    }