Exemplo n.º 1
0
 def setup_windows(self):
     """
     Setup for headset on the Windows platform. 
     """
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             is_emotiv = False
             if "Emotiv" in device.vendor_name:
                 is_emotiv = True
             if "Emotiv" in device.product_name:
                 is_emotiv = True
             if "EPOC" in device.product_name:
                 is_emotiv = True
             if "Brain Waves" in device.product_name:
                 is_emotiv = True
             if device.product_name == '00000000000':
                 is_emotiv = True
             if "EEG Signals" in device.product_name:
                 is_emotiv = True
             if is_emotiv:
                 devices.append(device)
         if len(devices) > 0:
             device = devices[1]
             device.open()
             self.serial_number = device.serial_number
             device.set_raw_data_handler(self.handler)
             crypto = gevent.spawn(self.setup_crypto, self.serial_number)
             console_updater = gevent.spawn(self.update_console)
             while self.running:
                 try:
                     gevent.sleep(DEVICE_POLL_INTERVAL)
                 except KeyboardInterrupt:
                     self.running = False
         else:
             print("Could not find device")
             print("-------------------------")
             for device in hid.find_all_hid_devices():
                 print(device.vendor_name)
                 print(device.product_name)
                 print(device.vendor_id)
                 print(device.product_id)
                 print(device.serial_number)
                 print("-------------------------")
             print(
                 "Please include this information if you open a new issue.")
     except Exception, ex:
         print(ex.message)
Exemplo n.º 2
0
    def __init__(self):
        super(WiiBBRuntime, self).__init__()

        self.all_hids = hid.find_all_hid_devices()
        self.index_option = 15  # check for device number with hidtesting script
        self.int_option = int(self.index_option)

        self.result_wii = {
            'data': [[]],
            'start_time': [[]],
            'ts': [],
            'frame': [[]]
        }
        self.record = False
        self.first = True
        self.setWindowTitle("Wii Balance Board")

        self.rec_button = QPushButton('Start Recording', self)
        self.save_button = QPushButton('Save', self)
        self.new_button = QPushButton('New File', self)
        self.save_path, _ = QFileDialog.getSaveFileName(self, 'Save Path')

        self.layout = QGridLayout()
        self.layout.addWidget(self.rec_button)
        self.layout.addWidget(self.save_button)
        self.layout.addWidget(self.new_button)
        self.setLayout(self.layout)

        self.timer = QTimer(self)
        # self.timer.timeout.connect(self.wiibb_run)
        self.timer.start(0)

        self.new_button.clicked.connect(self.new_file)
        self.save_button.clicked.connect(self.save_data)
        self.rec_button.clicked.connect(self.record_switch)
Exemplo n.º 3
0
    def __init__(self, button_pressed_func, device_unplugged):
        """
        Init Function
        :param button_pressed_func: function that will be called after get_btn_press is called
        :return:
        """
        self.cl = ControllerLinks()
        self.wait_for_button = False
        self.poll = False
        self.last_USB = None
        self.data_to_make_link = None

        # Hid device stuff
        self.devices = hid.find_all_hid_devices()
        self.device = None

        #return func to notify UI that a key has been captured
        self.BPF = button_pressed_func

        # Called if the device is unplugged
        self.device_unplugged = device_unplugged

        #launch thread to generate keys
        self.GenerateThread = threading.Thread(target=self.generate_key_events,name="Bob")
        self.StopThread = threading.Event()
        self.GenerateThread.start()
Exemplo n.º 4
0
 def setup_windows(self):
     """
     Setup for headset on the Windows platform.
     """
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             if device_is_emotiv(device, self.platform):
                 devices.append(device)
         if len(devices) == 0:
             print_hid_enumerate(system_platform, hid)
             sys.exit()
         device = devices[1]
         device.open()
         self.hid = device
         self.serial_number = device.serial_number
         print("Reader detected serial number: {serial_number}".format(
             serial_number=self.serial_number))
         device.set_raw_data_handler(self.data_handler)
     except Exception as ex:
         print("Emotiv WindowsSetupError ",
               sys.exc_info()[0],
               sys.exc_info()[1],
               sys.exc_info()[2], " : ", ex)
     finally:
         if self.hid is not None:
             self.hid.close()
Exemplo n.º 5
0
def get_available_devices():
    devices = []
    if WINDOWS:
        try:
            for device in hid.find_all_hid_devices():
                if device.product_name == 'Emotiv RAW DATA':
                    devices.append(device.device_path)
        finally:
            pass
    else:
        serials = {}
        for name in os.listdir("/sys/class/hidraw"):
            realInputPath = os.path.realpath("/sys/class/hidraw/" + name)
            path = '/'.join(realInputPath.split('/')[:-4])
            try:
                if os.path.isfile(path + "/manufacturer"):
                    with open(path + "/manufacturer", 'r') as f:
                        manufacturer = f.readline()
                    if "emotiv" in manufacturer.lower():
                        with open(path + "/serial", 'r') as f:
                            serial = f.readline().strip()
                            if serial not in serials:
                                serials[serial] = []
                            serials[serial].append(name)
            except IOError as e:
                print("Couldn't open file: %s" % e)

        for serial, names in serials.items():
            device_path = '/dev/'+names[1]
            devices.append(device_path)

    return devices
Exemplo n.º 6
0
    def getConnectedInterfaces(vid, pid):
        """
        returns all the connected devices which matches PyWinUSB.vid/PyWinUSB.pid.
        returns an array of PyWinUSB (Interface) objects
        """
        all_devices = hid.find_all_hid_devices()
        
        # find devices with good vid/pid
        all_mbed_devices = []
        for d in all_devices:
            if (d.vendor_id == vid) and (d.product_id == pid):
                all_mbed_devices.append(d)
                
        if not all_mbed_devices:
            logging.debug("No Mbed device connected")
            return
            
        boards = []
        for dev in all_mbed_devices:
            new_board = PyWinUSB()
            new_board.vendor_name = dev.vendor_name
            new_board.product_name = dev.product_name
            new_board.serial_number = dev.serial_number
            new_board.vid = dev.vendor_id
            new_board.pid = dev.product_id
            new_board.path = dev.device_path
            new_board.device = dev

            boards.append(new_board)
                
        return boards
def find_vec_usb_footpedal():
    all_hids = hid.find_all_hid_devices()
    for index, device in enumerate(all_hids):
        if (device.vendor_id == 0x05f3 and device.product_id == 0x00ff):
            print("Found VEC USB Footpedal")
            return all_hids[index]
    raise Exception("VEC USB Footpedal not found");
Exemplo n.º 8
0
    def getAllConnectedInterface(vid, pid):
        """
        returns all the connected devices which matches PyWinUSB.vid/PyWinUSB.pid.
        returns an array of PyWinUSB (Interface) objects
        """
        all_devices = hid.find_all_hid_devices()

        # find devices with good vid/pid
        all_mbed_devices = []
        for d in all_devices:
            if (d.vendor_id == vid) and (d.product_id == pid):
                all_mbed_devices.append(d)

        boards = []
        for dev in all_mbed_devices:
            try:
                dev.open(shared=False)
                report = dev.find_output_reports()
                if (len(report) == 1):
                    new_board = PyWinUSB()
                    new_board.report = report[0]
                    new_board.vendor_name = dev.vendor_name
                    new_board.product_name = dev.product_name
                    new_board.vid = dev.vendor_id
                    new_board.pid = dev.product_id
                    new_board.device = dev
                    new_board.device.set_raw_data_handler(new_board.rx_handler)

                    boards.append(new_board)
            except Exception as e:
                logging.error("Receiving Exception: %s", e)
                dev.close()

        return boards
