def open_dev(): for desc in hid.enumerate(): if desc["vendor_id"] == 0x16d0 and desc[ "product_id"] == 0x106d and desc["interface_number"] == 1: dev = hid.device() dev.open_path(desc["path"]) return dev
def __enter__(self): dev = hidraw.device() for d in hidraw.enumerate(): logging.debug("Looking at v=%s pr=%s sn=%s if=%s p=%s", d['vendor_id'], d['product_id'], d['serial_number'], d['interface_number'], d['path']) if d['vendor_id'] != self.vend: continue if d['product_id'] != self.prod: continue if d['interface_number'] != self.iface: continue if self.sn is not None and d['serial_number'] != self.sn: continue dev.open_path(d['path']) logging.debug("Checking version") r = dev.write([0, ord('V')] + [0] * 7) if r != 9: logging.debug("Device handshake failed to send: %d", r) continue r = dev.read(8) if r[0:3] != [ord('V'), 0x00, 0xFF]: logging.debug("Device handshake mismatch: %r", r) dev.close() continue logging.debug("Device handshake OK: %r", r) self.dev = dev return dev else: raise ValueError("Device not found")
def list_connected(cls): btns = hid.enumerate(cls.USB_VID, cls.USB_PID) return [ (btn["serial_number"],btn["release_number"],btn["path"]) for btn in btns #if btn["manufacturer_string"] == cls.USB_MFR #and btn["product_string"] == cls.USB_PROD ]
def list_connected(cls): btns = hid.enumerate(cls.USB_VID, cls.USB_PID) return [ (btn["serial_number"], btn["release_number"], btn["path"]) for btn in btns #if btn["manufacturer_string"] == cls.USB_MFR #and btn["product_string"] == cls.USB_PROD ]
def enumerate_devices(cls): devices = [] for hidDevice in hid.enumerate(LEDGER_VENDOR_ID, 0): if ("interface_number" in hidDevice and hidDevice["interface_number"] == 0) or ("usage_page" in hidDevice and hidDevice["usage_page"] == 0xFFA0): hid_device_path = hidDevice["path"] devices.append(HidDevice(hid_device_path)) return devices
def list_devices(): devices = [] for d in hid.enumerate(0, 0): usage_page = d['usage_page'] if usage_page == 0xf1d0 and d['usage'] == 1: devices.append(HIDDevice(d['path'])) # Usage page doesn't work on Linux elif (d['vendor_id'], d['product_id']) in DEVICES: device = HIDDevice(d['path']) try: device.open() device.close() devices.append(HIDDevice(d['path'])) except exc.DeviceError: pass return devices
def list_devices(): devices = [] for d in hid.enumerate(0, 0): usage_page = d['usage_page'] if usage_page == 0xf1d0 and d['usage'] == 1: devices.append(HIDDevice) # Usage page doesn't work on Linux elif (d['vendor_id'], d['product_id']) in DEVICES: device = HIDDevice(d['path']) try: device.open() device.close() devices.append(HIDDevice(d['path'])) except exc.DeviceError: pass return devices
def __init__(self, device, description, **kwargs): # compatibility with v1.1.0 drivers, which could be directly # instantiated with a usb.core.Device if isinstance(device, usb.core.Device): clname = self.__class__.__name__ _LOGGER.warning( 'constructing a %s instance from a usb.core.Device has been deprecated, ' 'use %s.find_supported_devices() or pass a HidapiDevice handle', clname, clname) usbdev = device hidinfo = next( info for info in hid.enumerate(usbdev.idVendor, usbdev.idProduct) if info['serial_number'] == usbdev.serial_number) assert hidinfo, 'Could not find device in HID bus' device = HidapiDevice(hid, hidinfo) super().__init__(device, description, **kwargs)
def __init__(self, device, description, **kwargs): # compatibility with v1.1.0 drivers, which could be directly # instantiated with a usb.core.Device if isinstance(device, usb.core.Device): LOGGER.warning( 'deprecated: device must be HidapiDevice, not PyUSB handle') LOGGER.warning( 'deprecated: PyUSB no longer supported for HID devices') LOGGER.warning( 'deprecated: switch to find_supported_devices or pass HidapiDevice' ) usbdev = device hidinfo = next( info for info in hid.enumerate(usbdev.idVendor, usbdev.idProduct) if info['serial_number'] == usbdev.serial_number) assert hidinfo, 'Could not find device in HID bus' device = HidapiDevice(hid, hidinfo) super().__init__(device, description, **kwargs)
def main(): """ Main function: Entry point if running this module from the command line. Prints messages to stdout. """ import argparse from inspect import cleandoc parser = argparse.ArgumentParser(description=cleandoc(__doc__)) parser.add_argument('-v', '--verbose', action='store_true', help='Increase verbosity') parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') args = parser.parse_args() try: try: import hidraw as hid except ImportError: import hid except ImportError: parser.error("You need to install cython-hidapi first!") import logging loglevel = logging.WARNING if args.verbose: loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG logging.basicConfig(format='%(message)s', level=loglevel) try: logging.info("Enumerating Devices") devices = hid.enumerate(0x1a86, 0xe008) if len(devices) == 0: raise NameError('No device found. Check your USB connection.') logging.info("Found {} devices: ".format(len(devices))) for dev in devices: name = dev['manufacturer_string'] + " " + dev['product_string'] path = dev['path'].decode('ascii') logging.info("* {} [{}]".format(name, path)) logging.info("Opening device") h = hid.device() try: h.open(0x1a86, 0xe008) except IOError as ex: raise NameError('Cannot open the device. Please check permissions.') buf = [0]*6 buf[0] = 0x0 # report ID buf[1] = BPS & 0xFF buf[2] = ( BPS >> 8 ) & 0xFF buf[3] = ( BPS >> 16 ) & 0xFF buf[4] = ( BPS >> 24 ) & 0xFF buf[5] = 0x03 # 3 = enable? fr = h.send_feature_report(buf) if fr == -1: raise NameError("Sending Feature Report Failed") logging.debug("Feature Report Sent") try: logging.debug("Start Reading Messages") while True: #answer = h.read(256) answer = h.read(256, timeout_ms=1000) if len(answer) < 1: continue nbytes = answer[0] & 0x7 if nbytes > 0: if len(answer) < nbytes+1: raise NameError("More bytes announced then sent") payload = answer[1:nbytes+1] data = [b & ( ~(1<<7) ) for b in payload] data = [chr(b) for b in data] data = ''.join(data) sys.stdout.write(data) sys.stdout.flush() except KeyboardInterrupt: logging.info("You pressed CTRL-C, stopping...") logging.debug("Closing device") h.close() except IOError as ex: logging.error(ex) except Exception as ex: logging.error(ex)
def main(): """ Main function: Entry point if running this module from the command line. Prints messages to stdout. """ import argparse from inspect import cleandoc parser = argparse.ArgumentParser(description=cleandoc(__doc__)) parser.add_argument('-v', '--verbose', action='store_true', help='Increase verbosity') parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') args = parser.parse_args() try: try: import hidraw as hid except ImportError: import hid except ImportError: parser.error("You need to install cython-hidapi first!") import logging loglevel = logging.WARNING if args.verbose: loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG logging.basicConfig(format='%(message)s', level=loglevel) try: logging.info("Enumerating Devices") devices = hid.enumerate(0x1a86, 0xe008) if len(devices) == 0: raise NameError('No device found. Check your USB connection.') logging.info("Found {} devices: ".format(len(devices))) for dev in devices: name = dev['manufacturer_string'] + " " + dev['product_string'] path = dev['path'].decode('ascii') logging.info("* {} [{}]".format(name, path)) logging.info("Opening device") h = hid.device() try: h.open(0x1a86, 0xe008) except IOError as ex: raise NameError( 'Cannot open the device. Please check permissions.') buf = [0] * 6 buf[0] = 0x0 # report ID buf[1] = BPS & 0xFF buf[2] = (BPS >> 8) & 0xFF buf[3] = (BPS >> 16) & 0xFF buf[4] = (BPS >> 24) & 0xFF buf[5] = 0x03 # 3 = enable? fr = h.send_feature_report(buf) if fr == -1: raise NameError("Sending Feature Report Failed") logging.debug("Feature Report Sent") try: logging.debug("Start Reading Messages") while True: #answer = h.read(256) answer = h.read(256, timeout_ms=1000) if len(answer) < 1: continue nbytes = answer[0] & 0x7 if nbytes > 0: if len(answer) < nbytes + 1: raise NameError("More bytes announced then sent") payload = answer[1:nbytes + 1] data = [b & (~(1 << 7)) for b in payload] data = [chr(b) for b in data] data = ''.join(data) sys.stdout.write(data) sys.stdout.flush() except KeyboardInterrupt: logging.info("You pressed CTRL-C, stopping...") logging.debug("Closing device") h.close() except IOError as ex: logging.error(ex) except Exception as ex: logging.error(ex)
def readFromUsb(self): import argparse,sys from inspect import cleandoc BPS = 19200 try: try: import hidraw as hid except ImportError: import hid except ImportError: parser.error("You need to install cython-hidapi first!") import logging loglevel = logging.ERROR logging.basicConfig(format='%(message)s', level=loglevel) #try: if True: logging.info("Enumerating Devices") devices = hid.enumerate(0, 0) print(devices) if len(devices) == 0: raise NameError('No device found. Check your USB connection.') logging.info("Found {} devices: ".format(len(devices))) for dev in devices: name = dev['manufacturer_string'] + " " + dev['product_string'] path = dev['path'].decode('ascii') logging.info("* {} [{}]".format(name, path)) logging.info("Opening device") h = hid.device() try: h.open(0x1a86, 0xe008) except IOError as ex: raise NameError('Cannot open the device. Please check permissions.') buf = [0]*6 buf[0] = 0x0 # report ID buf[1] = BPS & 0xFF buf[2] = ( BPS >> 8 ) & 0xFF buf[3] = ( BPS >> 16 ) & 0xFF buf[4] = ( BPS >> 24 ) & 0xFF buf[5] = 0x03 # 3 = enable? fr = h.send_feature_report(buf) if fr == -1: raise NameError("Sending Feature Report Failed") logging.debug("Feature Report Sent") try: logging.debug("Start Reading Messages") while True: #answer = h.read(256) answer = h.read(256, timeout_ms=1000) if len(answer) < 1: continue nbytes = answer[0] & 0x7 if nbytes > 0: if len(answer) < nbytes+1: raise NameError("More bytes announced then sent") payload = answer[1:nbytes+1] data = [b & ( ~(1<<7) ) for b in payload] data = [chr(b) for b in data] data = ''.join(data) if not data.endswith("\r\n"): self.lastvalue = data else: self.lastvalue = self.lastvalue + data self.parseValue(self.lastvalue) #sys.stdout.write(data) #sys.stdout.flush() except KeyboardInterrupt: logging.info("You pressed CTRL-C, stopping...") logging.debug("Closing device") h.close()
def find_device(): for desc in hid.enumerate(): if desc["vendor_id"] == QC_VID and desc[ "product_id"] == QC_PID and desc["interface_number"] == 1: return desc return None