Example #1
0
 def findDevice(self, idVendor, idProduct):
     """Find a USB device by product and vendor id."""
     for bus in usb.busses():
         for device in bus.devices:
             if device.idVendor == idVendor and device.idProduct == idProduct:
                 return device
     return None
Example #2
0
def hid_enumerate(vendor_id, product_id):

    hid_devices = []

    busses = list(usb.busses())

    # check each bus
    for b_index in range(0, len(busses)):
        bus = busses[b_index]
        devices = list(bus.devices)
        # check each device on a bus
        for d_index in range(0, len(devices)):
            device = devices[d_index]

            # If the device matches all criteria
            if device.deviceClass == USB_CLASS_PER_INTERFACE \
                and device.idVendor == vendor_id \
                and device.idProduct == product_id:

                for c in device.configurations:
                    for ilist in c.interfaces:
                        for interface in ilist:
                            if interface.interfaceClass == USB_CLASS_HID:
                                hid_devices.append(
                                    HIDDevice(device, b_index, d_index))

    return hid_devices
Example #3
0
    def devices(vendor_id=None, product_id=None):
        usb_devices = [d for b in usb.busses() for d in b.devices
                       if d.deviceClass == USB_CLASS_PER_INTERFACE
                       and d.idVendor == vendor_id
                       and d.idProduct == product_id]

        return [HIDDevice(u) for u in usb_devices]
Example #4
0
 def __init__(self):
     logger.info('Initializing GUSBamp instance')
     # list of available amps
     self.amps = []
     for bus in usb.busses():
         for device in bus.devices:
             if (device.idVendor == ID_VENDOR_GTEC and
                 device.idProduct == ID_PRODUCT_GUSB_AMP):
                 self.amps.append(device)
     self.devh = None
     self.mode = None
     # Initialize the amplifier and make it ready.
     device = self.amps[0]
     self.devh = device.open()
     # detach kernel driver if nessecairy
     config = device.configurations[0]
     self.devh.setConfiguration(config)
     assert(len(config.interfaces) > 0)
     first_interface = config.interfaces[0][1]
     first_setting = first_interface.alternateSetting
     self.devh.claimInterface(first_interface)
     self.devh.setAltInterface(first_interface)
     # initialization straight from the usb-dump
     self.set_mode('data')
     self.devh.controlMsg(CX_OUT, 0xb6, value=0x80, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xb5, value=0x80, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xb9, value=0x00, buffer="\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10")
     self.set_slave_mode(False)
     self.devh.controlMsg(CX_OUT, 0xd3, value=0x01, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xca, value=0x01, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xc8, value=0x01, buffer="\x00"*16)
     self.set_common_reference()
     self.set_common_ground()
     self.set_calibration_mode('sine')
     self.set_sampling_ferquency(128, [False for i in range(16)], None, None)
Example #5
0
    def __init__(self):
        super().__init__()

        buses = usb.busses()
        xula = None
        for bus in buses:
            for device in bus.devices:
                if(device.idVendor == 0x04d8 and device.idProduct == 0xff8c):
                    xula = device

        if(xula == None):
            return

        self.handle = xula.open()

        if(sys.platform != "win32"):
            try:
                self.handle.detachKernelDriver(0)
            except usb.USBError as error:
                print("detachKernelDriver exception {}".format(error))
                pass

        self.handle.claimInterface(0)

        self.ir = bitstring.BitStream('0b000000')
Example #6
0
 def get_device(self):
     for bus in usb.busses():
         for device in bus.devices:
             if (device.idVendor == self.VENDOR_ID and
                 device.idProduct in self.POSSIBLE_PRODUCTS):
                 return device
     raise NoBuddyFound
Example #7
0
 def _findDevice(self):
     """Find the vendor and product ID on the USB bus."""
     for bus in usb.busses():
         for dev in bus.devices:
             if dev.idVendor == self.vendor_id and dev.idProduct == self.product_id:
                 return dev
     return None
Example #8
0
	def __init__(self, flush=True):
		'''Finds and opens the scope's USB device.
		If flush==True, any pending data is discarded.'''
		
		self.device = None
		
		self.palette = [0] * 768
		# Build the default palette.
		# This is based on what the palette appears to be *intended* to be,
		# which is more colorful than the scope's actual display.
		for i in range(256):
			self.palette[i*3]   = i / 64 * 255 / 3
			self.palette[i*3+1] = (i & 0x30) / 16 * 255 / 3
			self.palette[i*3+2] = (i & 0x0c) / 4 * 255 / 3
		
		# Time in milliseconds to wait for a USB control transaction to finish.
		# *RST takes about 1500ms, so the timeout should be longer than that.
		self.timeout = 10000
		
		for bus in usb.busses():
			for dev in bus.devices:
				if dev.idVendor == 0x0400 and dev.idProduct == 0xc55d:
					self.device = dev.open()
					self.device.setConfiguration(1)
					self.device.claimInterface(0)
					break
		if not self.device:
			raise IOError('No USB oscilloscope found')
		if flush:
			self.read()
Example #9
0
def get_usb_device(vendor_id, device_id):
    buses = usb.busses()
    for bus in buses:
        for device in bus.devices:
            if device.idVendor == vendor_id and device.idProduct == device_id:
                return device
    return None
