示例#1
0
    def __init__(self, dev):
        self.dev = dev
        self.cfg = cfg = dev.get_active_configuration()

        self.intf = intf = find_descriptor(
            cfg,
            bInterfaceClass=CONFIG["class"],
            bInterfaceSubClass=CONFIG["subclass"],
            # bInterfaceProtocol=CCID_PROTOCOL_0,
        )
        if intf is None:
            raise ValueError("Not a CCID device")

        claim_interface(dev, intf)

        for ep in intf:
            if (endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and
                    endpoint_direction(ep.bEndpointAddress) == ENDPOINT_OUT):
                self.bulkout = ep.bEndpointAddress
            if (endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and
                    endpoint_direction(ep.bEndpointAddress) == ENDPOINT_IN):
                self.bulkin = ep.bEndpointAddress

        self.seq = 0
        self.timeout = 10000
示例#2
0
    def __init__(self, device):
        """Create a new PtpUsbTransport instance.
        
        Arguments:
        device -- USB ptp device."""

        # Device
        self.__device = device

        # Device interface
        self.__usb_interface = PtpUsbTransport.retrieve_device_interface(
            self.__device)
        if self.__usb_interface.bInterfaceClass != PtpUsbTransport.USB_CLASS_PTP:
            raise UsbException("Device")

        # Device endpoints
        self.__bulkin = None
        self.__bulkout = None
        self.__irqin = None
        self.__bulkin, self.__bulkout, self.__irqin = PtpUsbTransport.retrieve_device_endpoints(
            self.__device)
        if (self.__bulkin == None) or (self.__bulkout == None) or (self.__irqin
                                                                   == None):
            raise RuntimeError("Unable to find all required endpoints")

        # Open the USB device
        # self.__usb_handle.set_configuration(test)
        claim_interface(self.__device, self.__usb_interface)
        device_name = PtpUsbTransport.retrieve_device_name(self.__device)
        print(f"Connected to {device_name}.")
        self.usb_read_timeout = 5000
        self.usb_write_timeout = 5000
示例#3
0
    def __init__(self):
        super().__init__("IS-NITRO-Emulator")
        self.device = find(idVendor=0x0F6e, idProduct=0x0404)

        if self.device is None:
            raise DeviceNotFound(self)

        if self.debug:
            self.print_configurations()

        self.device.set_configuration()
        # self.device.reset()  # Prevent weird timeouts when used twice

        config = self.device.get_active_configuration()
        interface = config[(0, 0)]

        # Claim interface
        if self.device.is_kernel_driver_active(interface.iInterface):
            self.device.detach_kernel_driver(interface.iInterface)
            claim_interface(self.device, interface.iInterface)

        self.endpoint_out = find_descriptor(interface,
                                            bEndpointAddress=0x01)  # Bulk Out
        self.endpoint_in = find_descriptor(interface,
                                           bEndpointAddress=0x82)  # Bulk in
        # self.endpoint_debug = find_descriptor(interface, bEndpointAddress=0x83)  # Bulk in 2?

        assert self.endpoint_out is not None
        assert self.endpoint_in is not None

        self.isid = resource_stream(__name__, "../resources/isid.bin").read()
        self.debugger_code = resource_stream(
            __name__, "../resources/debugger_code.bin").read()
示例#4
0
文件: legacy.py 项目: wrtcoder/stuff
    def claimInterface(self, interface):
        r"""Claims the interface with the Operating System.

        Arguments:
            interface: interface number or an Interface object.
        """
        util.claim_interface(self.dev, interface)
        self.__claimed_interface = interface
示例#5
0
文件: legacy.py 项目: ChrisX34/stuff
    def claimInterface(self, interface):
        r"""Claims the interface with the Operating System.

        Arguments:
            interface: interface number or an Interface object.
        """
        util.claim_interface(self.dev, interface)
        self.__claimed_interface = interface
