Exemple #1
0
 def __init__(self, serial=None, path=None):
     '''Constructor, the algorithm will connect to the first YKUSH found if a path or serial number is not provided'''
     self._devhandle = None
     self._firmware_major_version = None
     self._firmware_minor_version = None
     self._downstream_port_count = None
     #Alber3.2 add self._proudct_id
     self._proudct_id = None
     if path:
         # open the provided path
         if _usingHid:
             # blocking by default
             self._devhandle = hid.device()
             self._devhandle.open_path(path)
         else:
             # also blocking by default but ensure it is
             self._devhandle = hidapi.Device(path=path, blocking=True)
     else:
         # otherwise try to locate a device
         for device in hid_enumerate(0, 0):
             if device['vendor_id'] == YKUSH_USB_VID and device[
                     'product_id'] in YKUSH_USB_PID_LIST:
                 if serial is None or serial == device['serial_number']:
                     #Alber3.1 3.2 object attribute for YKUSHXS
                     self._proudct_id = device['product_id']
                     return self.__init__(path=device['path'])
     if self._devhandle is None:
         raise YKUSHNotFound()
Exemple #2
0
    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 __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"
         )
Exemple #4
0
    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)
Exemple #5
0
 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
Exemple #6
0
    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)
Exemple #7
0
    def _ensure_open(self) -> bool:
        try:
            if self._dev is None:
                self._dev = hidapi.Device(self._devinfo, blocking=False)
        except Exception as err:
            self.logger.exception("Failed to open connection", exc_info=err)
            return False

        return True
Exemple #8
0
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)
Exemple #9
0
    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
Exemple #10
0
 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")
Exemple #11
0
    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"
Exemple #12
0
def main():
    device = hidapi.Device(0x16c0, 0x27dc)
    # check serialNumber
    device.set_nonblocking(1)

    while True:
        # ret2 = device.get_feature_report(0, 8)
        ret2 = device.read(8)
        sys.stderr.write(repr(ret2) + '\r')
        ret = []
        for i, r in enumerate(ret2):
            if i >= 2:
                ret.append((~ord(r)) & 0xFF)
            else:
                ret.append(ord(r))
        # sys.stderr.write(' '.join(['%02x' % x for x in ret]) + ' | ' + ' '.join([bin(x, 8) for x in ret]) + '\r')
        # if ret[1] != 0x5A:
        #     print 'error'
        time.sleep(0.05)
Exemple #13
0
            print("No widget")
            exit(-1)
        self.updateTemp(21.22)
        self.show()

    def updateTemp(self, temperature):
        self.temperatureWidget.display(temperature)


#
vid = 0x1eaf  # Change it for your device
pid = 0x24  # Change it for your device

app = QtWidgets.QApplication(sys.argv)
#
bluepill = hidapi.Device(None, None, vid, pid, None, True)
if (bluepill is None):
    QMessageBox.about(None, "Error", "Sensor not found")
    exit(-1)
ui = tempUI()
#
rep = bytes(1)
length_id = 2
round = 0
while True:
    print("Read " + str(round))
    round = round + 1
    out = bluepill.read(8, 1000, True)
    if (out is not None):
        temp = out[0] * 1000 + out[1] * 100 + out[2] * 10 + out[3]
        temp = temp / 100.
Exemple #14
0
#!/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)
Exemple #15
0
# 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]))

    print("-")
Exemple #16
0
def open_joycons(lefts, rights):
    return ([hidapi.Device(d)
             for d in lefts], [hidapi.Device(d) for d in rights])
Exemple #17
0
 def Connect(self):
     self.dev = hid.Device(vendor_id=self.vendorID,
                           product_id=self.productID,
                           serial_number=self.serial)
Exemple #18
0
 def __init__(self):
     self.dev = hid.Device(vendor_id=self.vendorID,
                           product_id=self.productID,
                           serial_number=self.serial)
     self.state = 'stop'
Exemple #19
0
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)
    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(
            "Incorrect device ROM magic number (is %04x, should be 55aa). This software is not meant to be used with your device."