Exemplo n.º 9
0
    def getAllConnectedInterface(board_id = None):
        """
        returns all the connected CMSIS-DAP devices
        """
        all_devices = hid.find_all_hid_devices()

        # find devices with good vid/pid
        all_mbed_devices = []
        for d in all_devices:
            if (d.product_name.find("CMSIS-DAP") >= 0):
                all_mbed_devices.append(d)

        boards = []
        for dev in all_mbed_devices:
            try:
                dev.open(shared=False)
                report = dev.find_output_reports()
                if (len(report) == 1):
                    new_board = PyWinUSB()
                    new_board.report = report[0]
                    new_board.vendor_name = dev.vendor_name
                    new_board.product_name = dev.product_name
                    new_board.serial_number = dev.serial_number
                    new_board.vid = dev.vendor_id
                    new_board.pid = dev.product_id
                    new_board.device = dev
                    new_board.device.set_raw_data_handler(new_board.rx_handler)

                    boards.append(new_board)
            except Exception as e:
                logging.error("Receiving Exception: %s", e)
                dev.close()

        return boards
Exemplo n.º 10
0
    def __init__(self):
        #TODO - should be more specific here - there are likely to be cases
        #where we have more than one HID device

        hid_dev = hid.find_all_hid_devices()

        sns = [h for h in hid_dev if (h.product_name == 'SpaceNavigator')]
        self.snav = sns[0]

        self.snav.open()

        self.x = 0
        self.y = 0
        self.z = 0
        self.rho = 0
        self.theta = 0
        self.phi = 0
        self.buttonState = 0

        self.WantPosNotification = []
        self.WantAngleNotification = []
        self.WantButtonNotification = []

        self.OnLeftButtonUp = []
        self.OnRightButtonUp = []

        self.snav.set_raw_data_handler(self._handleData)
Exemplo n.º 11
0
    def get_available_devices(cls):
        devices = OrderedDict()

        if WINDOWS:
            try:
                for device in hid.find_all_hid_devices():
                    print "device : ", device
                    if (device.product_name == 'Emotiv RAW DATA' or device.product_name == 'EPOC BCI'):
                        devices['Emotiv '+device.serial_number] = get_info(device)
            finally:
                pass

        else:
            serials = { }
            for name in os.listdir("/sys/class/hidraw"):
                realInputPath =  os.path.realpath("/sys/class/hidraw/" + name)
                path = '/'.join(realInputPath.split('/')[:-4])
                try:
                    with open(path + "/manufacturer", 'r') as f:
                        manufacturer = f.readline()
                    if "emotiv" in manufacturer.lower():
                        with open(path + "/serial", 'r') as f:
                            serial = f.readline().strip()
                            if serial not in serials:
                                serials[serial] = [ ]
                            serials[serial].append(name)
                except IOError as e:
                    print "Couldn't open file: %s" % e

            for serial, names in serials.items():
                device_path = '/dev/'+names[1]
                info = get_info(device_path)
                devices['Emotiv '+device_path] = info

        return devices
Exemplo n.º 12
0
        def enumerate(vid: int, pid: int) -> List[Interface]:
            """Returns all the connected devices which matches PyWinUSB.vid/PyWinUSB.pid.

            :param vid: USB Vendor ID
            :param pid: USB Product ID
            :return: List of interfaces found
            """
            targets: List[Interface] = []
            all_devices = hid.find_all_hid_devices()

            # find devices with good vid/pid
            for dev in all_devices:
                if (dev.vendor_id == vid) and (dev.product_id == pid):
                    try:
                        dev.open(shared=False)
                        report = dev.find_output_reports()

                        if report:
                            new_target = RawHid()
                            new_target.report = report
                            new_target.vendor_name = dev.vendor_name
                            new_target.product_name = dev.product_name
                            new_target.vid = dev.vendor_id
                            new_target.pid = dev.product_id
                            new_target.device = dev
                            new_target.device.set_raw_data_handler(
                                new_target.rx_handler)
                            targets.append(new_target)

                    except hid.HIDError as e:
                        logger.error(f"Receiving Exception: {str(e)}")
                    finally:
                        dev.close()

            return targets
Exemplo n.º 13
0
    def __init__(self, **kwds):
        """
        Define arrays for translating joystick events and find the joystick HID.
        """
        super().__init__(self, **kwds)
        self.buttons = [[1,24,0],  # 1
                        [2,40,0],  # 2
                        [3,72,0],  # 3
                        [4,136,0], # 4
                        [5,8,1],   # 5
                        [6,8,2],   # 6
                        [7,8,4],   # 7
                        [8,8,8],   # 8
                        [9,8,16],  # 9
                        [10,8,32]]  # 10
        self.down = False
        self.hats = [["up",0,0],
                     ["left",6,0],
                     ["right",2,0],
                     ["down",4,0]]

        # initialize connection to joystick
        all_hids = hid.find_all_hid_devices()
        self.jdev = False
        for device in all_hids:
            if (device.product_name == "Logitech Dual Action"):
                self.jdev = device

        if not self.jdev:
            print("Logitech Dual Action joystick not found.")
Exemplo n.º 14
0
 def select_HID(self):
     # simple test
     # browse devices...
     all_hids = hid.find_all_hid_devices()
     if all_hids:
         while True:
             print("Sélectionner l'appareil correspondant à : " +
                   self.name + "\n")
             for index, device in enumerate(all_hids):
                 device_name = unicode("{0.vendor_name} {0.product_name}" \
                         "(vID=0x{1:04x}, pID=0x{2:04x})"\
                         "".format(device, device.vendor_id, device.product_id))
                 print("{0} => {1}".format(index + 1, device_name))
             index_option = raw_input()
             if index_option.isdigit(
             ) and int(index_option) <= len(all_hids):
                 # invalid
                 break
         int_option = int(index_option)
         if int_option:
             self.device = all_hids[int_option - 1]
             device_name = unicode("{0.vendor_name} {0.product_name}" \
                         "(vID=0x{1:04x}, pID=0x{2:04x})"\
                         "".format(self.device, self.device.vendor_id, self.device.product_id))
             print("Vous avez assigné à %s l'appareil %s" %
                   (self.name, device_name))
     else:
         print("Pas de périphérique USB HID trouvé")
Exemplo n.º 15
0
 def setupWin(self):
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             if device.vendor_id != 0x21A1:
                 continue
             if device.product_name == 'Brain Waves':
                 devices.append(device)
                 device.open()
                 self.serialNum = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == 'EPOC BCI':
                 devices.append(device)
                 device.open()
                 self.serialNum = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == '00000000000':
                 devices.append(device)
                 device.open()
                 self.serialNum = device.serial_number
                 device.set_raw_data_handler(self.handler)
         gevent.spawn(self.setupCrypto, self.serialNum)
         gevent.spawn(self.updateStdout)
         while self._goOn:
             try:
                 gevent.sleep(0)
             except KeyboardInterrupt:
                 self._goOn = False
                 for device in devices:
                     device.close()
     finally:
         for device in devices:
             device.close()
Exemplo n.º 16
0
def find_vec_usb_footpedal():
    all_hids = hid.find_all_hid_devices()
    for index, device in enumerate(all_hids):
        if (device.vendor_id == 0x05f3 and device.product_id == 0x00ff):
            print("Found VEC USB Footpedal")
            return all_hids[index]
    raise Exception("VEC USB Footpedal not found")