Example #10
0
 def __init__(self):
     self.dh = None
     footswitch = None
     self.iface = None
     self.location = None
     for bus in usb.busses():
         for dev in bus.devices:
             if dev.idVendor == VENDOR_ID and dev.idProduct == PRODUCT_ID:
                 footswitch = dev
                 self.location = (bus.dirname, dev.filename)
                 break
     if footswitch is None:
         raise BackendError("Device not found")
     for intf in footswitch.configurations[0].interfaces:
         if intf[0].interfaceNumber == INTERFACE_NUMBER:
             self.iface = intf
     self.dh = footswitch.open()
     # TODO: flaky after an ACPI suspend
     self.dh.reset()
     # This sometimes fails, and then errno doesn't get reset
     # so subsequent errors are still populated with this.
     try:
         self.dh.detachKernelDriver(self.iface[0])
     except usb.USBError as e:
         if 'Operation not permitted' in e.message:
             raise BackendError("Permission denied while removing kernel driver")
     self.dh.claimInterface(self.iface[0])
Example #11
0
def search_usb(device, vendor=None, product=None):
    busses = usb.busses()
    for bus in busses:
        dev = search_usb_bus(bus, device)
        if dev != None:
            return (bus, dev)
    return (None, None)
Example #12
0
def get_g9_device():
    for bus in usb.busses():
        for device in bus.devices:
            if device.idVendor == G9_VENDOR_ID \
                    and device.idProduct in G9_PRODUCT_IDS:
                return device.open()
    return None
	def enumTry(self):
		busses = usb.busses()
		for bus in busses:
			devices = bus.devices
			for dev in devices:
				print "Devices: ", dev.filename
				print " Device Class: ", dev.deviceClass
				print " Device Subclass: ", dev.deviceSubClass
				print " Device Protocol: ", dev.deviceProtocol
				print " Device max packet size: ", dev.maxPacketSize
				print " ID Vendor: ", dev.idVendor
				print " ID Product: ", dev.idProduct
				print " Device Version: ", dev.deviceVersion
				for config in dev.configurations:
					print "  Configuration: ", config.value
					print "   Total Length: ", config.totalLength
					print "   Self powered: ", config.selfPowered
					print "   Remote Wakeup: ", config.remoteWakeup
					print "   Max Power: ", config.maxPower
					for intf in config.interfaces:
						print "    Interface: ", intf[0].interfaceNumber
						for alt in intf:
							print "    Alternate Setting:",alt.alternateSetting
							print "      Interface class:",alt.interfaceClass
							print "      Interface sub class:",alt.interfaceSubClass
							print "      Interface protocol:",alt.interfaceProtocol
							for ep in alt.endpoints:
								print "      Endpoint:",hex(ep.address)
								print "        Type:",ep.type
								print "        Max packet size:",ep.maxPacketSize
								print "        Interval:",ep.interval
Example #14
0
    def __send_initalization(self):

        usbdev = None
        for bus in usb.busses():
            for dev in bus.devices:
                if dev.idVendor == 0x3333:
                    usbdev = dev
        if usbdev is None:
            raise IOError('Could not find laser device (3333:5555) ...')

        handle = usbdev.open()

        print 'Initializing device ... ',
        initlog = open(os.path.dirname(os.path.abspath(__file__))+'/usbinit.log')

        for line in initlog.readlines():
            setup_packet = line.split('|')[0]
            buf = line.split('|')[-1]
            if len(buf):
                values = setup_packet.strip().split(' ')
                reqType = int(values[0],16)
                req = int(values[1],16)
                value = int(values[2],16)*256+int(values[3],16)
                index = int(values[4],16)*256+int(values[5],16)
                length = int(values[6],16)*256+int(values[7],16)

                binbuf = ''
                for byte in buf.strip().split(' '):
                    binbuf += chr(int(byte,16))

                handle.controlMsg(reqType,req,binbuf,value,index)

        print 'done'
        time.sleep(1)
Example #15
0
def init(n=0): #opens the device, returns its deviceHandle
	import usb
	#global dh
	b=usb.busses()
	d=b[0].devices[n]
	print "DEVICE ",n,": PID:", d.idProduct ," VID: ",d.idVendor,", devnum: ",d.devnum
	dh=d.open()
	print "manuf:",dh.getString(d.iManufacturer,1000),", SN:",dh.getString(d.iSerialNumber,1000)
	c=d.configurations[0]
	try:
		print "config:",c.value,",",dh.getString(c.iConfiguration,1000)
	except:
		pass
	ifs=c.interfaces
	i=ifs[0][0]
	es=i.endpoints
	for e in es:
		if e.address>=128:
			ei=e.address
		else:
			eo=e.address
	dh.setConfiguration(c)
	global dhG
	try:
		dh.claimInterface(i)
		dhG=dh
	except usb.USBError:
		print "					INTERFACE WAS BUSY; RELEASING..."
		dhG.releaseInterface()
		#dh.releaseInterface()
		dh.claimInterface(i)
		dhG=dh
	return {"hnd":dh,"in":ei,"out":eo}
Example #16
0
 def is_available():
     for bus in usb.busses():
         for device in bus.devices:
             if (device.idVendor == ID_VENDOR_GTEC and
                 device.idProduct == ID_PRODUCT_GUSB_AMP):
                 return True
     return False
Example #17
0
 def __init__(self,skipNIAs):
     self.VENDOR_ID = 0x1234 #: Vendor Id
     self.PRODUCT_ID = 0x0000 #: Product Id for the bridged usb cable
     self.TIME_OUT = 100
     self.handle = None
     self.device = None
     buses = usb.busses()
     found = False
     for bus in buses :
         for device in bus.devices :
             if device.idVendor == self.VENDOR_ID and device.idProduct == self.PRODUCT_ID:
                 if skipNIAs ==0:
                     self.device = device 
                     self.config = self.device.configurations[0]
                     self.interface = self.config.interfaces[0][0]
                     self.ENDPOINT1 = self.interface.endpoints[0].address
                     self.ENDPOINT2 = self.interface.endpoints[1].address
                     self.PACKET_LENGTH1 = self.interface.endpoints[0].maxPacketSize
                     self.PACKET_LENGTH2 = self.interface.endpoints[1].maxPacketSize
                     found = True
                     break
                 else:
                     skipNIAs -= 1
         if found:
             break