示例#6
0
文件: usb.py 项目: slater1/libant
    def _open(self) -> None:
        print('USB OPEN START')
        try:
            # find the first USB device that matches the filter
            self._dev = find(idVendor=self._idVendor,
                             idProduct=self._idProduct)

            if self._dev is None:
                raise DriverException("Could not open specified device")

            # Detach kernel driver
            try:
                if self._dev.is_kernel_driver_active(0):
                    try:
                        self._dev.detach_kernel_driver(0)
                    except USBError as e:
                        raise DriverException("Could not detach kernel driver")
            except NotImplementedError:
                pass  # for non unix systems

            # set the active configuration. With no arguments, the first
            # configuration will be the active one
            self._dev.set_configuration()

            # get an endpoint instance
            cfg = self._dev.get_active_configuration()
            self._interfaceNumber = cfg[(0, 0)].bInterfaceNumber
            interface = find_descriptor(cfg,
                                        bInterfaceNumber=self._interfaceNumber,
                                        bAlternateSetting=get_interface(
                                            self._dev, self._interfaceNumber))
            claim_interface(self._dev, self._interfaceNumber)

            self._epOut = find_descriptor(
                interface,
                custom_match=lambda e: endpoint_direction(e.bEndpointAddress
                                                          ) == ENDPOINT_OUT)

            self._epIn = find_descriptor(
                interface,
                custom_match=lambda e: endpoint_direction(e.bEndpointAddress
                                                          ) == ENDPOINT_IN)

            if self._epOut is None or self._epIn is None:
                raise DriverException("Could not initialize USB endpoint")

            self._queue = Queue()
            self._loop = self.USBLoop(self._epIn, self._packetSize,
                                      self._queue)
            self._loop.start()
            self._driver_open = True
            print('USB OPEN SUCCESS')
        except IOError as e:
            self._close()
            raise DriverException(str(e))
示例#7
0
    def claimInterface(self, interface):
        r"""Claims the interface with the Operating System.

        Arguments:
            interface: interface number or an Interface object.
        """
        if_num = interface.interfaceNumber \
                if isinstance(interface, Interface) else interface

        util.claim_interface(self.dev, if_num)
        self.__claimed_interface = if_num
示例#8
0
def openDev():
    global dev
    dev = usb.core.find(idVendor=VID, idProduct=PID)
    if dev is None:
        raise ValueError('Device not found')

    if dev.is_kernel_driver_active(0):
        dev.detach_kernel_driver(0)
    dev.set_configuration(
    )  # do reset and set active conf. Must be done before claim.
    # intf number changed from None to 0
    util.claim_interface(dev, 0)
示例#9
0
def openPort(Vid, Pid, ifc):
    global dev
    # Find glove
    dev = core.find(idVendor=Vid, idProduct=Pid)
    # Return if glove isn't found
    if dev is None:
        return None
    # Claim interface
    if dev.is_kernel_driver_active(ifc) is True:
        dev.detach_kernel_driver(ifc)
    util.claim_interface(dev, ifc)
    return 0
示例#10
0
    def __init__(self, dev):
        """
        __init__(dev) -> None
        Initialize the DEV of CCID.
        device: usb.core.Device object.
        """

        cfg = dev.get_active_configuration()
        intf = find_descriptor(cfg,
                               bInterfaceClass=CCID_CLASS,
                               bInterfaceSubClass=CCID_SUBCLASS,
                               bInterfaceProtocol=CCID_PROTOCOL_0)
        if intf is None:
            raise ValueError("Not a CCID device")

        try:
            claim_interface(dev, intf)
        except Exception as e:
            print(e)

        for ep in intf:
            if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \
               endpoint_direction(ep.bEndpointAddress) == ENDPOINT_OUT:
                self.__bulkout = ep.bEndpointAddress
            if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \
               endpoint_direction(ep.bEndpointAddress) == ENDPOINT_IN:
                self.__bulkin = ep.bEndpointAddress

        assert len(intf.extra_descriptors) == 54
        assert intf.extra_descriptors[1] == 33

        if (intf.extra_descriptors[42] & 0x02):
            # Short APDU level exchange
            self.__use_APDU = True
        elif (intf.extra_descriptors[42] & 0x04):
            # Short and extended APDU level exchange
            self.__use_APDU = True
        elif (intf.extra_descriptors[42] & 0x01):
            # TPDU level exchange
            self.__use_APDU = False
        else:
            raise ValueError("Unknown exchange level")

        # Check other bits???
        #       intf.extra_descriptors[40]
        #       intf.extra_descriptors[41]

        self.__dev = dev
        self.__timeout = 10000
        self.__seq = 0
示例#11
0
def get_device_handle():
    dev = core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
    if dev is None:
        raise SystemError("Device not found!")

    interface = 0  # HID

    # Free red button from kernel driver
    # This does not work on OSX
    if dev.is_kernel_driver_active(interface) is True:
        dev.detach_kernel_driver(interface)
        util.claim_interface(dev, interface)
        kernel_was_attached = True

    return dev