Exemplo n.º 17
0
def main(fn=None):
	if fn == None:
		devices = []
		try:
			for device in hid.find_all_hid_devices():
				if device.vendor_id != 0x21A1:
					continue
				if device.product_name == 'Brain Waves':
					devices.append(device)
					device.open()
					device.set_raw_data_handler(sample_handler)
				elif device.product_name == 'EPOC BCI':
					print 'foo'
					devices.append(device)
					device.open()
					device.set_raw_data_handler(bci_handler)
			while True:#device.is_plugged() and count < 1000:
				time.sleep(0.1)
		finally:
			for device in devices:
				device.close()
	else:
		for line in file(fn, 'r').readlines():
			data = [0] + [int(x, 16) for x in line.strip().split(' ')]
			sample_handler(data)
Exemplo n.º 18
0
    def getAllConnectedInterface(vid, pid):
        """
        returns all the connected devices which matches PyWinUSB.vid/PyWinUSB.pid.
        returns an array of PyWinUSB (Interface) objects
        """
        all_devices = hid.find_all_hid_devices()

        # find devices with good vid/pid
        all_mbed_devices = []
        for d in all_devices:
            if (d.vendor_id == vid) and (d.product_id == pid):
                all_mbed_devices.append(d)

        boards = []
        for dev in all_mbed_devices:
            try:
                dev.open(shared=False)
                report = dev.find_output_reports()
                if len(report) == 1:
                    new_board = PyWinUSB()
                    new_board.report = report[0]
                    new_board.vendor_name = dev.vendor_name
                    new_board.product_name = dev.product_name
                    new_board.vid = dev.vendor_id
                    new_board.pid = dev.product_id
                    new_board.device = dev
                    new_board.device.set_raw_data_handler(new_board.rx_handler)

                    boards.append(new_board)
            except Exception as e:
                logging.error("Receiving Exception: %s", e)
                dev.close()

        return boards
Exemplo n.º 19
0
    def __init__(self):
        self.buttons = [
            [1, 24, 0],  # 1
            [2, 40, 0],  # 2
            [3, 72, 0],  # 3
            [4, 136, 0],  # 4
            [5, 8, 1],  # 5
            [6, 8, 2],  # 6
            [7, 8, 4],  # 7
            [8, 8, 8],  # 8
            [9, 8, 16],  # 9
            [10, 8, 32]
        ]  # 10
        self.down = False
        self.hats = [["up", 0, 0], ["left", 6, 0], ["right", 2, 0],
                     ["down", 4, 0]]

        # initialize connection to joystick
        all_hids = hid.find_all_hid_devices()
        self.jdev = False
        for device in all_hids:
            if (device.product_name == "Logitech Dual Action"):
                self.jdev = device

        if not self.jdev:
            print "Logitech Dual Action joystick not found."
Exemplo n.º 20
0
    def getAllConnectedInterface():
        """
        returns all the connected CMSIS-DAP devices
        """
        all_devices = hid.find_all_hid_devices()

        # find devices with good vid/pid
        all_mbed_devices = []
        for d in all_devices:
            if (d.product_name.find("MicArray") >= 0):
                all_mbed_devices.append(d)

        boards = []
        for dev in all_mbed_devices:
            try:
                dev.open(shared=False)
                report = dev.find_output_reports()
                if (len(report) == 1):
                    new_board = PyWinUSB()
                    new_board.report = report[0]
                    new_board.vendor_name = dev.vendor_name
                    new_board.product_name = dev.product_name
                    new_board.serial_number = dev.serial_number
                    new_board.vid = dev.vendor_id
                    new_board.pid = dev.product_id
                    new_board.device = dev
                    new_board.device.set_raw_data_handler(new_board.rx_handler)

                    boards.append(new_board)
            except Exception as e:
                logging.error("Receiving Exception: %s", e)
                dev.close()

        return boards
Exemplo n.º 21
0
 def setupWin(self):
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             if device.vendor_id != 0x21A1:
                 continue
             if device.product_name == 'Brain Waves':
                 devices.append(device)
                 device.open()
                 self.serialNum = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == 'EPOC BCI':
                 devices.append(device)
                 device.open()
                 self.serialNum = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == '00000000000':
                 devices.append(device)
                 device.open()
                 self.serialNum = device.serial_number
                 device.set_raw_data_handler(self.handler)
         gevent.spawn(self.setupCrypto, self.serialNum)
         gevent.spawn(self.updateStdout)
         while self._goOn:
             try:
                 gevent.sleep(0)
             except KeyboardInterrupt:
                 self._goOn = False
                 for device in devices:
                     device.close()
     finally:
         for device in devices:
             device.close()
Exemplo n.º 22
0
    def __init__(self):
        self.buttons = [[1,24,0],  # 1
                        [2,40,0],  # 2
                        [3,72,0],  # 3
                        [4,136,0], # 4
                        [5,8,1],   # 5
                        [6,8,2],   # 6
                        [7,8,4],   # 7
                        [8,8,8],   # 8
                        [9,8,16],  # 9
                        [10,8,32]]  # 10
        self.down = False
        self.hats = [["up",0,0],
                     ["left",6,0],
                     ["right",2,0],
                     ["down",4,0]]

        # initialize connection to joystick
        all_hids = hid.find_all_hid_devices()
        self.jdev = False
        for device in all_hids:
            if (device.product_name == "Logitech Dual Action"):
                self.jdev = device

        if not self.jdev:
            print "Logitech Dual Action joystick not found."
Exemplo n.º 23
0
    def __init__(self, **kwds):
        """
        Define arrays for translating joystick events and find the joystick HID.
        """
        super().__init__(self, **kwds)
        self.buttons = [
            [1, 24, 0],  # 1
            [2, 40, 0],  # 2
            [3, 72, 0],  # 3
            [4, 136, 0],  # 4
            [5, 8, 1],  # 5
            [6, 8, 2],  # 6
            [7, 8, 4],  # 7
            [8, 8, 8],  # 8
            [9, 8, 16],  # 9
            [10, 8, 32]
        ]  # 10
        self.down = False
        self.hats = [["up", 0, 0], ["left", 6, 0], ["right", 2, 0],
                     ["down", 4, 0]]

        # initialize connection to joystick
        all_hids = hid.find_all_hid_devices()
        self.jdev = False
        for device in all_hids:
            if (device.product_name == "Logitech Dual Action"):
                self.jdev = device

        if not self.jdev:
            print("Logitech Dual Action joystick not found.")
Exemplo n.º 24
0
 def setup_windows(self):
     """
     Setup for headset on the Windows platform. 
     """
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             is_emotiv = False
             if "Emotiv" in device.vendor_name:
                 is_emotiv = True
             if "Emotiv" in device.product_name:
                 is_emotiv = True
             if "EPOC" in device.product_name:
                 is_emotiv = True
             if "Brain Waves" in device.product_name:
                 is_emotiv = True
             if device.product_name == '00000000000':
                 is_emotiv = True
             if "EEG Signals" in device.product_name:
                 is_emotiv = True
             if is_emotiv:
                 devices.append(device)
         if len(devices) > 0:
             device = devices[1]
             device.open()
             self.serial_number = device.serial_number
             device.set_raw_data_handler(self.handler)
             crypto = gevent.spawn(self.setup_crypto, self.serial_number)
             console_updater = gevent.spawn(self.update_console)
             while self.running:
                 try:
                     gevent.sleep(DEVICE_POLL_INTERVAL)
                 except KeyboardInterrupt:
                     self.running = False
         else:
             print("Could not find device")
             print("-------------------------")
             for device in hid.find_all_hid_devices():
                 print(device.vendor_name)
                 print(device.product_name)
                 print(device.vendor_id)
                 print(device.product_id)
                 print(device.serial_number)
                 print("-------------------------")
             print("Please include this information if you open a new issue.")
     except Exception, ex:
         print(ex.message)
