Beispiel #1
0
    def _connect(self):
        try:
            for d in hid.enumerate(0, 0):
                vendor_id = d['vendor_id']
                product_id = d['product_id']
                serial_number = d['serial_number']
                interface_number = d['interface_number']
                usage_page = d['usage_page']
                path = d['path']

                if (vendor_id, product_id) in DEVICE_IDS:
                    if serial_number == '1000000000':
                        if usage_page == 0xffab or interface_number == 2:
                            self._hid = hid.Device(vendor_id,
                                                   product_id,
                                                   path=path)
                            self._hid.nonblocking = True
                    else:
                        if usage_page == 0xf1d0 or interface_number == 1:
                            self._hid = hid.Device(vendor_id,
                                                   product_id,
                                                   path=path)
                            self._hid.nonblocking = True

        except:
            log.exception('failed to connect')
            raise OnlyKeyUnavailableException()
Beispiel #2
0
    def __init__(self):
        vid = 0x10e6
        pid = 0x1033

        with hid.Device(vid, pid) as h:
            print(f'Device manufacturer: {h.manufacturer}')
            print(f'Product: {h.product}')
            print(f'Serial Number: {h.serial}')

        self.unit = hid.Device(vid, pid)
Beispiel #3
0
    def __init__(self, filename: str):
        self.mid = mido.MidiFile(filename)
        #self.connect()

        self.joyconL = hid.Device(0x057E, 0x2006)
        self.joyconR = hid.Device(0x057E, 0x2006 + 0x01)

        self.send_cmd(0x48, [0x01])
        self.send_cmd(0x30, [0xFF])
        self.send_cmd(0x38, [0x28, 0x20, 0xF2, 0xF0, 0xF0])
Beispiel #4
0
 def __init__(self, serial_number_str=None):
     self._hid = hid.Device(Device.VID, Device.PID, serial_number_str)
     self.serial_number = self._hid.serial
     self._reset()
     self._hid.close()
     time.sleep(1)
     self._hid = hid.Device(Device.VID, Device.PID, self.serial_number)
     device = helper.find_serial_port(Device.VID, Device.PID,
                                      self.serial_number)
     self._serial = serial.Serial(device)
     #self.serial_number = self._get_serial_number()
     self.firmware_version = self._get_firmware_version()
     # self._report_events_list = []
     self._irq_event_callbacks = {}
Beispiel #5
0
  def __init__(self, vid=None, pid=None, serial=None, path=None):
    if path:
      self.device = hid.Device(path=path)
    elif serial:
      self.device = hid.Device(serial=serial)
    else:
      if vid is None:
        vid = CP2110_VID

      if pid is None:
        pid = CP2110_PID

      self.device = hid.Device(vid=vid, pid=pid)

    self.device.nonblocking = 1
Beispiel #6
0
def open_device(device_type):
    dev = None

    devlist = [device_type]
    if 'dongle' not in devlist:
        devlist.append('dongle')

    for i in devlist:
        try:
            vid = get_device_vid(i)
            pid = get_device_pid(i)
            dev = hid.Device(vid=vid, pid=pid)
            break
        except hid.HIDException:
            pass
        except:
            logging.error('Unknown error: {}'.format(sys.exc_info()[0]))

    if dev is None:
        print('Cannot find selected device nor dongle')
    elif i == device_type:
        print('Device found')
    else:
        print('Device connected via {}'.format(i))

    return dev
def open_device():
    global hid
    import hid

    info_good = []
    info_skip = []

    device_list = hid.enumerate(0x046d, 0xc245)
    for info in device_list:
        # The mouse should have two interfaces, #0 and #1.  We need
        # interface #1.  Linux uses the `interface_number` field.  macOS uses
        # an IOKit IOService path, which includes a string like
        # "/IOUSBHostInterface@0/".
        if b"/IOUSBHostInterface@0/" in info["path"] or info[
                "interface_number"] == 0:
            info_skip.append(info)
        elif b"/IOUSBHostInterface@1/" in info["path"] or info[
                "interface_number"] == 1:
            info_good.append(info)
        else:
            print("unexpected G400 USB device: " + info["path"])

    if len(info_good) == 1:
        return hid.Device(path=info_good[0]["path"])
    elif len(info_good) != len(info_skip):
        sys.exit(
            "error: unexpected USB interfaces while querying for a G400 mouse")
    elif len(info_good) == 0:
        sys.exit("error: no G400 mouse attached")
    else:
        sys.exit(
            "error: multiple G400 mice detected -- this script only supports one"
        )
