Python usb.core() Examples

The following are 14 code examples of usb.core(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module usb , or try the search function .
Example #1
Source File: prober.py    From alienfx with GNU General Public License v3.0 6 votes vote down vote up
def find_controllers(vendor):
        """Go through the usb-bus and find devices(and most likely controllers) by vendor-id"""
        vid = int(vendor, 16)  # Convert our given Vendor-HEX-String to an equivalent intenger

        devs = usb.core.find(find_all=1)  # All USB devices
        devices = []  # List of found AFX-Controllers
        for dev in devs:
            if dev is not None:
                if dev.idVendor is not None:
                    if dev.idVendor == vid:
                        devices.append(dev)
        if len(devices):
            return devices
        return None 
Example #2
Source File: USBProxy.py    From Facedancer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, maxusb_app, verbose=0, index=0, quirks=[], scheduler=None, **kwargs):
        """
        Sets up a new USBProxy instance.
        """

        # Open a connection to the proxied device...
        usb_devices = list(usb.core.find(find_all=True, **kwargs))
        if len(usb_devices) <= index:
            raise DeviceNotFoundError("Could not find device to proxy!")
        self.libusb_device = usb_devices[index]


        try:
            interfaces = self.libusb_device.get_active_configuration().interfaces()
        except:
            print("-- could not read device interfaces --")
            interfaces = []


        # If possible, detach the device from any kernel-side driver that may prevent us
        # from communicating with it.
        for interface in interfaces:
            try:
                self.libusb_device.detach_kernel_driver(interface.bInterfaceNumber)
            except usb.core.USBError as e:
                if e.errno != errno.ENOENT:
                    print("-- could not detach interface {}--".format(interface))

        # ... and initialize our base class with a minimal set of parameters.
        # We'll do almost nothing, as we'll be proxying packets by default to the device.
        USBDevice.__init__(self, maxusb_app, verbose=verbose, quirks=quirks, scheduler=scheduler) 
Example #3
Source File: USBProxy.py    From Facedancer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def configured(self, configuration):
        """
        Callback that handles when the target device becomes configured.
        If you're using the standard filters, this will be called automatically;
        if not, you'll have to call it once you know the device has been configured.

        configuration: The configuration to be applied.
        """

        # Gather the configuration's endpoints for easy access, later...
        self.endpoints = {}
        for interface in configuration.interfaces:
            for endpoint in interface.endpoints:
                self.endpoints[endpoint.number] = endpoint

        # ... and pass our configuration on to the core device.
        self.maxusb_app.configured(configuration)
        configuration.set_device(self) 
Example #4
Source File: crazyradio.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def _find_devices():
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    if pyusb1:
        dev = usb.core.find(idVendor=0x1915, idProduct=0x7777, find_all=1, backend=pyusb_backend)
        if dev is not None:
            ret = dev
    else:
        busses = usb.busses()
        for bus in busses:
            for device in bus.devices:
                if device.idVendor == CRADIO_VID:
                    if device.idProduct == CRADIO_PID:
                        ret += [device, ]

    return ret 
Example #5
Source File: crazyradio.py    From crazyflie-lib-python with GNU General Public License v2.0 5 votes vote down vote up
def _find_devices(serial=None):
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    if pyusb1:
        for d in usb.core.find(idVendor=0x1915, idProduct=0x7777, find_all=1,
                               backend=pyusb_backend):
            if serial is not None and serial == d.serial_number:
                return d
            ret.append(d)
    else:
        busses = usb.busses()
        for bus in busses:
            for device in bus.devices:
                if device.idVendor == CRADIO_VID:
                    if device.idProduct == CRADIO_PID:
                        if serial == device.serial_number:
                            return device
                        ret += [device, ]

    return ret 
Example #6
Source File: cfusb.py    From crazyflie-lib-python with GNU General Public License v2.0 5 votes vote down vote up
def _find_devices():
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    logger.info('Looking for devices....')

    if pyusb1:
        for d in usb.core.find(idVendor=USB_VID, idProduct=USB_PID, find_all=1,
                               backend=pyusb_backend):
            if d.manufacturer == 'Bitcraze AB':
                ret.append(d)
    else:
        busses = usb.busses()
        for bus in busses:
            for device in bus.devices:
                if device.idVendor == USB_VID:
                    if device.idProduct == USB_PID:
                        ret += [device, ]

    return ret 
Example #7
Source File: protocol.py    From MonitorDarkly with GNU General Public License v3.0 5 votes vote down vote up
def _hook(self):
        try:
            self.dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
        except Exception as e:
            if self.verbose:
                traceback.print_exc()
                print(e)
            raise Exception("USB error!")
        if self.dev is None:
            raise Exception("Could not hook dell monitor, please verify connection!")
        if self.verbose:
            print("USB handle:")
            print(self.dev)
        # Default kernel driver sometimes hooks it first
        if self.dev.is_kernel_driver_active(0):
            self.dev.detach_kernel_driver(0) 
Example #8
Source File: USBProxy.py    From Facedancer with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _proxy_in_transfer(self, endpoint):
        """
        Proxy OUT requests, which sends a request from the target device to the
        victim, at the target's request.
        """

        ep_num = endpoint.number

        # Filter the "IN token" generated by the target device. We can use this
        # to e.g. change the endpoint before proxying to the target device, or
        # to absorb a packet before it's proxied.
        for f in self.filter_list:
            ep_num = f.filter_in_token(ep_num)

        if ep_num is None:
            return

        # Read the target data from the target device.
        endpoint_address = ep_num | 0x80


        # Quick hack to improve responsiveness on interrupt endpoints.
        try:
            if endpoint.interval:
                timeout = endpoint.interval
            else:
                timeout = None

            data = self.libusb_device.read(endpoint_address, endpoint.max_packet_size, timeout=timeout)
        except usb.core.USBError as e:
            if e.errno != errno.ETIMEDOUT:
                raise e
            else:
                return


        # Run the data through all of our filters.
        for f in self.filter_list:
            ep_num, data = f.filter_in(endpoint.number, data)

        # If our data wasn't filtered out, transmit it to the target!
        if data:
            endpoint.send_packet(data) 