Exemplo n.º 25
0
def raw_test():

    GRAND_PIANO = 0
    CHURCH_ORGAN = 19
    global instrument
    instrument = GRAND_PIANO

    pygame.init()
    pygame.midi.init()
    global midi_out
    port = pygame.midi.get_default_output_id()
    print ("using output_id :%s:" % port)
    midi_out = pygame.midi.Output(port, 0)
    midi_out.set_instrument(instrument)

    # simple test
    # browse devices...
    all_hids = hid.find_all_hid_devices()

    if all_hids:
 #       while True:
        print("Choose a device to monitor raw input reports:\n")
        print("0 => Exit")
        for index, device in enumerate(all_hids):
             device_name = unicode("{0.vendor_name} {0.product_name}" \
                     "(vID=0x{1:04x}, pID=0x{2:04x})"\
                     "".format(device, device.vendor_id, device.product_id))
             print("{0} => {1}".format(index+1, device_name))
             if 'DJ' in device_name:
                 print "DETECTED DJ DECK"
                 index_option = index+1

#            print("\n\tDevice ('0' to '%d', '0' to exit?) " \
#                    "[press enter after number]:" % len(all_hids))
#            index_option = raw_input()
#            if index_option.isdigit() and int(index_option) <= len(all_hids):
                # invalid
#                break;
        int_option = int(index_option)

        global prevdata
        prevdata=[0,0,0,8,128,128,0,0,0,0,0,0,0,0,0,127,0,0,0,0,0,0,0,0,0,224,13,11];
        if int_option:
            device = all_hids[int_option-1]
            try:
                device.open()

                #set custom raw data handler
                device.set_raw_data_handler(sample_handler)

                print("\nWaiting for data...\nPress any (system keyboard) key to stop...")
                while device.is_plugged():
                    #just keep the device opened to receive events
                    sleep(600)
                return
            finally:
                device.close()
    else:
        print("There's not any non system HID class device available")
Exemplo n.º 26
0
def detect_device():
    all_hids = hid.find_all_hid_devices()
    pads = []
    for hids in all_hids:
        tmp = 1
        matchObj = re.match(r'HID\\VID_0B43&PID_0003', hids.instance_id, re.M)
        if matchObj:
            pads.append(hids)
    return pads
Exemplo n.º 27
0
def getHIDlist():
    hid_list=hid.find_all_hid_devices()
    if len(hid_list) == 0:
        print('NA')
        return
    for i in range(len(hid_list)):
        print("[FINDHID]{};VID:{},PID:{},vendor:{},product:{}".format(i,
        hex(hid_list[i].vendor_id),hex(hid_list[i].product_id),
        hid_list[i].vendor_name,hid_list[i].product_name))
Exemplo n.º 28
0
        def enumerate(vid=None, pid=None, path=None):
            """
            returns all the connected devices which matches PyWinUSB.vid/PyWinUSB.pid.
            returns an array of PyWinUSB (Interface) objects
            :param vid:
            :param pid:
            """
            all_devices = hid.find_all_hid_devices()

            # find devices with good vid/pid
            all_kboot_devices = []
            for d in all_devices:
                if d.vendor_id == vid and d.product_id == pid:
                    all_kboot_devices.append(d)
                elif path:  # serach by path, no need for vid, pid
                    all_kboot_devices.append(d)
                elif pid is None and d.vendor_id == vid:
                    all_kboot_devices.append(d)
                elif vid is None and d.product_id == pid:
                    all_kboot_devices.append(d)
            if not all_kboot_devices:
                logging.debug(
                    'No device connected(vid={}, pid={}), please check'
                    '"vid", "pid", "device_path"'.format(
                        vid or 'None', pid or 'None'))
                return all_kboot_devices

            targets = []
            for dev in all_kboot_devices:
                try:
                    dev.open(shared=False)
                    report = dev.find_output_reports()
                    dev.close()
                    # Specify additional path to search.
                    if path is not None and path != dev.device_path.split(
                            '#')[-2]:
                        continue
                    if report:
                        new_target = RawHID()
                        new_target.report = report
                        new_target.vendor_name = dev.vendor_name
                        new_target.product_name = dev.product_name
                        new_target.desc = dev.vendor_name[:-1]
                        new_target.vid = dev.vendor_id
                        new_target.pid = dev.product_id
                        new_target.path = dev.device_path.split(
                            '#'
                        )[-2]  # Actually the device id, which is basically equivalent to dev.instance_id
                        new_target.device = dev
                        new_target.device.set_raw_data_handler(
                            new_target.__rx_handler)
                        targets.append(new_target)
                except Exception as e:
                    logging.error("Receiving Exception: %s", e)
                    dev.close()

            return targets
Exemplo n.º 29
0
 def show_hids(self):
     all_hids = hid.find_all_hid_devices()
     if all_hids:
         self.logText.append( "Available HID devices:" )
         for hid_device in all_hids:
             self.logText.append( "  vId={0:04X}, pId= {1:04X}".format(
                 hid_device.vendor_id, hid_device.product_id ))
     else:
         self.logText.append( "No HID USB devices attached now" )
Exemplo n.º 30
0
def detect_device():
    all_hids = hid.find_all_hid_devices()
    pads = []
    for hids in all_hids:
        tmp = 1
        matchObj = re.match(r'HID\\VID_0B43&PID_0003', hids.instance_id, re.M)
        if matchObj:
            pads.append(hids)
    return pads
Exemplo n.º 31
0
 def __init__(self):        
     # initialize connection to joystick
     all_hids = hid.find_all_hid_devices()
     self.jdev = False
     for device in all_hids:
         if (device.product_name == "Logitech Dual Action"):
             self.jdev = device
             
     if not self.jdev:
         print "Gamepad 310 joystick not found."
Exemplo n.º 32
0
 def get_devices(self):
     """
     Called to get the usb devices on the machine
     :return: List of the HIDDevices
     """
     self.devices = hid.find_all_hid_devices()
     device_names = []
     for device in self.devices:
         device_names.append(device.product_name)
     return tuple(device_names)