Beispiel #8
0
    def __init__(self, hid_device, numeric):
        self.hid_device = hid_device
        self.numeric = numeric
        self.device = hid.Device(path=hid_device['path'])
        self.current_line = ''

        cli.log.info('Console Connected: %(color)s%(manufacturer_string)s %(product_string)s{style_reset_all} (%(color)s%(vendor_id)04X:%(product_id)04X:%(index)d{style_reset_all})', hid_device)
Beispiel #9
0
    def __init__(self, index=0, path=None):
        """Initialize."""

        device = None
        devices = enumerate_luxafor()
        if not devices:
            raise RuntimeError('Cannot find a valid connected Luxafor device')
        if path is not None:
            target = os.fsencode(path)
            for d in devices:
                if d['path'] == target:
                    device = d['path']
                    break
            if device is None:
                raise RuntimeError(
                    'The Luxfor device with path {} could not be found'.format(
                        path))
        if device is None:
            if index < 0 or index >= len(devices):
                raise RuntimeError(
                    'The Luxafor device at index {} cannot be found'.format(
                        index))
            device = devices[index]['path']
        self._path = device
        self._device = hid.Device(path=self._path)
        self._closed = False
        self._disconnected = False
        self._serial = self._get_serial()
Beispiel #10
0
    def __init__(self, config, comm):
        super().__init__()

        self._is_trigger = False
        self._is_enabled = True

        self._comm = comm
        self._h = hid.Device(vid, pid)
Beispiel #11
0
    def __init__(self, device=hid.Device, vid=None, pid=None, path=None):
        # Initialize the base class event object
        super().__init__()
    
        # Path must be convertable to bytes, and vid/pid integers
        if path:
            try:
                self.__path = path.lower().encode()
            except AttributeError:
                self.__path = path.lower()
            try:
                with hid.Device(path=self.__path):
                    super().set()
            except hid.HIDException:
                pass
        elif vid and pid:
            try:
                v, p = map(lambda x: int(x),[vid,pid])
            except:
                v, p = map(lambda x: int(x, 0),[vid,pid])
            
            # The IDs are only used to find the full device path
            self.__ids = list(f"{x}_{y:04x}".encode() for x, y in zip(["vid","pid"],[v,p]))
            
            # Always use path for connection; check for device at startup
            self.__path = None
            for d in hid.enumerate(vid=v, pid=p):
                if self.__matchingdevice(d["path"]):
                    super().set()
                    break
        else:
            raise Exception("VID, PID or path required for HID device")
        
        self.__dev = device
    
        # Create a window class for receiving messages
        self.wc = win32gui.WNDCLASS()
        self.wc.hInstance = win32api.GetModuleHandle(None)
        self.wc.lpszClassName = "win32hidnotifier"
        self.wc.lpfnWndProc = {win32con.WM_DEVICECHANGE:self.__devicechange}
        
        # Register the window class
        winClass = win32gui.RegisterClass(self.wc)
        
        # Create a Message-Only window
        self.hwnd = win32gui.CreateWindowEx(
            0,                      #dwExStyle
			self.wc.lpszClassName,  #lpClassName
			self.wc.lpszClassName,  #lpWindowName
			0, 0, 0, 0, 0,
			win32con.HWND_MESSAGE,  #hWndParent
			0, 0, None)
        
        # Watch for all USB device notifications
        self.filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE(Win32HID.GUID_DEVINTERFACE_HID)
        self.hdev = win32gui.RegisterDeviceNotification(self.hwnd, self.filter,
                                                        win32con.DEVICE_NOTIFY_WINDOW_HANDLE)