Example #18
0
def enumerate_usb():
    """Return a generator yielding all attached USB devices."""
    busses = usb.busses()
    for bus in busses:
        devices = bus.devices
        for dev in devices:
            yield dev
Example #19
0
def find_sixaxes():
  res = []
  for bus in usb.busses():
    for dev in bus.devices:
      if dev.idVendor == vendor and dev.idProduct == product:
        res.append(dev)
  return res
 def autodetect(self, core):
   try:
     import usb
     found = False
     try:
       for bus in usb.busses():
         for dev in bus.devices:
           if dev.idVendor == 0x0403 and dev.idProduct == 0x6001:
             try:
               handle = dev.open()
               manufacturer = handle.getString(dev.iManufacturer, 100).decode("latin1")
               product = handle.getString(dev.iProduct, 100).decode("latin1")
               serial = handle.getString(dev.iSerialNumber, 100).decode("latin1")
               if (manufacturer == "FTDI" and product == "FT232R USB UART") or (manufacturer == "FPGA Mining LLC" and product == "X6500 FPGA Miner") or (manufacturer == "BTCFPGA" and product == "ModMiner"):
                 try:
                   configuration = dev.configurations[0]
                   interface = configuration.interfaces[0][0]
                   handle.setConfiguration(configuration.value)
                   handle.claimInterface(interface.interfaceNumber)
                   handle.releaseInterface()
                   handle.setConfiguration(0)
                   found = True
                   break
                 except: pass
             except: pass
         if found: break
     except: pass
     if found: core.add_worker(self(core))
   except: pass
 def autodetect(self, core):
   try:
     found = False
     try:
       import usb
       for bus in usb.busses():
         for dev in bus.devices:
           if dev.idVendor == 0x221a and dev.idProduct >= 0x100 and dev.idProduct <= 0x1ff:
             try:
               handle = dev.open()
               serial = handle.getString(dev.iSerialNumber, 100).decode("latin1")
               try:
                 configuration = dev.configurations[0]
                 interface = configuration.interfaces[0][0]
                 handle.setConfiguration(configuration.value)
                 handle.claimInterface(interface.interfaceNumber)
                 handle.releaseInterface()
                 handle.setConfiguration(0)
                 found = True
                 break
               except: pass
             except: pass
         if found: break
     except: pass
     if found: core.add_worker(self(core))
   except: pass
Example #22
0
	def findDevice(self, vendor_id, product_id):
		buses = usb.busses()
		for bus in buses :
			for device in bus.devices :
				if device.idVendor == vendor_id and device.idProduct == product_id:
					return device
		return None
Example #23
0
def find_usb_devices():
    busses = usb.busses()

    devobjs = []
    for dev in usb.core.find(find_all=True):
        serialno = None
        if dev.iSerialNumber > 0:
            try:
                serialno = dev.serial_number
            except usb.USBError:
                pass
            except ValueError:
                pass

        did = None
        try:
            did = '%04x' % dev.bcdDevice
        except TypeError:
            pass

        devobjs.append(
            LibDevice(
                vid=dev.idVendor,
                pid=dev.idProduct,
                did=did,
                serialno=serialno,
                path=Path(
                    bus=dev.bus,
                    address=dev.address)))
    return devobjs
Example #24
0
def find_bricks(host=None, name=None):
	# FIXME: probably should check host and name
	for bus in usb.busses():
		for device in bus.devices:
			if device.idVendor == ID_VENDOR_LEGO and \
			   device.idProduct == ID_PRODUCT_NXT:
				yield USBSock(device)
Example #25
0
def search_usb(device):
    '''
    Takes either None, specifying that any USB device in the
    global vendor and product lists are acceptable, or takes
    a string that identifies a device in the format
    <BusNumber>:<DeviceNumber>, and returns the pyUSB objects
    for bus and device that correspond to the identifier string.
    '''
    if device == None:
        busNum = None
        devNum = None
    else:
        if ':' not in device:
            raise KBInterfaceError("USB device format expects <BusNumber>:<DeviceNumber>, but got {0} instead.".format(device))
        busNum, devNum = map(int, device.split(':', 1))
    if USBVER == 0:
        busses = usb.busses()
        for bus in busses:
            dev = search_usb_bus_v0x(bus, busNum, devNum)
            if dev != None:
                return (bus, dev)
        return None #Note, can't expect a tuple returned
    elif USBVER == 1:
        return usb.core.find(custom_match=findFromListAndBusDevId(busNum, devNum, usbVendorList, usbProductList)) #backend=backend, 
    else:
        raise Exception("USB version expected to be 0.x or 1.x.")
Example #26
0
 def get_device(self) :
     buses = usb.busses()
     for bus in buses :
         for device in bus.devices :
             if device.idVendor == self.idVendor and device.idProduct == self.idProduct :
                     return device
     return None
def find_keyboard_device():
    for bus in usb.busses():
        for device in bus.devices:
	    print device
            if device.idVendor == USB_VENDOR and \
               device.idProduct == USB_PRODUCT or device.idProduct == USB_OTHER_PRODUCT:
                return device
Example #28
0
 def _find_device(idVendor, idProduct):
     for bus in usb.busses():
         for dev in bus.devices:
             if dev.idVendor == idVendor and \
                     dev.idProduct == idProduct:
                 return dev
     return None