Exemplo n.º 33
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        icon_path = resource_path("icon.ico")
        self.setWindowIcon(QIcon(icon_path))
        self.ui.messageBox = QMessageBox(self.ui.centralwidget)
        self.ui.messageBox.setWindowTitle(" ")
        self.all_hids = hid.find_all_hid_devices()
        self.current_index = 0

        # selects
        self.ui.deviceBox.activated.connect(self.select_device)

        # buttons
        self.ui.forwardButton.clicked.connect(self.add_result)
        self.ui.backwardButton.clicked.connect(self.remove_result)
        self.ui.leftMonitorSelect.clicked.connect(
            lambda: self.set_monitor("left"))
        self.ui.rightMonitorSelect.clicked.connect(
            lambda: self.set_monitor("right"))
        self.ui.lightThemeButton.clicked.connect(
            lambda: self.set_theme("light"))
        self.ui.darkThemeButton.clicked.connect(lambda: self.set_theme("dark"))
        self.ui.prideThemeButton.clicked.connect(
            lambda: self.set_theme("pride"))
        self.ui.saveButton.clicked.connect(self.save_data)
        self.ui.inputFileButton.clicked.connect(self.choose_input_file)
        self.ui.outputFileButton.clicked.connect(self.choose_output_file)
        self.ui.inputFileButton.setStyleSheet('text-align:left;padding:5px;')
        self.ui.outputFileButton.setStyleSheet('text-align:left;padding:5px;')
        self.ui.resetButton.clicked.connect(self.reset_values)
        self.ui.restoreButton.clicked.connect(self.restore_config)

        # inputs
        self.ui.leftLNumberInput.textEdited.connect(
            lambda: self.change_text(self.ui.leftLNumberInput))
        self.ui.rightLNumberInput.textEdited.connect(
            lambda: self.change_text(self.ui.rightLNumberInput))
        self.ui.leftLNumberInput.textEdited.connect(
            self.change_output_filename)
        self.ui.rightLNumberInput.textEdited.connect(
            self.change_output_filename)
        self.ui.leftTesterInput.textEdited.connect(
            lambda: self.change_text(self.ui.leftTesterInput))
        self.ui.rightTesterInput.textEdited.connect(
            lambda: self.change_text(self.ui.rightTesterInput))

        self.thread_pool = QThreadPool()
        self.worker = None
        self.repository = None
        self.device = None
        self.current_measurement = None
        self.raw_value = None
Exemplo n.º 34
0
    def find_all_devices(self):
        '''
        线程检测USB的连接状态
        '''
        try:
            self.temp_pyusb = list()
            if platform.system() == "Windows":
                usb_dev = hid.find_all_hid_devices()
                for dev in usb_dev:
                    vid = hex(dev.vendor_id)[2:].rjust(4, "0")
                    pid = self.fill_zero(hex(dev.product_id)[2:])
                    name = dev.product_name
                    dev_info = "VID:{0} PID:{1}".format(vid, pid)
                    dev_info = '{}'.format(name)
                    self.temp_pyusb.append(dev_info)
            else:
                usb_dev = usb.core.find(find_all=True)
                for dev in usb_dev:
                    vid = self.fill_zero(hex(dev.idVendor)[2:])
                    pid = self.fill_zero(hex(dev.idProduct)[2:])
                    name = dev.product_name
                    dev_info = "VID:{0} PID:{1}".format(vid, pid)
                    dev_info = '{}'.format(name)
                    self.temp_pyusb.append(dev_info)
            for item in self.temp_pyusb:
                if item not in self.list_box_pyusb:
                    self.frm_left_listbox.insert("end", item)
            for item in self.list_box_pyusb:
                if item not in self.temp_pyusb:
                    index = list(
                        self.frm_left_listbox.get(
                            0, self.frm_left_listbox.size())).index(item)
                    self.frm_left_listbox.delete(index)
            # 检测到usb设备被拔出时,关闭usb设备
            if self.pid and self.vid:
                _vid = self.fill_zero(hex(self.vid)[2:])
                _pid = self.fill_zero(hex(self.pid)[2:])
                _name = self.name
                dev_info = "VID:{0} PID:{1}".format(_vid, _pid)
                dev_info = '{}'.format(_name)
                if dev_info not in self.temp_pyusb:
                    self.Toggle()
                    self.vid = None
                    self.pid = None
                    self.name = None
            self.list_box_pyusb = self.temp_pyusb

            self.thread_find_all_devices = threading.Timer(
                1, self.find_all_devices)
            self.thread_find_all_devices.setDaemon(True)
            self.thread_find_all_devices.start()
        except Exception as e:
            logging.error(e)
Exemplo n.º 35
0
def open(callback=None, button_callback=None, device=None):
    """
    Open a 3D space navigator device. Makes this device the current active device, which enables the module-level read() and close()
    calls. For multiple devices, use the read() and close() calls on the returned object instead, and don't use the module-level calls.
    
    Parameters:        
        callback: If callback is provided, it is called on each HID update with a copy of the current state namedtuple  
        button_callback: If button_callback is provided, it is called on each button push, with the arguments (state_tuple, button_state) 
        device: name of device to open. Must be one of the values in supported_devices. If None, chooses the first supported device found.
    Returns:
        Device object if the device was opened successfully
        None if the device could not be opened
    """
    # only used if the module-level functions are used
    global _active_device

    # if no device name specified, look for any matching device and choose the first
    if device == None:
        all_devices = list_devices()
        if len(all_devices) > 0:
            device = all_devices[0]
        else:
            return None

    all_hids = hid.find_all_hid_devices()
    if all_hids:
        for index, dev in enumerate(all_hids):
            spec = device_specs[device]
            if dev.vendor_id == spec.hid_id[
                    0] and dev.product_id == spec.hid_id[1]:
                print("%s found" % device)
                # create a copy of the device specification
                new_device = copy.deepcopy(spec)
                new_device.device = dev
                # copy in product details
                new_device.product_name = dev.product_name
                new_device.vendor_name = dev.vendor_name
                new_device.version_number = dev.version_number
                # doesn't seem to work on 3dconnexion devices...
                new_device.serial_number = dev.serial_number
                # set the callbacks
                new_device.callback = callback
                new_device.button_callback = button_callback
                # open the device and set the data handler
                new_device.open()
                dev.set_raw_data_handler(lambda x: new_device.process(x))
                _active_device = new_device
                return new_device
        print("No supported devices found")
        return None
    else:
        print("No HID devices detected")
        return None
Exemplo n.º 36
0
def hid_devices():
    all_hids = hid.find_all_hid_devices()  # Get a list of HID objects
    # Convert to a dictionary of Names:Objects
    hids_dict = {}
    for device in all_hids:
        device_name = str(
                "{0.vendor_name} {0.product_name}"
                "(vID=0x{1:04x}, pID=0x{2:04x})"
                "".format(device, device.vendor_id, device.product_id)
        )
        hids_dict[device_name] = device
    return hids_dict