Beispiel #12
0
def open_device():
    # Open HID device. If mouse is not connected, try dongle
    try:
        try:
            dev = hid.Device(vid=NORDIC_VID, pid=MOUSE_PID)
            print("Found nRF52 Desktop Mouse")
        except hid.HIDException:
            try:
                dev = hid.Device(vid=NORDIC_VID, pid=DONGLE_PID)
                print("Found nRF52 Desktop Dongle")
            except hid.HIDException:
                logging.error("No device connected")
                return None
    except:
        logging.error("Unknown error: {}".format(sys.exc_info()[0]))
        return None

    return dev
Beispiel #13
0
    def __init__(self):
        """Initialize the QLight class.

        Attributes:
            lights (OrderedDict): A list of all lights and the state that they
            have been set to.  The valid states are:

                    off: The light is off.
                    on: The light is on.
                    blink: The light alternates between off and on.
                    pass: The light has not had a state set, and it will
                        maintain it's previous state on updates.

                All lights are initialized to a value of 'pass' because there
                is no known way to poll the light for the current status of the
                lights.

            sound (str): What audio pattern the light is currently playing.
                The exact pattern that is played for the 5 different tones
                varies depending on the model.  The valid states are:

                    off: No sound is playing.
                    tone_1: The first tone is playing.
                    tone_2: The second tone is playing.
                    tone_3: The third tone is playing.
                    tone_4: The fourth tone is playing.
                    tone_5: The fifth tone is playing.
                    pass: The light has not had an audio tone set, whatever
                        tone it is already playing will continue to play.

                The sound is initialized to a value of 'pass' because there is
                no known way to poll the light for the current status of the
                audio.
        """
        self._light_states = {
            'off': '00',
            'on': '01',
            'blink': '02',
            'pass': '******'
        }
        self.lights = OrderedDict([('red', 'pass'), ('yellow', 'pass'),
                                   ('green', 'pass'), ('blue', 'pass'),
                                   ('white', 'pass')])
        self._sound_states = {
            'off': '00',
            'tone_1': '01',
            'tone_2': '02',
            'tone_3': '03',
            'tone_4': '04',
            'tone_5': '05',
            'pass': '******'
        }
        self.sound = 'pass'

        self._usbdev = hid.Device(vid=1240, pid=59196)
        assert self._usbdev is isinstance(hid.Device)
Beispiel #14
0
def main():
    with hid.Device(vid, pid) as h:
        print(h)
        # print(f'Device manufacturer: {h.manufacturer}')
        # print(f'Product: {h.product}')
        # print(f'Serial Number: {h.serial}')

        data = struct.pack("<II", RETURN_KERNEL_0, RETURN_KERNEL_1)
        print(data)
        print(h.send_feature_report(data))
 def __init__(self):
     self.device = None
     try:
         self.device = hid.Device(self.VENDOR, self.PRODUCT)
     except Exception as e:
         if str(e) == 'unable to open device':
             raise Exception('Microlife Blood Pressure Monitor '
                             'not found on USB ports.')
         else:
             raise e