Example #29
0
	def JobTask(self):
		LinkState = 0
		if fileExists('/sys/class/net/wlan0/operstate'):
			LinkState = open('/sys/class/net/wlan0/operstate').read()
			if LinkState != 'down':
				LinkState = open('/sys/class/net/wlan0/operstate').read()
		elif fileExists('/sys/class/net/eth0/operstate'):
			LinkState = open('/sys/class/net/eth0/operstate').read()
			if LinkState != 'down':
				LinkState = open('/sys/class/net/eth0/carrier').read()
		LinkState = LinkState[:1]
		if fileExists("/proc/stb/lcd/symbol_network") and config.lcd.mode.value == '1':
			open("/proc/stb/lcd/symbol_network", "w").write(str(LinkState))
		elif fileExists("/proc/stb/lcd/symbol_network") and config.lcd.mode.value == '0':
			open("/proc/stb/lcd/symbol_network", "w").write('0')

		USBState = 0
		busses = usb.busses()
		for bus in busses:
			devices = bus.devices
			for dev in devices:
				if dev.deviceClass != 9 and dev.deviceClass != 2 and dev.idVendor > 0:
# 						print ' '
# 						print "Device:", dev.filename
# 						print "  Number:", dev.deviceClass
# 						print "  idVendor: %d (0x%04x)" % (dev.idVendor, dev.idVendor)
# 						print "  idProduct: %d (0x%04x)" % (dev.idProduct, dev.idProduct)
					USBState = 1
		if fileExists("/proc/stb/lcd/symbol_usb") and config.lcd.mode.value == '1':
			open("/proc/stb/lcd/symbol_usb", "w").write(str(USBState))
		elif fileExists("/proc/stb/lcd/symbol_usb") and config.lcd.mode.value == '0':
			open("/proc/stb/lcd/symbol_usb", "w").write('0')

		self.timer.startLongTimer(30)
def find_device(vendor, product):
    for bus in usb.busses():
        for device in bus.devices:
            if device.idVendor == vendor \
                    and device.idProduct == product:
                        return device
    return None
Example #31
0
 def __init__(self, deviceid, takeover):
   import usb
   self.handle = None
   self.serial = deviceid
   permissionproblem = False
   deviceinuse = False
   for bus in usb.busses():
     if self.handle != None: break
     for dev in bus.devices:
       if self.handle != None: break
       if dev.idVendor == 0x0403 and dev.idProduct == 0x6001:
         try:
           handle = dev.open()
           manufacturer = handle.getString(dev.iManufacturer, 100).decode("latin1")
           product = handle.getString(dev.iProduct, 100).decode("latin1")
           serial = handle.getString(dev.iSerialNumber, 100).decode("latin1")
           if (manufacturer == "FTDI" and product == "FT232R USB UART") or product == "X6500 FPGA Miner" or product == "X6500r3 FPGA Miner" or (manufacturer == "FTDI" and product == "TTL232RG-VIP"):
             if deviceid == "" or deviceid == serial:
               try:
                 if takeover: handle.reset()
                 configuration = dev.configurations[0]
                 interface = configuration.interfaces[0][0]
                 handle.setConfiguration(configuration.value)
                 handle.claimInterface(interface.interfaceNumber)
                 handle.setAltInterface(interface.alternateSetting)
                 self.inep = interface.endpoints[0].address
                 self.inepsize = interface.endpoints[0].maxPacketSize
                 self.outep = interface.endpoints[1].address
                 self.outepsize = interface.endpoints[1].maxPacketSize
                 self.index = 1
                 self.handle = handle
                 self.serial = serial
               except: deviceinuse = True
         except: permissionproblem = True
   if self.handle == None:
     if deviceinuse:
       raise Exception("Can not open the specified device, possibly because it is already in use")
     if permissionproblem:
       raise Exception("Can not open the specified device, possibly due to insufficient permissions")
     raise Exception("Can not open the specified device")
   self.handle.controlMsg(0x40, 3, None, 0, 0)
Example #32
0
    def JobTask(self):
        LinkState = 0
        if fileExists('/sys/class/net/wlan0/operstate'):
            LinkState = open('/sys/class/net/wlan0/operstate').read()
            if LinkState != 'down':
                LinkState = open('/sys/class/net/wlan0/operstate').read()
        elif fileExists('/sys/class/net/eth0/operstate'):
            LinkState = open('/sys/class/net/eth0/operstate').read()
            if LinkState != 'down':
                LinkState = open('/sys/class/net/eth0/carrier').read()
        LinkState = LinkState[:1]
        if fileExists("/proc/stb/lcd/symbol_network"
                      ) and config.lcd.mode.value == '1':
            f = open("/proc/stb/lcd/symbol_network", "w")
            f.write(str(LinkState))
            f.close()
        elif fileExists("/proc/stb/lcd/symbol_network"
                        ) and config.lcd.mode.value == '0':
            f = open("/proc/stb/lcd/symbol_network", "w")
            f.write('0')
            f.close()

        USBState = 0
        busses = usb.busses()
        for bus in busses:
            devices = bus.devices
            for dev in devices:
                if dev.deviceClass != 9 and dev.deviceClass != 2 and dev.idVendor > 0:
                    USBState = 1
        if fileExists(
                "/proc/stb/lcd/symbol_usb") and config.lcd.mode.value == '1':
            f = open("/proc/stb/lcd/symbol_usb", "w")
            f.write(str(USBState))
            f.close()
        elif fileExists(
                "/proc/stb/lcd/symbol_usb") and config.lcd.mode.value == '0':
            f = open("/proc/stb/lcd/symbol_usb", "w")
            f.write('0')
            f.close()

        self.timer.startLongTimer(30)
