def __find_device(self) -> hidapi.Device: """ find HID device and open it Raises: Exception: HIDGuardian detected Exception: No device detected Returns: hid.Device: returns opened controller device """ # TODO: detect connection mode, bluetooth has a bigger write buffer # TODO: implement multiple controllers working if sys.platform.startswith('win32'): import pydualsense.hidguardian as hidguardian if hidguardian.check_hide(): raise Exception('HIDGuardian detected. Delete the controller from HIDGuardian and restart PC to connect to controller') detected_device: hidapi.Device = None devices = hidapi.enumerate(vendor_id=0x054c) for device in devices: if device.vendor_id == 0x054c and device.product_id == 0x0CE6: detected_device = device if detected_device == None: raise Exception('No device detected') dual_sense = hidapi.Device(vendor_id=detected_device.vendor_id, product_id=detected_device.product_id) return dual_sense
def _open(device, hidpp): if hidpp and not device: for d in hidapi.enumerate(vendor_id=0x046d): if d.driver == 'logitech-djreceiver': device = d.path break if not device: sys.exit("!! No HID++ receiver found.") if not device: sys.exit("!! Device path required.") print (".. Opening device", device) handle = hidapi.open_path(device) if not handle: sys.exit("!! Failed to open %s, aborting." % device) print (".. Opened handle %r, vendor %r product %r serial %r." % ( handle, hidapi.get_manufacturer(handle), hidapi.get_product(handle), hidapi.get_serial(handle))) if hidpp: if hidapi.get_manufacturer(handle) != b'Logitech': sys.exit("!! Only Logitech devices support the HID++ protocol.") print (".. HID++ validation enabled.") return handle
def __init__(self, vendor_id=0x10c4, product_id=0x8468, timeout_ms=1000, data=b'', debug=False): self.debug = debug self.data = data self.hd = None if (not self.data): self.timeout_ms = timeout_ms deviceInfo = next( hidapi.enumerate(vendor_id=vendor_id, product_id=product_id)) self.hd = hidapi.Device(info=deviceInfo) self.generator = self._generator() first_chunk = next(self.generator) init_ok = int.from_bytes(self.get_field("init_ok"), byteorder='big') if (init_ok != 0x55aa): raise RuntimeError( "Incorrect device ROM magic number (is %04x, should be 55aa). Try again without re-connecting the device. If the error persists, this software is not meant to be used with your device." % (init_ok)) self.model = int.from_bytes(self.get_field("model"), byteorder='big') if (self.model != 0x0201): raise RuntimeError("Unknown model number.") self.id = self.get_field("ID") self.id_str = binascii.hexlify(self.id).decode("ascii") self.settings = self.get_field("settings") #self.current_interval_seconds = int.from_bytes(self.settings[1:3], byteorder='big') # not actually used anywhere – measurement series store the interval they were recorded at # TODO: move this offset into memory_map? if (self.settings[0] != 0x2d or self.settings[3:] != binascii.unhexlify('006414')): sys.stderr.write( "WARNING: Unknown settings detected (only 24h format with degrees celsius was tested). Expect havoc.\n" )
def _open(args): device = args.device if args.hidpp and not device: for d in _hid.enumerate(vendor_id=0x046d): if d.driver == 'logitech-djreceiver': device = d.path break if not device: sys.exit("!! No HID++ receiver found.") if not device: sys.exit("!! Device path required.") print(".. Opening device", device) handle = _hid.open_path(device) if not handle: sys.exit("!! Failed to open %s, aborting." % device) print(".. Opened handle %r, vendor %r product %r serial %r." % (handle, _hid.get_manufacturer(handle), _hid.get_product(handle), _hid.get_serial(handle))) if args.hidpp: if _hid.get_manufacturer(handle) != b'Logitech': sys.exit("!! Only Logitech devices support the HID++ protocol.") print(".. HID++ validation enabled.") else: if (_hid.get_manufacturer(handle) == b'Logitech' and b'Receiver' in _hid.get_product(handle)): args.hidpp = True print(".. Logitech receiver detected, HID++ validation enabled.") return handle
def _find_devices(self): for candidate in hidapi.enumerate(): try: dev = hidapi.Device(candidate, blocking=False) except IOError: raise DeviceException("Could not open HID device, please check" " your permissions on /dev/bus/usb.") yield dev
def discover(self): """ Perform HID device discovery Iterates over all connected HID devices with RAZER_VENDOR_ID and checks the product ID against the Hardware descriptor. Interface endpoint restrictions are currently hard-coded. In the future this should be done by checking the HID report descriptor of the endpoint, however this functionality in HIDAPI is broken (report_descriptor returns garbage) on Linux in the current release. Discovery is automatically performed when the object is constructed, so this should only need to be called if the list of devices changes (monitoring for changes is beyond the scope of this API). """ devinfos = sorted(list(hidapi.enumerate(vendor_id=RAZER_VENDOR_ID)), key=lambda x: x.path) for devinfo in devinfos: parent = self._get_parent(devinfo.product_id) if parent is None: continue if self._key_for_path(parent.sys_path) is not None: continue hardware = Hardware.get_device(devinfo.product_id) if hardware is None: continue if hardware.type == Hardware.Type.HEADSET: if devinfo.interface_number != 3: continue elif hardware.type in (Hardware.Type.KEYBOARD, Hardware.Type.KEYPAD, Hardware.Type.LAPTOP): if devinfo.interface_number != 2: continue elif hardware.type in (Hardware.Type.MOUSE, Hardware.Type.MOUSEPAD): if devinfo.interface_number != 1: continue else: if devinfo.interface_number != 0: continue device = self._create_device(parent, hardware, devinfo) if device is not None: self._devices[device.key] = device if hardware.type == Hardware.Type.KEYBOARD: device.set_device_mode(0) if self._monitor and self._callbacks: ensure_future(self._fire_callbacks('add', device), loop=self._loop)
def hid_enumerate(vid=0, pid=0): '''HID enumerate wrapper function''' for info in hid.enumerate(vid, pid) if _usingHid else hidapi.enumerate(vid, pid): if _usingHid: ret = info else: # unfortunately there is no __dict__ attr in the cffi DeviceInfo object ret = dict([(p, getattr(info, p)) for p in info.__slots__]) yield ret
def find_joycons(): lefts = [] rights = [] for d in hidapi.enumerate(vendor_id=VENDOR_ID): if d.product_id == PRODUCT_ID_L: lefts.append(d) elif d.product_id == PRODUCT_ID_R: rights.append(d) return (lefts, rights)
def main(): for dev_info in hidapi.enumerate(vendor_id=0x413d, product_id=0x2107): if(dev_info.interface_number != 1): continue dev = hidapi.Device(info=dev_info) dev.write(b'\x01\x80\x33\x01\x00\x00\x00\x00') temp_raw = dev.read(8) dev.close() print(dump_to_temperature(temp_raw[2:4])) exit(0) print('No temper thermometer found') exit(1)
def _find_devices(self): """ Find all attached USB HID devices. :returns: All devices found :rtype: Generator that yields :py:class:`hidapi.Device` """ for candidate in hidapi.enumerate(): try: dev = hidapi.Device(candidate, blocking=False) except IOError: raise DeviceException("Could not open HID device, please check" " your permissions on /dev/bus/usb.") yield dev
def __init__(self, vendor_id=0x04d8, product_id=0xef7e, product_string=u'HoloPlay'): for dev in hidapi.enumerate(vendor_id=vendor_id, product_id=product_id): if dev.product_string == product_string: self.hiddev = hidapi.Device(dev) self.calibration = self.loadconfig() self.calculate_derived() break else: raise IOError("Looking Glass HID device not found")
def __init__(self, conntype='usb'): self.pdstate = 0 self.redcurrent = 0x08 self.ircurrent = 0x10 self.rawred = 0 self.redw = 0.0 self.redv = 0.0 self.red = 0.0 self.redsum = 0.0 self.rawir = 0 self.irw = 0.0 self.irv = 0.0 self.ir = 0.0 self.irsum = 0.0 self.redbuf = numpy.zeros(self.AVGSIZE, dtype=int) self.irbuf = numpy.zeros(self.AVGSIZE, dtype=int) self.bufidx = 0 self.pulse = False self.i2c = None self.usb = None if conntype == 'i2c': try: self.i2c = SMBus(1) self.set_reg(self.MODE_CONF, 0x40) time.sleep(0.01) self.set_reg(self.MODE_CONF, 0x03) self.set_reg(self.SPO2_CONF, ((0x00 << 5) | (0x01 << 2) | 0x03)) self.set_currents() self.set_reg(self.TEMP_CONF, 0x01) except: print "Heartbeat I2C sensor failed" self.i2c = None if conntype == 'usb': try: for dev in hidapi.enumerate(self.USB_VENDORID, self.USB_PRODUCTID): print "Checking %s" % (dev.path) if dev.manufacturer_string == self.USB_MANUFACTURER and dev.product_string == self.USB_PRODUCT: self.usb = hidapi.Device(path=dev.path) except: self.usb = None if not self.usb: print "Heartbeat USB sensor failed"
def __init__(self): devices = tuple( hidapi.enumerate(vendor_id=self.vendor_id, product_id=self.product_id)) if not devices: raise DeviceNotFound() # keyboard subdevice kbd_info = next(filter(lambda x: x.interface_number == 1, devices), None) # control subdevice ctl_info = next(filter(lambda x: x.interface_number == 2, devices), None) self._kbd = hidapi.Device(kbd_info) self._ctl = hidapi.Device(ctl_info)
def __init__(self): logger.debug('searching for device {}'.format(self.__class__.info())) devices = tuple( hidapi.enumerate(vendor_id=self.vendor_id, product_id=self.product_id)) if len(devices): logger.debug('found {} subdevices:'.format(len(devices))) for device in devices: # print(device) # print(dir(device)) # x = 'interface_number', 'manufacturer_string', 'path', 'product_id', 'product_string', 'release_number', 'serial_number', 'usage', 'usage_page', 'vendor_id' # for i in x: # print(i, getattr(device, i)) interface = '' if device.interface_number == self.keyboard_interface: interface = ' [using as keyboard]' elif device.interface_number == self.control_interface: interface = ' [using as control]' logger.debug('{}: {} {} interface {}{}'.format( device.path.decode(), device.manufacturer_string, device.product_string, device.interface_number, interface)) else: logger.debug('0 devices found') if not devices: raise DeviceNotFound() # keyboard subdevice kbd_info = next( filter(lambda x: x.interface_number == self.keyboard_interface, devices), None) # control subdevice ctl_info = next( filter(lambda x: x.interface_number == self.control_interface, devices), None) logger.debug('opening keyboard subdevice') self._kbd = hidapi.Device(kbd_info) logger.debug('opening control subdevice') self._ctl = hidapi.Device(ctl_info)
#!/usr/bin/env python import time, sys import hidapi devpath = None for d in hidapi.enumerate(0x16c0, 0x05df): if d.manufacturer_string == 'monsuwe.nl' and d.product_string == 'HeartMonitor': devpath = d.path if not devpath: raise "No device found" dev = hidapi.Device(path=devpath) print "%s %s" % (dev.get_manufacturer_string(), dev.get_product_string()) while True: values = map(ord, dev.get_feature_report(chr(0), (6 * 8) + 2)) if values: errstate = values[0] nums = values[1] #print "Err: %02x Nums: %02x" % (errstate, nums) for sn in range(0, nums): red = (values[sn * 6 + 2] * 256 + values[sn * 6 + 3]) * 256 + values[sn * 6 + 4] ird = (values[sn * 6 + 5] * 256 + values[sn * 6 + 6]) * 256 + values[sn * 6 + 7] print "Red: %10d IR: %10d" % (red, ird) time.sleep(0.02)
def receivers(): """List all the Linux devices exposed by the UR attached to the machine.""" for receiver_usb_id in _RECEIVER_USB_IDS: for d in _hid.enumerate(receiver_usb_id): yield d
# Read the HID stream from the PSVR and extract # the timestamp, gyro and accelerometer values. import hidapi import struct from sys import version_info if version_info[0] < 3: import six time2 = 0 Sensor = None # Use the first HID interface of the PSVR device_list = hidapi.enumerate(0x054c, 0x09af) for device_info in device_list: Sensor = hidapi.Device(device_info) break while Sensor: data = Sensor.read(64) if data == None: continue (time1, ) = struct.unpack("<I", data[16:20]) if time1 < time2: time2 = time2 - (1 << 24) print("Time-Slot1:", time1, time1 - time2) print("Gyros:", struct.unpack("<hhh", data[20:26])) print("Accel:", struct.unpack("<hhh", data[26:32]))
def receivers(): """Enumerate all the receivers attached to the machine.""" yield from _hid.enumerate(filter_receivers)
#print jsonlen json = bytearray() while len(json) < jsonlen: page = len(json)//64 l = min(64, jsonlen-64*page) json[64*page:] = rp(dev, page, l) #print json return json[4:] def read_eeprom(devinfo): dev = hidapi.Device(devinfo) cfg = json.loads(loadconfig(dev).decode('ascii')) pprint(cfg) # TODO: Use calibration data. Sample code in lgdisplaytest.py return (dev, cfg) for dev in hidapi.enumerate(vendor_id=0x04d8, product_id=0xef7e): if dev.product_string == u'HoloPlay': hiddev, cfg = read_eeprom(dev) while True: # Keep reading the button bitmask r = hiddev.read(1) if r: byte = r[0] # Python 2 compatibility if isinstance(byte, str): byte = ord(byte) print('{:04b}'.format(byte))
def receivers(): """List all the Linux devices exposed by the UR attached to the machine.""" for receiver_usb_id in _RECEIVER_USB_IDS: for d in _hid.enumerate(*receiver_usb_id): yield d
def receivers(): """Enumerate all the receivers attached to the machine.""" for dev in _hid.enumerate(filter_receivers): yield dev
def wired_devices(): for device_usb_id in _WIRED_DEVICE_IDS: for dev in _hid.enumerate(device_usb_id): yield dev
sample_interval_minutes = 5 # TODO: read interval from settings or rather datasets print("Used HIDAPI lib: " + hidapi.lib) mode = "device" if (len(sys.argv) == 3): if (sys.argv[1] in ["dump", "read"]): mode = sys.argv[1] else: raise RuntimeError("Unknown command-line arguments.") data = None # TODO: in device mode, data should be supplied by a generator, lazily reading on-demand only if (mode in ["device", "dump"]): if "hidapi-libusb" in hidapi.lib: deviceInfo = next( hidapi.enumerate(vendor_id=vendor_id, product_id=product_id)) hd = hidapi.Device(info=deviceInfo) else: deviceInfo = next( hidapi.enumerate(vendor_id=vendor_id, product_id=product_id)) hd = hidapi.Device(info=deviceInfo) data = create_dump(hd) if (mode == "dump"): with open(sys.argv[2], 'wb') as f: f.write(data) else: data = open(sys.argv[2], 'rb').read() init_ok = int.from_bytes(get_field(data, "init_ok"), byteorder='big') if (init_ok != 0x55aa): raise RuntimeError(
def wired_devices(): """Enumerate all the USB-connected and Bluetooth devices attached to the machine.""" for dev in _hid.enumerate(filter_devices): yield dev
def receivers(): """List all the Linux devices exposed by the UR attached to the machine.""" for d in _hid.enumerate(*DEVICE_UNIFYING_RECEIVER): yield d for d in _hid.enumerate(*DEVICE_UNIFYING_RECEIVER_2): yield d