Exemplo n.º 37
0
def raw_test():

    # browse devices...
    all_hids = hid.find_all_hid_devices()
    if not all_hids:
        print("There's not any non system HID class device available")

    else:
        while True:
            print("Choose a device to monitor raw input reports:\n")
            print("0 => Exit")
            for index, device in enumerate(all_hids):
                device_name = unicode("{0.vendor_name} {0.product_name}" \
                        "(vID=0x{1:04x}, pID=0x{2:04x}, pVer={0.instance_id})"\
                        "".format(device, device.vendor_id, device.product_id, device))
                print("{0} => {1}".format(index+1, device_name))
            print("\n\tDevice ('0' to '%d', '0' to exit?) " \
                    "[press enter after number]:" % len(all_hids))
            index_option = raw_input()
            if index_option.isdigit() and int(index_option) <= len(all_hids):
                # invalid
                break
        int_option = int(index_option)
        if int_option:
            device = all_hids[int_option-1]
            try:
                device.open()

                #set custom raw data handler
                device.set_raw_data_handler(sample_handler)

                print("\nWaiting for data...\nPress any (system keyboard) key to stop...")
                while not kbhit() and device.is_plugged():
                    #just keep the device opened to receive events
                    for report in device.find_output_reports():
                        for target_usage in range(len(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(report)
                            sleep(1)


                    #sleep(1000)
                    pass
                return
            finally:
                device.close()
Exemplo n.º 38
0
    def __init__(self, verbose = False, **kwds):
        """
        Create the arrays for translating the joystick objects and try and
        find the joystick among the HID devices that are attached to the computer.
        """
        super().__init__(**kwds)
        
        # initialize internal variables
        self.buttons = [["A", False, 2], #[name, state bit]
                        ["B", False, 3],
                        ["X", False, 1],
                        ["Y", False, 4]]
        self.actions = [["left joystick press", False, 7], #[name, state, bit]
                        ["right joystick press", False, 8],
                        ["left upper trigger", False, 1],
                        ["right upper trigger", False, 2],
                        ["left lower trigger", False, 3],
                        ["right lower trigger", False, 4],
                        ["back", False, 5],
                        ["start", False, 6]]
        self.hats = [["up", False], #[name, state]
                     ["right",False],
                     ["down",False],
                     ["left",False]]
        self.hats_dictionary = {0: [True, False, False, False], 
                                1: [True, True, False, False],
                                2: [False, True, False, False],
                                3: [False, True, True, False],
                                4: [False, False, True, False],
                                5: [False, False, True, True],
                                6: [False, False, False, True],
                                7: [True, False, False, True],
                                8: [False, False, False, False]}
        self.joysticks = [["right joystick", [128, 128]], #[name, [state 1, state 2]]
                         ["left joystick", [128, 128]]]

        self.data = [0, 128, 127, 128, 127, 8, 0, 0, 255] #default data
        self.events_to_send = []
        self.verbose = verbose
        
        # initialize connection to joystick
        all_hids = hid.find_all_hid_devices()
        self.jdev = False
        if self.verbose:
            print("Searching for HID devices")
        for device in all_hids:
            if self.verbose:
                print(device.product_name)
            if (device.product_name == "Logitech Dual Action"):
                self.jdev = device
                
        if not self.jdev:
            print("Gamepad 310 joystick not found.")
Exemplo n.º 39
0
def list_devices():
    """Return a list of the supported devices connected  
    
    Returns:
        A list of string names of the devices supported which were found. Empty if no supported devices found
    """
    devices = []
    all_hids = hid.find_all_hid_devices()
    if all_hids:
        for index, device in enumerate(all_hids):
            for device_name,spec in device_specs.iteritems():
                if device.vendor_id == spec.hid_id[0] and device.product_id == spec.hid_id[1]:
                    devices.append(device_name)                        
    return devices
Exemplo n.º 40
0
def list_devices():
    """Return a list of the supported devices connected  
    
    Returns:
        A list of string names of the devices supported which were found. Empty if no supported devices found
    """
    devices = []
    all_hids = hid.find_all_hid_devices()
    if all_hids:
        for index, device in enumerate(all_hids):
            for device_name,spec in device_specs.iteritems():
                if device.vendor_id == spec.hid_id[0] and device.product_id == spec.hid_id[1]:
                    devices.append(device_name)                        
    return devices
Exemplo n.º 41
0
def raw_test():
    # simple test
    # browse devices...
    all_hids = hid.find_all_hid_devices()
    if all_hids:
        while True:
            print("Choose a device to monitor:\n")
            print("0 => Exit")
            for index, device in enumerate(all_hids):
                device_name = unicode("{0.vendor_name} {0.product_name}" \
                        "(vID=0x{1:04x}, pID=0x{2:04x})"\
                        "".format(device, device.vendor_id, device.product_id))
                vID = hex(device.vendor_id).split('x')[1]
                pID = hex(device.product_id).split('x')[1]
                try:
                    # Uncomment the next raw to print the list of defices
                    print("{0} => {1}".format(index+1, device_name))
                    if vID == hrmvendor_id and pID == hrmproduct_id:
                        found_option = index+1
                        found_device = device_name
                except:
                    print("Error parsing the name", device.vendor_id, device.product_id )
            print("\n\tDevice ('0' to '%d', '0' to exit?) " \
                    "[press enter after number]:" % len(all_hids))
            if found_option:
                #print("We have found the device")
                index_option = str(found_option)
            else:
                print("Didn't find the vendor and product id. Plug in the device or edit the script and write the correct values")
                index_option = raw_input()
            if index_option.isdigit() and int(index_option) <= len(all_hids):
                # invalid
                break;
        int_option = int(index_option)
        if int_option:
            device = all_hids[int_option-1]
            try:
                device.open()
                #set custom raw data handler
                device.set_raw_data_handler(hrm_handler)
                print("\nWaiting for data...\nPress any (system keyboard) key to stop...")
                while not kbhit() and device.is_plugged():
                    #just keep the device opened to receive events
                    sleep(0.5)
                return
            finally:
                device.close()
    else:
        print("There's not any non system HID class device available")
Exemplo n.º 42
0
def raw_test():

    print(hid.find_all_hid_devices())

    # device = (hid.HidDeviceFilter(vendor_id =vId , product_id = pId).get_devices())[0]
    # device.open()
    # #set custom raw data handler
    # device.set_raw_data_handler(sample_handler)
    # print("\nWaiting for data...\nPress any (system keyboard) key to stop...")
    # while not kbhit() and device.is_plugged():
    #     #just keep the device opened to receive events
    #     sleep(0.5)
    #
    # device.close()
    return
Exemplo n.º 43
0
    def start(self):
        '''
        开始,打开HID设备
        '''
        _filter = hid.HidDeviceFilter(vendor_id=self.vid, product_id=self.pid)
        print(hid.find_all_hid_devices())
        print(_filter)
        hid_device = _filter.get_devices()
        print(hid_device)
        if len(hid_device) > 0:
            self.device = hid_device[0]
            self.device.open()
            self.report = self.device.find_output_reports()

            self.alive = True
Exemplo n.º 44
0
 def __init__(self, **kwds):
     """
     Find the joystick in the list of HID devices.
     """
     super().__init__(self, **kwds)
     
     # initialize connection to joystick
     all_hids = hid.find_all_hid_devices()
     self.jdev = False
     for device in all_hids:
         if (device.product_name == "Logitech Dual Action"):
             self.jdev = device
             
     if not self.jdev:
         print("Gamepad 310 joystick not found.")
Exemplo n.º 45
0
 def __init__(self, **kwds):
     """
     Find the joystick in the list of HID devices.
     """
     super().__init__(self, **kwds)
     
     # initialize connection to joystick
     all_hids = hid.find_all_hid_devices()
     self.jdev = False
     for device in all_hids:
         if (device.product_name == "Logitech Dual Action"):
             self.jdev = device
             
     if not self.jdev:
         print("Gamepad 310 joystick not found.")
Exemplo n.º 46
0
def set_mute(mute_value):
    "Browse for mute usages and set value"
    all_mutes = (\
            (0x8, 0x9), # LED page
            (0x1, 0xA7), # desktop page
            (0xb, 0x2f),
    )
    all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]

    # usually you'll find and open the target device, here we'll browse for the
    # current connected devices
    all_devices = hid.find_all_hid_devices()

    success = 0
    if not all_devices:
        print("Can't any HID device!")
    else:
        # search for our target usage
        # target pageId, usageId
        for device in all_devices:
            try:
                device.open()
                # target 'to set' value could be in feature or output reports
                for report in device.find_output_reports(
                ) + device.find_feature_reports():
                    for target_usage in all_target_usages:
                        if target_usage in report:
                            # set our value and send
                            print("Found in report: {0}\n".format(report))

                            old_raw_data = report.get_raw_data()
                            print(
                                "  Empty raw report: {0}".format(old_raw_data))
                            report[target_usage] = value
                            new_raw_data = report.get_raw_data()
                            print(
                                "  Set raw report: {0}\n".format(new_raw_data))
                            # validate that set_raw_data() is working properly
                            report.set_raw_data(new_raw_data)
                            report.send()
                            success += 1
            finally:
                device.close()
    # fit to sys.exit() proper result values
    print("{0} Mute usage(s) set\n".format(success))
    if success:
        return 0
    return -1
Exemplo n.º 47
0
def start_paddle(_mount):
    # simple test
    # browse devices...
    import sys
    if sys.version_info >= (3, ):
        # as is, don't handle unicodes
        unicode = str
        raw_input = input
    else:
        # allow to show encoded strings
        import codecs
        sys.stdout = codecs.getwriter('mbcs')(sys.stdout)

    all_hids = hid.find_all_hid_devices()
    if all_hids:
        while True:
            print("HID paddle is connected.")
            #            print("Choose a device to monitor raw input reports:\n")
            #            print("0 => Exit")
            for index, device in enumerate(all_hids):
                device_name = unicode("{0.vendor_name} {0.product_name}" \
                        "(vID=0x{1:04x}, pID=0x{2:04x})"\
                        "".format(device, device.vendor_id, device.product_id))
#                print("{0} => {1}".format(index+1, device_name))
#            print("\n\tDevice ('0' to '%d', '0' to exit?) " \
#                    "[press enter after number]:" % len(all_hids))
            index_option = '1'  #raw_input()
            if index_option.isdigit() and int(index_option) <= len(all_hids):
                # invalid
                break
        int_option = int(index_option)
        if int_option:
            device = all_hids[int_option - 1]
            try:
                device.open()

                #set custom raw data handler
                device.set_raw_data_handler(sample_handler)

                #                print("\nWaiting for data...\nPress any (system keyboard) key to stop...")
                while not kbhit() and device.is_plugged():
                    #just keep the device opened to receive events
                    sleep(0.5)
                return
            finally:
                device.close()
    else:
        print("There's not any non system HID class device available")
Exemplo n.º 48
0
def main(fn=None):
	if fn == None:
		for device in hid.find_all_hid_devices():
			if device.vendor_id == 0x21A1 and device.product_name == 'Brain Waves':
				try:
					device.open()
					device.set_raw_data_handler(sample_handler)
					while device.is_plugged() and count < 1000:
						time.sleep(0.1)
				finally:
					device.close()
					break
	else:
		for line in file(fn, 'r').readlines():
			data = [0] + [int(x, 16) for x in line.strip().split(' ')]
			sample_handler(data)
Exemplo n.º 49
0
def open(callback=None, button_callback=None, device=None):
    """
    Open a 3D space navigator device. Makes this device the current active device, which enables the module-level read() and close()
    calls. For multiple devices, use the read() and close() calls on the returned object instead, and don't use the module-level calls.
    
    Parameters:        
        callback: If callback is provided, it is called on each HID update with a copy of the current state namedtuple  
        button_callback: If button_callback is provided, it is called on each button push, with the arguments (state_tuple, button_state) 
        device: name of device to open. Must be one of the values in supported_devices. If None, chooses the first supported device found.
    Returns:
        Device object if the device was opened successfully
        None if the device could not be opened
    """
    # only used if the module-level functions are used
    global _active_device
    
    # if no device name specified, look for any matching device and choose the first
    if device==None:
        all_devices = list_devices()
        if len(all_devices)>0:
            device = all_devices[0]
        else:
            return None
        
    all_hids = hid.find_all_hid_devices()
    if all_hids:
        for index, dev in enumerate(all_hids):
                spec = device_specs[device]
                if dev.vendor_id == spec.hid_id[0] and dev.product_id == spec.hid_id[1]:
                    print("%s found") % device
                    # create a copy of the device specification
                    new_device = copy.deepcopy(spec)
                    new_device.device = dev
                    # set the callbacks
                    new_device.callback = callback
                    new_device.button_callback = button_callback
                    # open the device and set the data handler
                    new_device.open()                    
                    dev.set_raw_data_handler(lambda x:new_device.process(x))   
                    _active_device = new_device
                    return new_device
        print("No supported devices found")
        return None
    else:
        print("No HID devices detected")
        return None
Exemplo n.º 50
0
 def setup_windows(self):
     """
     Setup for headset on the Windows platform. 
     """
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             if device.vendor_id != 0x1234 and device.vendor_id != 0xED02:
                 continue
             if device.product_name == 'Brain Waves':
                 devices.append(device)
                 device.open()
                 self.serial_number = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == 'EPOC BCI':
                 devices.append(device)
                 device.open()
                 self.serial_number = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == '00000000000':
                 devices.append(device)
                 device.open()
                 self.serial_number = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == 'Emotiv RAW DATA':
                 devices.append(device)
                 device.open()
                 self.serial_number = device.serial_number
                 device.set_raw_data_handler(self.handler)
             elif device.product_name == 'EEG Signals':
                 devices.append(device)
                 device.open()
                 self.serial_number = device.serial_number
                 device.set_raw_data_handler(self.handler)
         crypto = gevent.spawn(self.setup_crypto, self.serial_number)
         console_updater = gevent.spawn(self.update_console)
         while self.running:
             try:
                 gevent.sleep(0)
             except KeyboardInterrupt:
                 self.running = False
     finally:
         for device in devices:
             device.close()
         gevent.kill(crypto, KeyboardInterrupt)
         gevent.kill(console_updater, KeyboardInterrupt)
Exemplo n.º 51
0
    def find_all_devices(self):
        '''
        线程检测USB的连接状态
        '''
        try:
            self.temp_pyusb = list()
            if platform.system() == "Windows":
                usb_dev = hid.find_all_hid_devices()
                for dev in usb_dev:
                    vid = self.fill_zero(hex(dev.vendor_id)[2:])
                    pid = self.fill_zero(hex(dev.product_id)[2:])
                    dev_info = "VID:{0} PID:{1}".format(vid, pid)
                    self.temp_pyusb.append(dev_info)
            else:
                usb_dev = usb.core.find(find_all=True)
                for dev in usb_dev:
                    vid = self.fill_zero(hex(dev.idVendor)[2:])
                    pid = self.fill_zero(hex(dev.idProduct)[2:])
                    dev_info = "VID:{0} PID:{1}".format(vid, pid)
                    self.temp_pyusb.append(dev_info)
            for item in self.temp_pyusb:
                if item not in self.list_box_pyusb:
                    self.frm_left_listbox.insert("end", item)
            for item in self.list_box_pyusb:
                if item not in self.temp_pyusb:
                    index = list(
                        self.frm_left_listbox.get(0, self.frm_left_listbox.size())).index(item)
                    self.frm_left_listbox.delete(index)
            # 检测到usb设备被拔出时,关闭usb设备
            if self.pid and self.vid:
                _vid = self.fill_zero(hex(self.vid)[2:])
                _pid = self.fill_zero(hex(self.pid)[2:])
                dev_info = "VID:{0} PID:{1}".format(_vid, _pid)
                if dev_info not in self.temp_pyusb:
                    self.Toggle()
                    self.vid = None
                    self.pid = None
            self.list_box_pyusb = self.temp_pyusb

            self.thread_find_all_devices = threading.Timer(
                1, self.find_all_devices)
            self.thread_find_all_devices.setDaemon(True)
            self.thread_find_all_devices.start()
        except:
            logging.error(e)
Exemplo n.º 52
0
def set_mute(mute_value):
    "Browse for mute usages and set value"
    all_mutes = ( \
            (0x8, 0x9), # LED page
            (0x1, 0xA7), # desktop page
            (0xb, 0x2f),
    )
    all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]

    # usually you'll find and open the target device, here we'll browse for the
    # current connected devices
    all_devices = hid.find_all_hid_devices()

    success = 0
    if not all_devices:
        print("Can't any HID device!")
    else:
        # search for our target usage
        # target pageId, usageId
        for device in all_devices:
            try:
                device.open()
                # target 'to set' value could be in feature or output reports
                for report in device.find_output_reports() + device.find_feature_reports():
                    for target_usage in all_target_usages:
                        if target_usage in report:
                            # set our value and send
                            print("Found in report: {0}\n".format(report))

                            old_raw_data = report.get_raw_data()
                            print("  Empty raw report: {0}".format(old_raw_data))
                            report[target_usage] = value
                            new_raw_data = report.get_raw_data()
                            print("  Set raw report: {0}\n".format(new_raw_data))
                            # validate that set_raw_data() is working properly
                            report.set_raw_data( new_raw_data )
                            report.send()
                            success += 1
            finally:
                device.close()
    # fit to sys.exit() proper result values
    print("{0} Mute usage(s) set\n".format(success))
    if success:
        return 0
    return -1