Example #33
0
    def __init__(self, Frames):
        self._Init = False
        self._Running = False
        self._Frames = Frames
        self._DataAvaliable = False

        self._busses = usb.busses()
        self._rdev = None
        self._observers = []
        for bus in self._busses:
            for dev in bus.devices:
                if dev.idVendor == 0x2c51:
                    self._rdev = dev
            if self._rdev == None:
                print "Archo not find !"
                sys.exit()
            else:
                self._dev = self._rdev
                self._Init = True
                self._current_handle = self._dev.open()
                self._dev.dev.read(0x86, 512 * 3, 0, 2000)
Example #34
0
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):
            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
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)
        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 #36
0
    def __init__(self, num=0):
        """ Num is the device number on the system (0,1,2...) """
        cnt = 0

        busses = usb.busses()
        for bus in busses:
            for device in bus.devices:
                if device.idVendor==VENDOR_ID \
                  and device.idProduct in [PRODUCT_ID_SISPM,
                  PRODUCT_ID_MSISPM_OLD,PRODUCT_ID_MSISPM_FLASH,
                  PRODUCT_ID_MSISPM_FLASH_NEW]:

                    if num == cnt:
                        self.device = device
                        self.deviceHandle = self.device.open()
                        return

                    else:
                        cnt += 1

        raise SispmException("Sispm device not found.")
Example #37
0
	def JobTask(self):
		LinkState = 0
		if fileExists("/proc/stb/lcd/symbol_network") and config.lcd.mode.value == '1':
			print("[Lcd] Write to /proc/stb/lcd/symbol_network")
			open("/proc/stb/lcd/symbol_network", "w").write(str(LinkState))
		elif fileExists("/proc/stb/lcd/symbol_network") and config.lcd.mode.value == '0':
			print("[Lcd] Write to /proc/stb/lcd/symbol_network")
			open("/proc/stb/lcd/symbol_network", "w").write("0")

		USBState = 0
		busses = usb.busses()
		for bus in busses:
			devices = bus.devices
			for dev in devices:
				if dev.deviceClass != 9 and dev.deviceClass != 2 and dev.idVendor != 3034 and dev.idVendor > 0:
					USBState = 1
		if fileExists("/proc/stb/lcd/symbol_usb"):
			print("[Lcd] Write to /proc/stb/lcd/symbol_usb")
			open("/proc/stb/lcd/symbol_usb", "w").write(str(USBState))

		self.timer.startLongTimer(30)
Example #38
0
    def conexion(self):
        if self.servidor.emular == True:
            return True
        pingu = False
        try:
            busses = usb.busses()
            for bus in busses:
                devices = bus.devices
                for dev in devices:
                    if dev.idVendor == 0x04d8 and dev.idProduct == 0xfeaa:
                        pingu = dev
            if pingu <> False:
                self.dh = pingu.open()
                self.dh.setConfiguration(3)
                self.dh.claimInterface(0)
                return True
            else:
                return False

        except Exception, ex:
            return False
Example #39
0
def getRfCatDevices():
    '''
    returns a list of USB device objects for any rfcats that are plugged in
    NOTE: if any rfcats are in bootloader mode, this will cause python to Exit
    '''
    rfcats = []
    for bus in usb.busses():
        for dev in bus.devices:
            # OpenMoko assigned or Legacy TI
            if (dev.idVendor == 0x0451 and dev.idProduct == 0x4715) or (
                    dev.idVendor == 0x1d50 and
                (dev.idProduct == 0x6047 or dev.idProduct == 0x6048
                 or dev.idProduct == 0x605b)):
                rfcats.append(dev)

            elif (dev.idVendor == 0x1d50
                  and (dev.idProduct == 0x6049 or dev.idProduct == 0x604a)):
                print "Already in Bootloader Mode... exiting"
                exit(0)

    return rfcats
Example #40
0
    def setup_serial(self, port_name=None):
        self.usb_timestamp = 0
        matchcount = 0
        matchdev = None
        self.write_queue = Queue.Queue()
        self.read_queue = Queue.Queue()
        self.__keep_running = 1
        try:
            #scan busses and devices to find appropriately indexed device
            for bus in usb.busses():
                for dev in bus.devices:
                    if dev.idVendor == self.idVendor and dev.idProduct == self.idProduct:
                        matchcount += 1
                        matchdev = dev
                        if matchcount == self.device_index: break

                if matchcount == self.device_index: break
            if not matchdev or matchcount != self.device_index:
                raise IOError("no USB LabPro found with requested index %d" %
                              self.device_index)

            udev = self.usbdev = matchdev.open()
            udev.claimInterface(0)
            time.sleep(0.020)  # wait 20 ms for safety
            udev.setConfiguration(1)  #default configure interface
            time.sleep(0.020)  # wait 20 ms for safety
            udev.claimInterface(0)  #reclaim after configure

            self.read_thread = threading.Thread(target=self.reader_thread_task)
            self.read_thread.start()
            self.write_thread = threading.Thread(
                target=self.writer_thread_task)
            self.write_thread.start()
        except IOError:
            raise
        except:
            self.__keep_running = 0
            self.close()
            raise
Example #41
0
def usb_find(vendor, product, serialname):
  """Find USB devices based on vendor, product and serial identifiers.

  Locates all USB devices that match the criteria of the arguments.  In the
  case where input arguments are 'None' that argument is a don't care

  Args:
    vendor: USB vendor id (integer)
    product: USB product id (integer)
    serial: USB serial id (string)

  Returns:
    matched_devices : list of pyusb devices matching input args
  """
  matched_devices = []
  for bus in usb.busses():
    for device in bus.devices:
      if (not vendor or device.idVendor == vendor) and \
            (not product or device.idProduct == product) and \
            (not serialname or usb_get_iserial(device).endswith(serialname)):
        matched_devices.append(device)
  return matched_devices