Beispiel #16
0
async def hid_fido_tokens(addresses=[], check_usage=None):
    # adresses are of the form VVVV[PPPP[-S+]]] where VVVV is the hex
    # representation of the vendor id, PPPP the hex representation of
    # the product id and S+ the serial number string
    vendor_ids = {}
    for address in addresses:
        if len(address) < 4:
            raise Exception('invalid address %s' % address)
        vendor_id = int(address[:4], 16)
        if wendor_id not in vendor_ids:
            vendor_ids[vendor_id] = {}
        product_ids = vendor_ids[vendor_id]
        if len(address) >= 8:
            product_id = int(address[4:8], 16)
            if product_id not in product_ids:
                product_ids[product_id] = []
            if len(address) > 9:
                serial_numbers = product_ids[product_id]
                serial_numbers.append(address[9:])
    if check_usage is None and not addresses:
        check_usage = True
    hid_device_infos = hid.enumerate()
    for hid_device_info in hid_device_infos:
        device_vendor_id = hid_device_info['vendor_id']
        device_product_id = hid_device_info['product_id']
        device_serial_number = hid_device_info['serial_number']
        if vendor_ids:
            if device_vendor_id not in vendor_ids:
                continue
            product_ids = vendor_ids[device_vendor_id]
        else:
            product_ids = None
        if product_ids:
            if device_product_id not in product_ids:
                continue
            serial_numbers = product_ids[device_product_id]
        else:
            serial_numbers = None
        if serial_numbers:
            if device_serial_number not in serial_numbers:
                continue
        if check_usage:
            usage_page = hid_device_info['usage_page']
            usage = hid_device_info['usage']
            if usage_page != 0xf1d0 or usage != 0x01:
                continue
        try:
            hid_device = hid.Device(device_vendor_id,
                                    device_product_id)  #, serial_number)
        except:
            print('failed to open device 0x%x 0x%x' %
                  (device_vendor_id, device_product_id))
            raise
        hid_fido_token = HIDFidoToken(hid_device, hid_device_info)
        yield hid_fido_token
Beispiel #17
0
def open_device(device_type):
    if device_type not in ['mouse', 'keyboard', 'dongle']:
        print("Unsupported device type")
        return None

    try:
        dev = hid.Device(vid=NORDIC_VID, pid=get_device_pid(device_type))
        print("Found device")
    except hid.HIDException:
        try:
            dev = hid.Device(vid=NORDIC_VID, pid=DONGLE_PID)
            print("Try to connect via dongle")
        except hid.HIDException:
            print("Cannot find selected device nor dongle")
            return None
    except:
        logging.error("Unknown error: {}".format(sys.exc_info()[0]))
        return None

    return dev
Beispiel #18
0
        def open(self):
            """
            Opens the HID device for input/output. This must be called prior to
            sending or receiving any HID reports.

            .. seealso:: See :func:`~HID.Device.close` for the corresponding
                         close method.
            """
            import hid

            self.hid = hid.Device(path=self.hid_info['path'])
 def __init__(self):
     
     hid.enumerate()
     self.device = hid.Device(vid=0x0451, pid=0xc900)
     time.sleep(0.5)
     #self.device.open(0x0451, 0xc900) #open the communication
     #self.device.open(0x0145, 0x022E) #open the communication
     # print(self.device.get_manufacturer_string())
     # print(self.device.get_product_string())
     # print(self.device.get_serial_number_string())
     self.ans = []
Beispiel #20
0
 def connect(self, vid=0x057E, pid=0x2006):
     for i in range(0x0004):
         try:
             self.joycon = hid.Device(vid, pid + i)
         except:
             pass
     if not hasattr(self, 'joycon'):
         print('Failed to detect Joycon L, R, PRO or other Device')
         exit()
     else:
         print(f'Device: {self.joycon.product}')
Beispiel #21
0
    def connect(self):
        """Connects the USB device.

        Connects the device and saves the USB device info attributes.
        """

        self.device = hid.Device(vid=self.vid, pid=self.pid)
        if not self.manufacturer:
            self.manufacturer = self.device.manufacturer
            self.product = self.device.product
            self.serial = self.device.serial
Beispiel #22
0
    def __init__(self):
        # Find matching USB HID devic
        self._vid = 0x0CB6
        self._pid = 0x0002
        devices = hid.enumerate(self._vid, self._pid)
        if not devices:
            raise RuntimeError('Cannot find USB LCD device')
        self._path = devices[0]['path']

        # Open hid device
        self._device = hid.Device(path=self._path)
Beispiel #23
0
    def __init__(self, device_path=None):
        if device_path is None:
            for dev in hid.enumerate():
                if dev['product_string'] == 'EL USB RT':
                    path = dev['path']

        if path is None:
            message = 'No path give and unable to find it'
            raise ValueError(message)

        self.dev = hid.Device(path=path)