Exemplo n.º 53
0
def speed_test():
    # browse devices...
    all_hids = hid.find_all_hid_devices()
    if not all_hids:
        print("There's not any non system HID class device available")
        return

    while True:
        print("Choose a device to monitor raw input reports:\n")
        print("0 => Exit")
        for index, device in enumerate(all_hids):
            device_name = unicode("{0.vendor_name} {0.product_name}" \
                    "(vID=0x{1:04x}, pID=0x{2:04x}, instanceID={0.instance_id})"\
                    "".format(device, device.vendor_id, device.product_id, device))
            print("{0} => {1}".format(index+1, device_name))
        print("\n\tDevice ('0' to '%d', '0' to exit?) " \
                "[press enter after number]:" % len(all_hids))
        index_option = raw_input()
        if index_option.isdigit() and int(index_option) <= len(all_hids):
            # invalid
            break
    int_option = int(index_option)
    if not int_option:
        return

    device = all_hids[int_option-1]
    try:
        device.open()

        #set custom raw data handler
        device.set_raw_data_handler(sample_handler)
        msgData = range(64)
        while not kbhit() and device.is_plugged():
            #just keep the device opened to receive events
            msg = hid.core.HidReport()
            msg.send()
            for report in device.find_output_reports():
                for target_usage in range(len(report)):
                    report.send(msgData)
                    print(report.get_raw_data())
                    sleep(1)
            pass
        return
    finally:
        device.close()