Example #42
0
    def find_serial(self):
        """ On linux only, use pyusb to enumerate all devices connected
        to the bus, return the string from the usb descriptor, which is
        the device serial number.
        """
        import platform
        if platform.system() != "Linux":
            return self.find_windows_serial()

        print "Finding serial number using pyusb"
        import usb
        for bus in usb.busses():
            devices = bus.devices
            for dev in devices:
                if dev.idVendor == 0x06c2:
                    print "  idVendor:",hex(dev.idVendor)
                    print "  idProduct:",hex(dev.idProduct)
                    ld = dev.open()
                    local_serial = ld.getString(dev.iSerialNumber, 256)
                    return local_serial

        raise ValueError("Can't find phidget (linux)")
Example #43
0
def get_devices():
    fail = False
    devs = []
    for bus in usb.busses():
        for dev in bus.devices:
            try:
                dh = dev.open()
            except usb.USBError:
                fail = True
                continue

            if fail is not True:
                ven = getstr(dh, dev.iManufacturer)
                mdl = getstr(dh, dev.iProduct)
                ser = getstr(dh, dev.iSerialNumber)

            if ven is None or mdl is None or ser is None:
                fail = True
                continue

            txt = []
            if ven:
                txt.append(ven)
            txt.append(mdl or '<unknown>')
            if ser:
                txt.append('(S/N %s)' % ser)
            txt = ' '.join(txt)

            if not filter_dev(dev, dh, ven, mdl, ser):
                continue

            for config in dev.configurations:
                for intf in config.interfaces:
                    for alt in intf:
                        name = getstr(dh, alt.iInterface)
                        if not filter_interface(dev, dh, alt, name):
                            continue
                        devs.append((txt, (dev, alt)))
    return fail, devs
    def get_connected_device_types():
        board_types = []
        generic_count = 0

        busses = usb.busses()
        for bus in busses:
            devices = bus.devices

            for device in devices:
                found_same_pid = False

                for board_type, id_pairs in board_ids.boards.items():
                    for id_pair in id_pairs:
                        if device.idVendor == id_pair.vid:
                            if device.idProduct == id_pair.pid:
                                if board_type not in configuration.excluded_devices:
                                    board_types.append(board_type)
                                found_same_pid = True
                                break

                    if found_same_pid:
                        break

                if not found_same_pid:
                    if device.idVendor == board_ids.ftdi:
                        generic_count += 1
                        break

        # Put generic devices at the end so that the number of checks needed to find actual device is much less
        for i in range(generic_count):
            board_types.append('generic')

        if generic_count > 0:
            logger.warning(
                'An Arduino board was found but the board type is unknown. An attempt to find the type of'
                'board will be made but this could take quite awhile. It is recommended that you specify'
                'the board instead.')

        return board_types
Example #45
0
 def __init__(self, ibus=0, idev=0):
     if ibus and idev:
         print "Using explicitly defined device"
         raise NameError, "Not implemented."
     ndev = 0
     ibus = 0
     # find device
     for bus in usb.busses():
         ibus += 1
         idev = 0
         for dev in bus.devices:
             idev += 1
             if dev.idVendor == self.idVendor and dev.idProduct == self.idProduct:
                 devh = dev.open()
                 if devh.getString(dev.iManufacturer, len(self.Manufacturer)) == self.Manufacturer \
                 and  devh.getString(dev.iProduct, len(self.Product)) == self.Product:
                     if not self.mydevh: self.mydevh = devh
                     print "Device found. Bus %3d Device %3d" % (ibus,
                                                                 idev),
                     if ndev: print ""
                     else: print "*"
                     ndev += 1
Example #46
0
def find(find_all=False, idVendor=None, idProduct=None):
    all = []
    for bus in usb.busses():
        for dev in bus.devices:
            d = UsbDeviceMini(dev, bus)
            # print "seen idVendor=%04x idProduct=%04x" % (d.idVendor, d.idProduct)
            if idVendor is None and idProduct is None:
                all.append(d)
            elif idVendor is None:
                if idProduct == d.idProduct:
                    all.append(d)
            elif idProduct is None:
                if idVendor == d.idVendor:
                    all.append(d)
            else:
                if idVendor == d.idVendor and idProduct == d.idProduct:
                    all.append(d)
    if find_all:
        return all
    if not len(all):
        return None
    return all[0]
Example #47
0
 def connect(self):
     buses = usb.busses()
     segway_handle_list = []
     for bus in buses:
         for device in bus.devices:
             if device.idVendor == 1027 and device.idProduct == 59177:
                 h = device.open()
                 serial_num = int(h.getString(3, 10))
                 if serial_num == 215:
                     if self.side == 'front':
                         print 'Connected to front segway'
                         self.segway = h
                         self.segway.claimInterface(0)
                 elif serial_num == 201:
                     if self.side == 'back':
                         print 'Connected to rear segway'
                         self.segway = h
                         self.segway.claimInterface(0)
                 else:
                     raise RuntimeError(
                         'Unknown_segway connected.' + ' Serial Number is ',
                         serial_num)
Example #48
0
 def connect(self):
     '''
     connect usb device
     '''
     try:
         self.dev = usb.core.find(idVendor=self._vid, idProduct=self._pid)
         if self.dev:
             self.ep_in = self.dev[0][(0,0)][0].bEndpointAddress
             self.ep_out = self.dev[0][(0,0)][1].bEndpointAddress
             self.size = self.dev[0][(0,0)][1].wMaxPacketSize
         busses = usb.busses()
         for bus in busses:
             for device in bus.devices:
                 if device.idVendor == self._vid and device.idProduct == self._pid:
                     self._handle = device.open()
                     if self.dev.is_kernel_driver_active(0):
                         self._handle.detachKernelDriver(0)
                     self._handle.claimInterface(0)
         return True
     except Exception as e:
         self._is_connected = False
         return False   