Beispiel #24
0
 def _get_compatible_board_and_reset(self, serial_number_str=None):
     for vid, pid in COMPATIBLE_BOARD_PID_VID:
         try:
             self._hid = hid.Device(vid, pid, serial_number_str)
             serial_number = self._hid.serial
             self._reset()
             self._hid.close()
         except hid.HIDException:
             continue
         return vid, pid, serial_number
     return None, None, None
Beispiel #25
0
def setup():
    global selected
    monitors = lib27gn950.find_monitors()
    if not monitors:
        print('No monitors found')
        sys.exit(0)
    for monitor in monitors:
        dev = hid.Device(path=monitor['path'])
        dev.model = monitor['model']
        devs.append(dev)
    selected = list(range(len(devs)))
Beispiel #26
0
 def _open(self, vendor_id, product_id, serial):
     try:
         if hasattr(hid, "device"):  # hidapi
             _joycon_device = hid.device()
             _joycon_device.open(vendor_id, product_id, serial)
         elif hasattr(hid, "Device"):  # hid
             _joycon_device = hid.Device(vendor_id, product_id, serial)
         else:
             raise Exception("Implementation of hid is not recognized!")
     except IOError as e:
         raise IOError('joycon connect failed') from e
     return _joycon_device
Beispiel #27
0
    def open(self):
        """
        Ready the device for use
        :return:
        """
        path = self._find_path()

        try:
            self.handle = hid.Device(path=path)
        except Exception:
            raise ValueError('Device not found:', self.VENDOR_ID,
                             self.PRODUCT_ID, self.bus_location)
Beispiel #28
0
 def __init__(self, serial_number_str=None):
     self.vid, self.pid, self.serial_number = self._get_compatible_board_and_reset(
         serial_number_str)
     if self.serial_number is None:
         raise ValueError("No board found")
     time.sleep(1)
     self._hid = hid.Device(self.vid, self.pid, self.serial_number)
     device = helper.find_serial_port(self.vid, self.pid,
                                      self.serial_number)
     self._serial = serial.Serial(device)
     self.firmware_version = self._get_firmware_version()
     # self._report_events_list = []
     self._irq_event_callbacks = {}
Beispiel #29
0
def hid_test():
    result = True

    # first byte is report id 3 to indicate big packet.
    # This packet would normally be 64 bytes, but for some bug in ST's usb code it won't receive it unless we send
    # something smaller first...
    # So we test with a packet of 56 bytes.
    bigReport = [
        3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
    ]

    # fill bigreport (except for report Id) with random bytes
    for i in range(1, len(bigReport)):
        bigReport[i] = random.randint(0, 255)

    result = True
    try:
        with hid.Device(vid, pid) as h:
            outpacket = bytes(bigReport)

            # we perform the test twice, because first received HID packet is corrupt because of ST firmware (grr)
            h.write(outpacket)
            inpacket = h.read(64,
                              100)  # read maximum of 64 bytes, 100 ms timeout

            h.write(outpacket)
            inpacket = h.read(64,
                              100)  # read maximum of 64 bytes, 100 ms timeout

            if len(bytearray(inpacket)) == 0:
                print("HID Test failed: timeout while reading device. FAIL")
                result = False

            elif outpacket != inpacket:
                print("HID Test failed, packets are not equal. FAIL")
                print("Sent:")
                print(outpacket)
                print("Received:")
                print(inpacket)
                result = False
    except Exception as e:
        print(e)
        print("HID Test failed, could not open device. FAIL")
        result = False

    if result == True:
        print("HID Test PASS")
    return result
Beispiel #30
0
    def _open_devices(vid, pid):
        devs = []
        try:
            devlist = hid.enumerate(vid=vid, pid=pid)
            for d in devlist:
                dev = hid.Device(path=d['path'])
                devs.append(dev)

        except hid.HIDException:
            pass
        except Exception as e:
            logging.error('Unknown exception: {}'.format(e))

        return devs