示例#12
0
    def _open(self):
        # Most of this is straight from the PyUSB example documentation
        dev = findDeviceUSB(
            idVendor=self.idVendor,
            idProduct=self.idProduct,
            custom_match=lambda d: (d.bus == self.bus or self.bus is None) and
            (d.address == self.address or self.address is None))

        if dev is None:
            raise DriverError("Could not open device (not found)")

        # make sure the kernel driver is not active
        try:
            if dev.is_kernel_driver_active(0):
                try:
                    dev.detach_kernel_driver(0)
                except USBError as e:
                    exit("could not detach kernel driver: {}".format(e))
        except NotImplementedError:
            pass  # for non unix systems

        dev.set_configuration()
        cfg = dev.get_active_configuration()
        interfaceNumber = cfg[(0, 0)].bInterfaceNumber

        intf = find_descriptor(cfg,
                               bInterfaceNumber=interfaceNumber,
                               bAlternateSetting=get_interface(
                                   dev, interfaceNumber))

        claim_interface(dev, interfaceNumber)

        endpoint_out_matcher = \
            lambda e: endpoint_direction(e.bEndpointAddress) == ENDPOINT_OUT
        epOut = find_descriptor(intf, custom_match=endpoint_out_matcher)
        assert epOut is not None

        endpoint_in_matcher = \
            lambda e: endpoint_direction(e.bEndpointAddress) == ENDPOINT_IN
        ep_in = find_descriptor(intf, custom_match=endpoint_in_matcher)
        assert ep_in is not None

        self._epOut = epOut
        self._epIn = ep_in
        self._dev = dev
        self._intNum = interfaceNumber
示例#13
0
    def __init__(self, dev):
        """
        __init__(dev) -> None
        Initialize the DEV of CCID.
        device: usb.core.Device object.
        """

        cfg = dev.get_active_configuration()
        intf = find_descriptor(cfg, bInterfaceClass=CCID_CLASS,
                               bInterfaceSubClass=CCID_SUBCLASS,
                               bInterfaceProtocol=CCID_PROTOCOL_0)
        if intf is None:
            raise ValueError("Not a CCID device")

        claim_interface(dev, intf)

        for ep in intf:
            if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \
               endpoint_direction(ep.bEndpointAddress) == ENDPOINT_OUT:
               self.__bulkout = ep.bEndpointAddress
            if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \
               endpoint_direction(ep.bEndpointAddress) == ENDPOINT_IN:
               self.__bulkin = ep.bEndpointAddress

        assert len(intf.extra_descriptors) == 54
        assert intf.extra_descriptors[1] == 33

        if (intf.extra_descriptors[42] & 0x02):
            # Short APDU level exchange
            self.__use_APDU = True
        elif (intf.extra_descriptors[42] & 0x04):
            # Short and extended APDU level exchange
            self.__use_APDU = True
        elif (intf.extra_descriptors[42] & 0x01):
            # TPDU level exchange
            self.__use_APDU = False
        else:
            raise ValueError("Unknown exchange level")

        # Check other bits???
        #       intf.extra_descriptors[40]
        #       intf.extra_descriptors[41]

        self.__dev = dev
        self.__timeout = 10000
        self.__seq = 0
示例#14
0
def connect(device):
    """
    Gets control over the USB lights device.
    """
    try:
        claim_interface(device, 0)
    except USBError:
        logger.debug('Failed to claim interface, trying harder...')
        try:
            device.detach_kernel_driver(0)
        except USBError:
            logger.debug('Cannot detach (already attached?), trying harder...')
        try:
            device.set_configuration()
        except USBError:
            logger.debug('Setting configuration failed, trying harder...')
            device.attach_kernel_driver(0)
            device.detach_kernel_driver(0)
            try:
                device.set_configuration()
            except USBError:
                logger.debug('Configuration set failed after (at/de)tach.')
                raise