Example #49
0
    def initial_setup(self):
        #self.stdscr.addstr(0, 0, "Moodtick recorder..")
        #self.stdscr.addstr(2, 0, "Please remove all 'moodsticks', and hit any key..")
        #c = self.stdscr.getch()
        #self.stdscr.clear()
        #self.stdscr.refresh()

        busses = usb.busses()
        for bus in busses:
        	devices = bus.devices
            	for dev in devices:
            		self.seen.append(dev.idVendor + dev.idProduct)

        for color in self.moodsticks:
            devid = self._record(color)
            self.moodsticks[color] = devid
            self.seen.append(devid)
            if not os.path.isdir(color):
                os.mkdir(color)
            devid_path = os.path.join(color, ".devnum")
            with open(devid_path, 'w') as fh:
                fh.write(str(devid))
Example #50
0
    def JobTask(self):
        LinkState = 0
        if fileExists('/sys/class/net/wlan0/operstate'):
            LinkState = open('/sys/class/net/wlan0/operstate').read()
            if LinkState != 'down':
                LinkState = open('/sys/class/net/wlan0/operstate').read()
        elif fileExists('/sys/class/net/eth0/operstate'):
            LinkState = open('/sys/class/net/eth0/operstate').read()
            if LinkState != 'down':
                LinkState = open('/sys/class/net/eth0/carrier').read()
        LinkState = LinkState[:1]
        if fileExists("/proc/stb/lcd/symbol_network"
                      ) and config.lcd.mode.getValue() == '1':
            open("/proc/stb/lcd/symbol_network", "w").write(str(LinkState))
        elif fileExists("/proc/stb/lcd/symbol_network"
                        ) and config.lcd.mode.getValue() == '0':
            open("/proc/stb/lcd/symbol_network", "w").write('0')

        USBState = 0
        busses = usb.busses()
        for bus in busses:
            devices = bus.devices
            for dev in devices:
                if dev.deviceClass != 9 and dev.deviceClass != 2 and dev.idVendor > 0:
                    # 						print ' '
                    # 						print "Device:", dev.filename
                    # 						print "  Number:", dev.deviceClass
                    # 						print "  idVendor: %d (0x%04x)" % (dev.idVendor, dev.idVendor)
                    # 						print "  idProduct: %d (0x%04x)" % (dev.idProduct, dev.idProduct)
                    USBState = 1
        if fileExists("/proc/stb/lcd/symbol_usb") and config.lcd.mode.getValue(
        ) == '1':
            open("/proc/stb/lcd/symbol_usb", "w").write(str(USBState))
        elif fileExists("/proc/stb/lcd/symbol_usb"
                        ) and config.lcd.mode.getValue() == '0':
            open("/proc/stb/lcd/symbol_usb", "w").write('0')

        self.timer.startLongTimer(30)
Example #51
0
 def __init__(self):
     logger.info('Initializing GUSBamp instance')
     # list of available amps
     self.amps = []
     for bus in usb.busses():
         for device in bus.devices:
             if (device.idVendor in [ID_VENDOR_GTEC, ID_VENDOR_GTEC2] and
                 device.idProduct == ID_PRODUCT_GUSB_AMP):
                 self.amps.append(device)
     self.devh = None
     self.mode = None
     # Initialize the amplifier and make it ready.
     device = self.amps[0]
     self.devh = device.open()
     # detach kernel driver if nessecairy
     config = device.configurations[0]
     self.devh.setConfiguration(config)
     assert(len(config.interfaces) > 0)
     # sometimes it is the other one
     first_interface = config.interfaces[0][0]
     if first_interface is None:
         first_interface = config.interfaces[0][1]
     first_setting = first_interface.alternateSetting
     self.devh.claimInterface(first_interface)
     self.devh.setAltInterface(first_interface)
     # initialization straight from the usb-dump
     self.set_mode('data')
     self.devh.controlMsg(CX_OUT, 0xb6, value=0x80, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xb5, value=0x80, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xb9, value=0x00, buffer="\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10")
     self.set_slave_mode(False)
     self.devh.controlMsg(CX_OUT, 0xd3, value=0x01, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xca, value=0x01, buffer=0)
     self.devh.controlMsg(CX_OUT, 0xc8, value=0x01, buffer="\x00"*16)
     self.set_common_reference()
     self.set_common_ground()
     self.set_calibration_mode('sine')
     self.set_sampling_ferquency(128, [False for i in range(16)], None, None)
def getDevice(vendor, product):
# ----------------------------------------------------------------------
    """ search USB device and returns a DeviceHandle object """

    if PYUSB_USE_CORE:

        device = usb.core.find(idVendor=vendor, idProduct=product)
        #print(device)
        if device is None :
            return ERR_DEVICE_NOT_FOUND
        else :
            return device

    else:

        busses = usb.busses()
        for bus in busses:
            #print(bus)
            for device in bus.devices:
                #print(device)
                if (device.idVendor, device.idProduct) == (vendor, product):
                    return device
        return ERR_DEVICE_NOT_FOUND