Example #9
Source File: prober.py    From alienfx with GNU General Public License v3.0 4 votes vote down vote up
def get_controller():
        """ Go through the supported_controllers list in AlienFXController
        and see if any of them exist on the USB bus, Return the first one
        found, or None if none are found.
        """
        for controller in AlienFXController.supported_controllers:
            vid = controller.vendor_id
            pid = controller.product_id
            dev = usb.core.find(idVendor=vid, idProduct=pid)
            if dev is not None:
                return controller
        return None 
Example #10
Source File: cfusb.py    From crazyflie-lib-python with GNU General Public License v2.0 4 votes vote down vote up
def get_serial(self):
        # The signature for get_string has changed between versions to 1.0.0b1,
        # 1.0.0b2 and 1.0.0. Try the old signature first, if that fails try
        # the newer one.
        try:
            return usb.util.get_string(self.dev, 255, self.dev.iSerialNumber)
        except (usb.core.USBError, ValueError):
            return usb.util.get_string(self.dev, self.dev.iSerialNumber) 
Example #11
Source File: __init__.py    From loophole with MIT License 4 votes vote down vote up
def __init__(self):
            """
            Constructor.

            :return: Instance object.
            """
            import usb as usb
            import usb.core as usb_core

            self.usb = usb
            self.usb_core = usb_core
            self.ep_out_0 = None
            self.ep_in_0 = None
            self.usb_device = None
        # end-of-method __init__ 
Example #12
Source File: inception.py    From avatar2 with Apache License 2.0 4 votes vote down vote up
def reset(self):
        """
        Resets the target

        returns: True on success
        """

        self.log.debug("Resetting target")

        # Reset JTAG
        data = '3000000030000000'
        self._ep_out.write(bytearray.fromhex(data))

        # Enable the FlashPatch module : breakpoint
        # FlashPatch Control Register (FP_CTRL)
        self.write_memory(0xE0002000, 4, 3)

        # Now we need to retrive the number of supported hw bkpt from the core
        FP_CTRL = self.read_memory(0xE0002000)

        # bits [7:4] are number of code slots field
        self._bkpt_limit = (FP_CTRL >> 4) & 0xF 
        self.log.debug(("Number of available breakpoints read %d") % (self._bkpt_limit))
        if self._bkpt_limit == 0:
            raise Exception("No hardware breakpoint found")

        # Watchpoint are located @ bits [11:8]
        #w = (FP_CTRL >> 8) & 0xF

        # Set SYSRESETREG bit at 1 in AIRCR register to request a system reset.
        # (system reset of all major components except for debug)
        self.write_memory(0xE000ED0C, 4, ((0xFA05 << 16) | (1 << 2)))

        return True 
Example #13
Source File: inception.py    From avatar2 with Apache License 2.0 4 votes vote down vote up
def stop(self):
        """
        Stops the execution of the target

        :returns: True on success
        """

        self.log.debug("Attempted to stop execution of the target.")
        #DHCSR = self.read_memory(0xE000EDF0, 4)

        # Set C_HALT and C_DEBUGEN bits at 1 in DHCSR register
        self.write_memory(0xE000EDF0, 4, (0xA05F << 16) | 0b11)
        self._debug_enabled = True

        # Check the core is halted 
        DHCSR = self.read_memory(0xE000EDF0, 4)
        if not ((DHCSR >> 1) & 1):
            self.log.warning("Core not halted after stop")
        # Check the core acknowledges by reading S_HALT bit in DHCSR
        if not ((DHCSR >> 17) & 1):
            self.log.warning("Core not in debug state after stop")
            self._debug_enabled = False

        avatar_msg = UpdateStateMessage(self._origin, TargetStates.STOPPED)
        self._fast_queue.put(avatar_msg)

        return True 
Example #14
Source File: inception.py    From avatar2 with Apache License 2.0 4 votes vote down vote up
def step(self):
        """
        Steps one instruction

        :returns:  True on success
        """

        self.log.debug("Attempted to step on the target.")

        # Enable Debug mode if not activated
        if not self._debug_enabled:
            self.write_memory(0xE000EDF0, 4, ((0xA05F << 16) | 0b11))
            self._debug_enabled = True

        # Check the core acknowledges by reading S_HALT bit in DHCSR
        DHCSR = self.read_memory(0xE000EDF0, 4)
        if not ((DHCSR >> 17) & 1):
            self.log.warning("Core is not in debug state before stepping")

        # Execute a step by setting the C_STEP bit to 1 in DHCSR register
        self.write_memory(0xE000EDF0, 4, (0xA05F << 16) | 0b101)

        avatar_msg = UpdateStateMessage(self._origin, TargetStates.RUNNING)
        self._fast_queue.put(avatar_msg)

        # Check the core is halted 
        DHCSR = self.read_memory(0xE000EDF0, 4)
        if not ((DHCSR >> 1) & 1):
            self.log.warning("Core is not halted after single step")

        avatar_msg = UpdateStateMessage(self._origin, TargetStates.STOPPED)
        self._fast_queue.put(avatar_msg)

        return True