示例#15
0
    def __getRawMeasures(self):
        logging.debug('USB Dev reset')
        dev = usb.core.find(idVendor=VID, idProduct=PID)
        if dev is None:
            logging.error('Please connect the device to the USB bus or check the vendor and product Id')
            sys.exit()

        if dev.is_kernel_driver_active(0):
            logging.debug('USB detach device from the OS')
            dev.detach_kernel_driver(0)
        try:
            logging.debug('USB set configuration')
            dev.set_configuration()
        except usb.core.USBError as e:
            logging.error('set_configuration exception %s', str(e))
            errno, strerror = e.args
            dev.reset()
        logging.debug('USB claim interface')
        util.claim_interface(dev, 0)
        # get an endpoint instance
        cfg = dev.get_active_configuration()
        intf = cfg[(0,0)]

        epOut = usb.util.find_descriptor(
            intf,
            # match the first OUT endpoint
            custom_match = \
            lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)

        assert epOut is not None
        logging.debug('USB first OUT endpoint is %s', str(epOut))

        epIn = usb.util.find_descriptor(
            intf,
            # match the first IN endpoint
            custom_match = \
            lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_IN)

        assert epIn is not None
        logging.debug('USB first IN endpoint is %s', str(epIn))

        logging.debug('USB Out (INIT_CMD): %s', INIT_CMD)
        epOut.write(INIT_CMD)
        while True:
            try:
                answer = dev.read(epIn.bEndpointAddress, \
                                  epIn.wMaxPacketSize, timeout=1000)
                logging.debug('USB In Init answer: %s', str(answer))
            except usb.core.USBError as e:
                answer = None
                logging.error('Exception %s', str(e))
                #errno, strerror = e.args
                #sys.stderr.write("I/O error({0}): {1}\n".format(errno,strerror))
                logging.error('Please push the "Start/Stop" button')
                dev.reset()
                usb.util.release_interface(dev, 0)
                dev.attach_kernel_driver(0)
                sys.exit()
            if len(answer) > 47:
                break

        getDataCmdTmpl = array('B', [0x02, 0x08, 0x01, 0x00, 0x02, 0xac, 0x28, 0x00, 0x8f ])
        addr = 0x02AC
        payload = array('B')
        for i in range(70):
            getDataCmdTmpl[4] = addr >> 8
            getDataCmdTmpl[5] = addr & 0xFF
            getDataCmdTmpl[8] = BloodpMonitor.buildCRC(getDataCmdTmpl)
            logging.debug('USB Out get data %d: %s', i, getDataCmdTmpl)
            epOut.write(getDataCmdTmpl)
            while True:
                try:
                    answer = dev.read(epIn.bEndpointAddress, \
                                      epIn.wMaxPacketSize, timeout=1000)
                    logging.debug("USB In (%d b): %s", len(answer), str(answer))
                except usb.core.USBError as e:
                    answer = None
                    logging.error('Exception' + str(e))
                    #if e.args == ('Operation timed out',):
                    dev.reset()
                    usb.util.release_interface(dev, 0)
                    dev.attach_kernel_driver(0)
                    sys.exit()
                    #break
                if len(answer) > 47:
                    payload.extend(answer[7:47])
                    break
                else :
                    raise ValueError('Partial read')
            addr += 40
        logging.debug('USB Out (DONE_CMD): %s', DONE_CMD)
        epOut.write(DONE_CMD)
        try:
            answer = dev.read(epIn.bEndpointAddress, \
                              epIn.wMaxPacketSize, timeout=1000)
            logging.debug("USB In Done answer: %s", str(answer))
        except usb.core.USBError as e:
            answer = None
            logging.error('Done answer Exception %s', str(e))

        # release the device
        logging.debug('USB Dev reset')
        dev.reset()
        logging.debug('USB release interface')
        usb.util.release_interface(dev, 0)
        # reattach the device to the OS kernel
        logging.debug('USB reattach the device to the OS kernel')
        dev.attach_kernel_driver(0)
        return payload
示例#16
0
# So, to workaround the problem I'm trying to save and restore the TLS state
# between the prototype invocation. This works fine with one exception. As soon as
# you close the last file descriptor associated with a USB device, the kernel automatically
# resets the device, effectively killing the established TLS state.
#
# This script helps to work around this last problem. It keeps an open descriptor which
# prevents kernel from resetting the device configuration. It does not interfere with
# the main process and does not hold the claim on the inface. It just sits there
# doing nothing until you decide to quit.
#
# The same can be achived by running something like "read 4</dev/bus/usb/001/011" from
# a command line, but in this case you need to figure out what is the current bus/device
# number yourself.

import usb.core
from usb.util import claim_interface, release_interface
from time import sleep

dev = usb.core.find(idVendor=0x138a, idProduct=0x0097)

# make sure we at least opened device descriptor
claim_interface(dev, 0)

sleep(0.2)

# release the iface, but keep the device open
release_interface(dev, 0)

# sit here, until the user press enter
raw_input()