Example #53
0
    def open(self, index=0):
        """ Given an index, opens the related ambx device. The index refers
        to the position of the device on the USB bus. Index 0 is default, 
        and will open the first device found.

        Returns True if open successful, False otherwise.
        """
        device_count = 0
        for bus in usb.busses():
            devices = bus.devices
            for dev in devices:
                if dev.idVendor == self.RAVESPIDER_VENDOR_ID and dev.idProduct == self.RAVESPIDER_PRODUCT_ID:
                    if device_count == index:
                        self.RaveSpiderDevice = dev
                        break
                    device_count += 1
        if self.RaveSpiderDevice is None:
            print "Returning!"
            return False
        self.RaveSpiderHandle = self.RaveSpiderDevice.open()
        self.RaveSpiderHandle.setConfiguration(1)
        self.RaveSpiderHandle.claimInterface(0)
        return True
Example #54
0
    def __init__(self):
        busses = usb.busses()
        for bus in busses:
            devices = bus.devices
            for dev in devices:
                if dev.idVendor is VENDOR_ID and dev.idProduct is PRODUCT_ID:
                    self.__dev = dev
                    self.__conf = dev.configurations[0]
                    self.__intf = dev.interfaces[0][0]
                    self.__endp = self.__intf.endpoints[0]

        if self.__dev is None:
            raise ValueError('Launcher not found')

        try:
            self.__handle = self.__dev.open()
            self.__handle.detachKernelDriver(0)
            self.__handle.setConfiguration(self.__conf)
            self.__handle.claimInterface(self.__intf)
            self.__handle.setAltInterface(self.__intf)
            self.__handle.reset()
        except:
            raise ValueError('Unable to initialize Launcher!')
Example #55
0
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 #56
0
    def getDevice(self, board):
        """ Scans connected USB devices until it finds a Pinguino board """

        logging.info("Looking for a Pinguino device ...")

        if self.PYUSB_USE_CORE:

            device = usb.core.find(idVendor=board.vendor,
                                   idProduct=board.product)
            if device is None:
                return self.ERR_DEVICE_NOT_FOUND
            else:
                return device

        else:

            busses = usb.busses()
            for bus in busses:
                for device in bus.devices:
                    if (device.idVendor, device.idProduct) == (board.vendor,
                                                               board.product):
                        return device
            return self.ERR_DEVICE_NOT_FOUND
Example #57
0
  def __init__(self, vendor_id, product_id, skip):
    busses = usb.busses()
    self.handle = None
    count = 0
    for bus in busses:
      devices = bus.devices
      for dev in devices:

        if dev.idVendor==vendor_id and dev.idProduct==product_id:
          if count==skip:
            log.info("ibuddy found! vend: %s   prod: %s",dev.idVendor, dev.idProduct)
            self.dev = dev
            
            self.conf = self.dev.configurations[0]
            self.intf = self.conf.interfaces[0][0]
            self.endpoints = []
            for endpoint in self.intf.endpoints:
              self.endpoints.append(endpoint)
              log.info("endpoint")
            return
          else:
            count=count+1
    raise NoBuddyException()
Example #58
0
    def __init__(self):
        self.is_initialized = False
        d = None
        busses = usb.busses()
        for bus in busses:
            devs = bus.devices
            for dev in devs:
                if dev.idVendor == 0x046d and dev.idProduct == 0xc21f:
                    d = dev
        #conf = d.configurations[0]
        #intf = conf.interfaces[0][0]
        if d is not None:
            self._dev = d.open()
            try:
                self._dev.detachKernelDriver(0)
            except usb.core.USBError:
                logging.warning(
                    "Gamepad: Error detaching kernel driver (usually no problem)"
                )
            except AttributeError:
                pass
            #handle.interruptWrite(0, 'W')
            self._dev.setConfiguration(1)
            self._dev.claimInterface(0)

            # This value has to be send to the gamepad, or it won't start working
            # value was determined by sniffing the usb traffic with wireshark
            # getting other gamepads to work might be a simple as changing this
            self._dev.interruptWrite(0x02, struct.pack('<BBB', 0x01, 0x03,
                                                       0x04))
            self.changed = False
            self._state = default_state
            self._old_state = default_state
            self.is_initialized = True
            logging.info("Gamepad initialized")
        else:
            RuntimeError("Could not initialize Gamepad")
Example #59
0
  def __init__(self):
    vendorid, productid = 0xffc, 2 # clavia, g2

    # find g2 usb device
    g2dev = None
    for bus in usb.busses():
      for device in bus.devices:
        if device.idVendor == vendorid and device.idProduct == productid:
          g2dev = device
    if not g2dev:
      raise Exception('No g2 device found')
    self.g2dev = g2dev

    # get 3 endpoints
    g2conf = g2dev.configurations[0]
    g2intf = g2conf.interfaces[0][0]
    g2eps = g2intf.endpoints
    self.g2iin  = g2eps[0].address
    self.g2bin  = g2eps[1].address
    self.g2bout = g2eps[2].address

    self.g2h = g2dev.open()
    self.g2h.setConfiguration(g2conf)
    self.g2h.reset()
Example #60
0
    def _get_usb_device(self, skip=0):
        """
        Get YubiKey USB device.

        Optionally allows you to skip n devices, to support multiple attached YubiKeys.
        """
        try:
            # PyUSB >= 1.0, this is a workaround for a problem with libusbx
            # on Windows.
            import usb.core
            import usb.legacy
            devices = [usb.legacy.Device(d) for d in usb.core.find(
                find_all=True, idVendor=YUBICO_VID)]
        except ImportError:
            # Using PyUsb < 1.0.
            import usb
            devices = [d for bus in usb.busses() for d in bus.devices]
        for device in devices:
            if device.idVendor == YUBICO_VID:
                if device.idProduct in PID.all(otp=True):
                    if skip == 0:
                        return device
                    skip -= 1
        return None