Exemplo n.º 54
0
def ViewJoypad():
    # browse devices...
    all_devices = hid.find_all_hid_devices()
    if all_devices:
        while True:
            print "Choose a device to monitor raw input reports:\n"
            print "0 => Exit"
            for index, dev in enumerate(all_devices):
                device_name = unicode("%s %s (vID=%04x, pID=%04x)" % \
                        (dev.vendor_name, dev.product_name, dev.vendor_id, dev.product_id))
                print index+1, '=>', device_name
            print "\n\tDevice ('0' to '%d', '0' to exit?) [press enter after number]:" % len(all_devices),
            index_option = raw_input()
            if index_option.isdigit() and int(index_option) <= len(all_devices):
                break;
        int_option = int(index_option)
        if int_option:
            device = all_devices[int_option-1]

            global H
            H = handler.Handler(Parser(CONTROLLERFILEPATH).sections)
            H.setGlobalKeys()
            
            
            try:
                device.open()

                #set custom raw data handler
                device.set_raw_data_handler(H.mainHandler)

                print "\nWaiting for data...\nPress any (system keyboard) key to stop..."
                b = []
                while not kbhit() and device.is_plugged():
                    a = H.currentKey
                    if (a != b):
                        b = a
                        pprint(H.currentKey)
                #while not kbhit() and device.is_plugged():
                #    pass
                return
            finally:
                device.close()
    else:
        print "There's not any non system HID class device available"
Exemplo n.º 55
0
def raw_test():
    # simple test
    # browse devices...
    all_hids = hid.find_all_hid_devices()
    if all_hids:
        while True:
            print("Choose a device to monitor raw input reports:\n")
            print("0 => Exit")
            for index, device in enumerate(all_hids):
                device_name = unicode(
                    "{0.vendor_name} {0.product_name}"
                    "(vID=0x{1:04x}, pID=0x{2:04x})"
                    "".format(device, device.vendor_id, device.product_id)
                )
                print("{0} => {1}".format(index + 1, device_name))
            print("\n\tDevice ('0' to '%d', '0' to exit?) " "[press enter after number]:" % len(all_hids))
            index_option = raw_input()
            if index_option.isdigit() and int(index_option) <= len(all_hids):
                # invalid
                break
        int_option = int(index_option)
        if int_option:
            global device
            device = all_hids[int_option - 1]
            try:
                device.open()

                # set custom raw data handler
                device.set_raw_data_handler(sample_handler)

                print("\nWaiting for data...\nPress any (system keyboard) key to stop...")

                while not kbhit() and device.is_plugged():
                    # just keep the device opened to receive events
                    pass

                return
            finally:
                device.close()
    else:
        print("There's not any non system HID class device available")
Exemplo n.º 56
0
    def get_all_connected_interfaces():
        """! @brief Returns all the connected CMSIS-DAP devices
        """
        all_devices = hid.find_all_hid_devices()

        # find devices with good vid/pid
        all_mbed_devices = []
        for d in all_devices:
            if (d.product_name.find("CMSIS-DAP") >= 0):
                all_mbed_devices.append(d)

        boards = []
        for dev in all_mbed_devices:
            try:
                dev.open(shared=True)

                # Perform device-specific filtering.
                if filter_device_by_usage_page(dev.vendor_id, dev.product_id, dev.hid_caps.usage_page):
                    dev.close()
                    continue

                report = dev.find_output_reports()
                if len(report) != 1:
                    dev.close()
                    continue
                new_board = PyWinUSB()
                new_board.report = report[0]
                new_board.vendor_name = dev.vendor_name
                new_board.product_name = dev.product_name
                new_board.serial_number = dev.serial_number
                new_board.vid = dev.vendor_id
                new_board.pid = dev.product_id
                new_board.device = dev
                dev.close()
                boards.append(new_board)
            except Exception as e:
                if (str(e) != "Failure to get HID pre parsed data"):
                    LOG.error("Receiving Exception: %s", e)
                dev.close()

        return boards
Exemplo n.º 57
0
 def setup_windows(self):
     """
     Setup for headset on the Windows platform.
     """
     devices = []
     try:
         for device in hid.find_all_hid_devices():
             if device_is_emotiv(device, self.platform):
                 devices.append(device)
         if len(devices) == 0:
             print_hid_enumerate(system_platform, hid)
             sys.exit()
         device = devices[1]
         device.open()
         self.hid = device
         self.serial_number = device.serial_number
         device.set_raw_data_handler(self.data_handler)
     except Exception as ex:
         print("Emotiv WindowsSetupError ", sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], " : ", ex)
     finally:
         if self.hid is not None:
             self.hid.close()