Beispiel #1
0
    def getAllConnectedTargets(vid, pid):
        """
        returns all the connected devices which matches HidApiUSB.vid/HidApiUSB.pid.
        returns an array of HidApiUSB (Interface) objects
        """

        devices = hid.enumerate(vid, pid)

        if not devices:
            logging.debug("No USB device connected")
            return

        targets = []

        for deviceInfo in devices:
            try:
                dev = hid.device(vendor_id=vid, product_id=pid, path=deviceInfo['path'])
            except IOError:
                logging.debug("Failed to open USB device")
                return

            # Create the USB interface object for this device.
            new_target = HidApiUSB()
            new_target.vendor_name = deviceInfo['manufacturer_string']
            new_target.product_name = deviceInfo['product_string']
            new_target.vid = deviceInfo['vendor_id']
            new_target.pid = deviceInfo['product_id']
            new_target.device = dev

            targets.append(new_target)

        return targets
Beispiel #2
0
    def _scan_devices_with_hid(self):
        try:
            import hid
        except ImportError:
            return []

        with self.hid_lock:
            hid_list = hid.enumerate(0, 0)

        devices = []
        for d in hid_list:
            product_key = (d['vendor_id'], d['product_id'])
            if product_key in self.recognised_hardware:
                # Older versions of hid don't provide interface_number
                interface_number = d.get('interface_number', -1)
                usage_page = d['usage_page']
                id_ = d['serial_number']
                if len(id_) == 0:
                    id_ = str(d['path'])
                id_ += str(interface_number) + str(usage_page)
                devices.append(Device(path=d['path'],
                                      interface_number=interface_number,
                                      id_=id_,
                                      product_key=product_key,
                                      usage_page=usage_page,
                                      transport_ui_string='hid'))
        return devices
Beispiel #3
0
def getDongle(debug=False):
	dev = None
	hidDevicePath = None
	for hidDevice in hid.enumerate(0, 0):
		if hidDevice['vendor_id'] == 0x2581 and hidDevice['product_id'] == 0x2b7c:
			hidDevicePath = hidDevice['path']
		if hidDevice['vendor_id'] == 0x2581 and hidDevice['product_id'] == 0x1807:
			hidDevicePath = hidDevice['path']
	if hidDevicePath is not None:
		dev = hid.device()
		dev.open_path(hidDevicePath)
		dev.set_nonblocking(True)
		return HIDDongleHIDAPI(dev, debug)
	if WINUSB:
		dev = usb.core.find(idVendor=0x2581, idProduct=0x1b7c) # core application, WinUSB
		if dev is not None:
			return WinUSBDongle(dev, debug)
		dev = usb.core.find(idVendor=0x2581, idProduct=0x1808) # bootloader, WinUSB
		if dev is not None:
			return WinUSBDongle(dev, debug)
		dev = usb.core.find(idVendor=0x2581, idProduct=0x2b7c) # core application, Generic HID
		if dev is not None:
			return HIDDongle(dev, debug)
		dev = usb.core.find(idVendor=0x2581, idProduct=0x1807) # bootloader, Generic HID
		if dev is not None:
			return HIDDongle(dev, debug)
	raise BTChipException("No dongle found")
Beispiel #4
0
def getDongles(dev_class=None, scrambleKey="", debug=False):
    dev_class = dev_class or HIDDevice
    devices = []
    for d in hid.enumerate(0, 0):
        usage_page = d['usage_page']
        if usage_page == 0xf1d0 and d['usage'] == 1:
            devices.append(U2FTunnelDongle(dev_class(d['path']),scrambleKey, debug=debug))
        # Usage page doesn't work on Linux
        # well known devices
        elif (d['vendor_id'], d['product_id']) in DEVICES:
            device = HIDDevice(d['path'])
            try:
                device.open()
                device.close()
                devices.append(U2FTunnelDongle(dev_class(d['path']),scrambleKey, debug=debug))
            except (exc.DeviceError, IOError, OSError):
                pass
        # unknown devices
        else:
            device = HIDDevice(d['path'])
            try:
                device.open()
                # try a ping command to ensure a FIDO device, else timeout (BEST here, modulate the timeout, 2 seconds is way too big)
                device.ping()
                device.close()
                devices.append(U2FTunnelDongle(dev_class(d['path']),scrambleKey, debug=debug))
            except (exc.DeviceError, IOError, OSError):
                pass
    return devices
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("vid_pid_string", type=str, help="This is the same VID:PID string lsusb outputs. Example: 04b4:f13b")
    parser.add_argument("firmware_file", type=str, help="The name of the *.cyacd file you want to flash.")
    args = vars(parser.parse_args())

    vid_pid_string = args["vid_pid_string"].split(':')

    vid = int(vid_pid_string[0], 16)
    pid = int(vid_pid_string[1], 16)

    # Search for a device with matching identifiers
    found = False
    for enumerated in hid.enumerate():
        if enumerated["vendor_id"] == vid and enumerated["product_id"] == pid:
            found = True
            break

    if found:
        # Connect to the device's bootloader
        bootloader = Bootloader(vid, pid)
        bootloader.enter_bootloader()

        # Load the firmware file
        firmware = Cyacd(open(args["firmware_file"], 'r'))
        firmware.parse()

        # Make sure the firmware is being flashed to the correct chip
        if (bootloader.jtag_id == firmware.silicon_id) and (bootloader.device_revision == firmware.silicon_revision):
            bootloader.flash(firmware)

        bootloader.exit_bootloader()
    else:
        sys.stderr.write("Device not found!\n")
        sys.exit(1)
Beispiel #6
0
    def scan_devices(self, handler):
        # All currently supported hardware libraries use hid, so we
        # assume it here.  This can be easily abstracted if necessary.
        # Note this import must be local so those without hardware
        # wallet libraries are not affected.
        import hid

        self.print_error("scanning devices...")

        # First see what's connected that we know about
        devices = []
        for d in hid.enumerate(0, 0):
            product_key = (d['vendor_id'], d['product_id'])
            if product_key in self.recognised_hardware:
                devices.append(Device(d['path'], d['interface_number'],
                                      d['serial_number'], product_key))

        # Now find out what was disconnected
        pairs = [(dev.path, dev.id_) for dev in devices]
        disconnected_ids = []
        with self.lock:
            connected = {}
            for client, pair in self.clients.items():
                if pair in pairs:
                    connected[client] = pair
                else:
                    disconnected_ids.append(pair[1])
            self.clients = connected

        # Unpair disconnected devices
        for id_ in disconnected_ids:
            self.unpair_id(id_)

        return devices
Beispiel #7
0
    def openDevice(self, serialNumber=None):
        """Open a USB-ADC2 device.

        If serialNumber is not None, the device with the given serial number is opened,
        otherwise the serial number supplied to the constructor is used.

        Args:
            serialNumber (Optional[int]): Serial number of the ADC to open. If None is given,
                                          the serial number supplied to the constructor is used.

        Raises:
            IOError: If the USB-ADC2 with the requested serial number could not be found.
        """
        if serialNumber is not None:
            self.serialNumber = serialNumber

        hidEnum = hid.enumerate()
        self.path = None
        for dev in hidEnum:
            if dev['vendor_id'] == self.vendorId and dev['product_id'] == self.productId:
                if int(dev['serial_number'], 16) == self.serialNumber:
                    self.path = dev['path']

        if self.path is None:
            raise IOError('Could not find ADC with serial number {}'.format(self.serialNumber))

        self.handle = hid.device()
        self.handle.open_path(self.path)
        self.resetDevice()
    def enumerate(cls):
        """
        Return a list of available TREZOR devices.
        """
        devices = {}
        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']
            path = d['path']

            # HIDAPI on Mac cannot detect correct HID interfaces, so device with
            # DebugLink doesn't work on Mac...
            if devices.get(serial_number) != None and devices[serial_number][0] == path:
                raise Exception("Two devices with the same path and S/N found. This is Mac, right? :-/")

            if (vendor_id, product_id) in DEVICE_IDS:
                devices.setdefault(serial_number, [None, None])
                if interface_number == 0 or interface_number == -1: # normal link
                    devices[serial_number][0] = path
                elif interface_number == 1: # debug link
                    devices[serial_number][1] = path
                else:
                    raise Exception("Unknown USB interface number: %d" % interface_number)

        # List of two-tuples (path_normal, path_debuglink)
        return devices.values()
Beispiel #9
0
	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 cls.USB_MFR.startswith(btn["manufacturer_string"].replace('\x00', ''))
			 and cls.USB_PROD.startswith(btn["product_string"].replace('\x00', ''))
			]
Beispiel #10
0
def find_device():
    while True:
        for device in hid.enumerate(0, 0):
            id = (device['vendor_id'], device['product_id'])
            if id in VALID_IDS:
                return id
        time.sleep(0.1)
Beispiel #11
0
def getDongle(path=None, dev_class=None, scrambleKey="", debug=False):
  # if path is none, then use the first device
  dev_class = dev_class or HIDDevice
  devices = []
  for d in hid.enumerate(0, 0):
    if path is None or d['path'] == path:
      usage_page = d['usage_page']
      if usage_page == 0xf1d0 and d['usage'] == 1:
          return U2FTunnelDongle(dev_class(d['path']),scrambleKey, debug=debug)
      # Usage page doesn't work on Linux
      # well known devices
      elif (d['vendor_id'], d['product_id']) in DEVICES and ('interface_number' not in d or d['interface_number'] == 1):
          #print d
          device = HIDDevice(d['path'])
          try:
              device.open()
              device.close()
              return U2FTunnelDongle(dev_class(d['path']),scrambleKey, debug=debug)
          except (exc.DeviceError, IOError, OSError):
              traceback.print_exc()
              pass
      # unknown devices
      # else:
      #     device = HIDDevice(d['path'])
      #     try:
      #         device.open()
      #         # try a ping command to ensure a FIDO device, else timeout (BEST here, modulate the timeout, 2 seconds is way too big)
      #         device.ping()
      #         device.close()
      #         return U2FTunnelDongle(dev_class(d['path']),scrambleKey, debug=debug)
      #     except (exc.DeviceError, IOError, OSError):
      #         traceback.print_exc()
      #         pass
  raise CommException("No dongle found")
    def run(self):
        # 首先上报设备数据
        for device_id in self.devices_info_dict:
            device_info = self.devices_info_dict[device_id]
            device_msg = {
                "device_id": device_info["device_id"],
                "device_type": device_info["device_type"],
                "device_addr": device_info["device_addr"],
                "device_port": device_info["device_port"],
                "protocol": self.protocol.protocol_type,
                "data": ""
            }
            self.mqtt_client.publish_data(device_msg)

        # 打印hid设备信息
        for d in hid.enumerate(0, 0):
            keys = d.keys()
            keys.sort()
            for key in keys:
                logger.debug("%s : %s" % (key, d[key]))
            logger.debug("")

        # 打开设备
        try:
            hid_device = hid.device(self.vendor_id, self.product_id)
        except Exception, e:
            logger.error("hid.device exception: %r." % e)
            return
Beispiel #13
0
 def digibox_is_connected(self):
     d = hid.enumerate(0x03eb, 0x2402)
     if not d:
         return False
     else:
         #hid.free_enumeration(d)
         return True
def list_devices():
    # TODO: Check the usage page to determine what is a U2F device
    devices = []
    for d in hid.enumerate(0, 0):
        if (d['vendor_id'], d['product_id']) in DEVICES:
            devices.append(HIDDevice(d['path']))
    return devices
Beispiel #15
0
def do_list():
    for d in hid.enumerate(0x10c4, 0x8acf):
        keys = d.keys()
        keys.sort()
        for key in keys:
            print("%s : %s" % (key, d[key]))
    print('')
Beispiel #16
0
def list():
    '''Lists all the Delcom USBLMP 904x devices'''
    for d in hid.enumerate(vendor_id, product_id):
        keys = d.keys()
        keys.sort()
        for key in keys:
            print "%s : %s" % (key, d[key])
        print ""
Beispiel #17
0
def usb_hid_path(serial_number):
    """Get a USB HID device system path based on the serial number."""
    if not CYTHON_HIDAPI_PRESENT:
        return None
    for device_info in hid.enumerate():  # pylint: disable=no-member
        if device_info.get('serial_number') == serial_number:  # pylint: disable=not-callable
            return device_info['path']
    return None
 def is_connected(self):
     """
     Check if the device is still connected.
     """
     for d in hid.enumerate(0, 0):
         if d['path'] == self.device:
             return True
     return False
Beispiel #19
0
def HIDDeviceList():
    usbPathList = []
    # Enumarate HID devices
    for d in hid.enumerate(0, 0):
        keys = d.keys()
        keys.sort()
        if d["vendor_id"] == USB_VENDOR_ID:
           usbPathList.append(d["path"])
    return usbPathList
Beispiel #20
0
 def _find_devs(self):
     services = {}
     for d in hid.enumerate():
         if 'product_string' in d and d['product_string'].startswith('USBRelay'):
             ports = int(d['product_string'][8:])
             d.update({'ports': ports})
             d.update({'relays': range(1,ports + 1)})
             services.update({ d['path']: d })
     return services
def get_hid_device():
    valid_hid_devices = hid.enumerate(vendor_id=0x03EB,
                                      product_id=0x2067)

    if len(valid_hid_devices) is 0:
        return None
    else:
        hid_device = hid.device()
        hid_device.open_path(valid_hid_devices[0]['path'])
        return hid_device
def get_hid_device_handle():
    all_hid_devices = hid.enumerate()

    lufa_hid_devices = [d for d in all_hid_devices if d['vendor_id'] == 0x1209 and d['product_id'] == 0x8473]

    if len(lufa_hid_devices) is 0:
        return None

    device_handle = hid.device()
    device_handle.open_path(lufa_hid_devices[0]['path'])
    return device_handle
Beispiel #23
0
    def enumerate(cls):
        devices = []
        for d in hid.enumerate(0, 0):
            vendor_id = d.get('vendor_id')
            product_id = d.get('product_id')
            path = d.get('path')

            if (vendor_id, product_id) in DEVICE_IDS and path.endswith(':00'):
                devices.append(path)
                
        return devices
 def enumerate(cls):
     devices = []
     for d in hid.enumerate(0, 0):
         vendor_id = d.get('vendor_id')
         product_id = d.get('product_id')
         serial_number = d.get('serial_number')
         
         if (vendor_id, product_id) in DEVICE_IDS:
             devices.append("0x%04x:0x%04x:%s" % (vendor_id, product_id, serial_number))
             
     return devices
Beispiel #25
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)
 def getDeviceList():
     devices = []
     for d in hid.enumerate(VStrokerDevice.VID, VStrokerDevice.PID):
         # The device actually uses TI's VID, meaning the 55a5 PID is
         # probably for their CC2500 dongle. Therefore, make sure we have
         # check the product string is set, so we don't just access any ol'
         # CC2500 dongle. Once I actually /have/ a CC2500 dongle this may
         # change.
         if d["product_string"] != "Vstroker":
             continue
         devices.append(d["path"])
     return devices
Beispiel #27
0
 def getDeviceList():
     devices = []
     for d in hid.enumerate(RealTouchDevice.VID, RealTouchDevice.PID):
         # Check the manufacturer string
         # if d["manufacturer_string"] != u"AEBN":
         #     continue
         if "v1" in d["product_string"]:
             # TODO: Throw on this?
             print "Warning, v1 device connected! Please update Realtouch Firmware to v2! (Available with v2 Platform Agent)"
             continue
         devices.append(d["path"])
     return devices
Beispiel #28
0
 def __usb_scan(self):
     """
     Diagnostic scan of available USB devices.
     """
     
     for d in hid.enumerate(0, 0):
         keys = d.keys()
         
         for key in keys:
             print ("%s : %s" % (key, d[key]))
             
         print ("")
def path_to_transport(path):
    try:
        device = [ d for d in hid.enumerate(0, 0) if d['path'] == path ][0]
    except IndexError:
        raise ConnectionError("Connection failed")

    # VID/PID found, let's find proper transport
    try:
        transport = DEVICE_TRANSPORTS[(device['vendor_id'], device['product_id'])]
    except IndexError:
        raise Exception("Unknown transport for VID:PID %04x:%04x" % (vid, pid))

    return transport
Beispiel #30
0
 def enumerate(cls, debug: bool = False) -> Iterable["HidTransport"]:
     devices = []
     for dev in hid.enumerate(0, 0):
         usb_id = (dev["vendor_id"], dev["product_id"])
         if usb_id != DEV_TREZOR1:
             continue
         if debug:
             if not is_debuglink(dev):
                 continue
         else:
             if not is_wirelink(dev):
                 continue
         devices.append(HidTransport(dev))
     return devices
#!/usr/bin/env python3

import hid
import binascii
import random
import time
import colorsys
import numpy as np

h = hid.enumerate()

#print(h)

my_idx = None
for j in range(len(h)):
    #    print(h[j])
    if ((h[j]['interface_number'] == 2) &
        (h[j]['product_string'] == 'N-KEY Device')):
        my_idx = j

#print(h[my_idx]['path'])

d = hid.Device(path=h[my_idx]['path'])

#commandstr_rainbow = binascii.unhexlify('5db30003000000f50000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
#commandstr_breathe = binascii.unhexlify('5db30001ff0000f5000100ff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
#commandstr2 = binascii.unhexlify('5db50000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
#commandstr3 = binascii.unhexlify('5db40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
#commandstr4 = binascii.unhexlify('5db50000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')

#d.write(commandstr_rainbow)
Beispiel #32
0
import hid
import time
import os

vid = 0xFEED  # Change it for your device
pid = 0x1307  # Change it for your device

interfaces = hid.enumerate(vid, pid)
filtered = [x for x in interfaces if x["interface_number"] == 1]
path = filtered[0]["path"]
# print(path)

with hid.Device(path=path) as h:
    print(f'Device manufacturer: {h.manufacturer}')
    print(f'Product: {h.product}')
    print(f'Serial Number: {h.serial}')
    while True:
        msg = h.read(7).decode()

        if msg.startswith("LAYER:"):
            layer = int(msg[6])
            if layer == 3:
                os.system(
                    "xinput --set-prop \"Primax Kensington Eagle Trackball\" 276 0 0"
                )
            else:
                os.system(
                    "xinput --set-prop \"Primax Kensington Eagle Trackball\" 276 1 0"
                )
        else:
            print(msg)
Beispiel #33
0
				self.sock.send(self.queryStatus())
				continue
			if data[0] == 0x68:
				self.received+=1
				self.sent+=1
				data[1] = self.exchangeHandler(data[1], self)
				self.sock.send(data)
				self.sock.send(self.queryStatus())
				continue
			print("Unknown command " + hex(data[0]))
			print(data)
			
	def setExchangeHandler(self, ex):
		self.exchangeHandler = ex

paths = [t['path'] for t in hid.enumerate(5824, 1158) if t['usage'] == 512]
teensy = hid.device()
teensy.open_path(paths[0])
#teensy.set_nonblocking(1)
buf = bytearray([0]*64)

def myHandler(data, obj):
    buf[0] = data
    teensy.write(buf)
    return teensy.read(64)[0]

if __name__ == "__main__":
    try:
        print("[!] Connecting to 127.0.0.1:8765...")
        link = BGBLinkCable('127.0.0.1',8765)
        link.setExchangeHandler(myHandler)
Beispiel #34
0
def main():

    # for gpio
    gpio_val = 0x00

    args = get_args()

    v_id = args.vid
    p_id = args.pid
    p_name = args.name
    gpio_no = args.gpio

    if args.hi:
        gpio_val = 0x01
    elif args.lo:
        gpio_val = 0x00

    # search hid device
    print('Hid device list VID/PID = 0x{0:04x}/0x{1:04x}'.format(v_id, p_id))
    print('---------------------------------------')

    index = 0  # numbering devices
    target_dict = []  # target list
    for device_dict in hid.enumerate(vendor_id=v_id, product_id=p_id):
        if device_dict['interface_number'] >= 0:
            print("No.{0:d} : {1:s}".format(index,
                                            device_dict['product_string']))
            d = {
                'no': index,
                'product_string': device_dict['product_string'],
                'path': device_dict['path'],
                'vendor_id': device_dict['vendor_id'],
                'product_id': device_dict['product_id']
            }
            target_dict.append(d)
            index += 1
    print()

    if len(target_dict) == 0:
        print('no target device')
        sys.exit(0)

    if args.no != None and args.no >= index:
        print('none target no.{0:d}'.format(args.no))
        sys.exit(0)

    # setup product string and gpio setting
    if args.setup:
        if args.no != None:
            ret = setup(path=target_dict[args.no]['path'], p_name=p_name)
            if ret == 0:
                print('setup successed')
            else:
                print('setup failed')
        else:
            print('use option \'--no\' to set device no.')

    else:
        # search target to control
        no = 0
        dic = dict()
        for d in target_dict:
            if args.no != None:
                if d['product_string'] == p_name and args.no == no:
                    dic = d
                    break
            else:
                if d['product_string'] == p_name:
                    dic = d
                    break
            no += 1

        if len(dic) == 0:
            if args.no != None:
                print('not found \'{0:s}\':No.{1:d}'.format(p_name, args.no))
            else:
                print('not found \'{0:s}\''.format(p_name))
            sys.exit(0)

        if args.wakeup:
            print('wakeup')
            ret = gpioctrl(path=dic['path'], no=0x00, val=0x01)
            if ret != 0:
                print('error wakeup')
                sys.exit(0)
            time.sleep(0.5)
            ret = gpioctrl(path=dic['path'], no=0x00, val=0x00)
            if ret != 0:
                print('error wakeup')
                sys.exit(0)

        elif args.shutdown:
            print('shutdown')
            ret = gpioctrl(path=dic['path'], no=0x01, val=0x01)
            if ret != 0:
                print('error shutdown')
                sys.exit(0)
            time.sleep(0.5)
            ret = gpioctrl(path=dic['path'], no=0x01, val=0x00)
            if ret != 0:
                print('error shutdown')
                sys.exit(0)

        elif args.hi or args.lo:
            print('gpio ctrl')
            ret = gpioctrl(path=dic['path'], no=gpio_no, val=gpio_val)
            if ret != 0:
                print('error control gpio')
        else:
            print('set option \'-h\' for usage')
Beispiel #35
0
 def enumerate(self):
     devices = [d for d in hid.enumerate(self.USB_VID, self.USB_PID)]
     return devices
Beispiel #36
0
 def __init__(self,VID = 0x04D8,PID = 0x00DE,devnum = 0):
     self.mcp2210 = hid.device()
     self.mcp2210.open_path(hid.enumerate(VID, PID)[devnum]["path"])
Beispiel #37
0
def printDevices():
    print(hid.enumerate())
Beispiel #38
0
# Install python3 HID package https://pypi.org/project/hid/
import hid

USB_VID = 0xcafe

print("Openning HID device with VID = 0x%X" % USB_VID)

for dict in hid.enumerate(USB_VID):
    print(dict)
    dev = hid.Device(dict['vendor_id'], dict['product_id'])
    if dev:
        while True:
            # Get input from console and encode to UTF8 for array of chars.
            # hid generic inout is single report therefore by HIDAPI requirement
            # it must be preceeded with 0x00 as dummy reportID
            str_out = b'\x00'
            str_out += input("Send text to HID Device : ").encode('utf-8')
            dev.write(str_out)
            str_in = dev.read(64)
            print("Received from HID Device:", str_in, '\n')
Beispiel #39
0
import hid
# enumerate USB devices

for d in hid.enumerate():
    if d['usage_page'] == 65329:
        path = d['path']

# try opening a device, then perform write and read

try:
    print("Opening the device")

    h = hid.device()
    h.open_path(path)  # TREZOR VendorID/ProductID

    print("Manufacturer: %s" % h.get_manufacturer_string())
    print("Product: %s" % h.get_product_string())
    print("Serial No: %s" % h.get_serial_number_string())

    while True:
        d = h.read(64, 25)
        if d:
            text = ""
            for x in d:
                text += chr(x)
            print(text)
        else:
            pass

    h.close()
Beispiel #40
0
        print "l: %r" % lightness
        final_color_rgb = colorsys.hls_to_rgb(temp_color[0], lightness,
                                              temp_color[2])
        final_color = Color(int(remap(final_color_rgb[0], 0, 1, 0, 255)),
                            int(remap(final_color_rgb[1], 0, 1, 0, 255)),
                            int(remap(final_color_rgb[2], 0, 1, 0, 255)))

        for illuminator in illuminators:
            illuminator.set(final_color)

        time.sleep(0.001)


#-------------------------LIST USB DEVICES--------------------------------
illuminators = []
for d in hid.enumerate(0, 0):
    keys = d.keys()
    keys.sort()
    # for key in keys:
    #     print "found: %s : %s" % (key, d[key])
    if d["product_id"] == product_id:
        illuminators.append(Illuminator(d["path"]))

if len(illuminators) > 2 or len(illuminators) == 0:
    print "unexpected amount of light"
    exit(1)
else:
    print "succesfully lit illuminator(s): %r" % illuminators

##########################
#	OSC
# Install python3 HID package https://pypi.org/project/hid/
import hid

# default is TinyUSB (0xcafe), Adafruit (0x239a), RaspberryPi (0x2e8a), Espressif (0x303a) VID
USB_VID = (0xcafe, 0x239a, 0x2e8a, 0x303a)

print("VID list: " + ", ".join('%02x' % v for v in USB_VID))

for vid in USB_VID:
    for dict in hid.enumerate(vid):
        print(dict)
        dev = hid.Device(dict['vendor_id'], dict['product_id'])
        if dev:
            while True:
                # Get input from console and encode to UTF8 for array of chars.
                # hid generic inout is single report therefore by HIDAPI requirement
                # it must be preceeded with 0x00 as dummy reportID
                str_out = b'\x00'
                str_out += input("Send text to HID Device : ").encode('utf-8')
                dev.write(str_out)
                str_in = dev.read(64)
                print("Received from HID Device:", str_in, '\n')
Beispiel #42
0
import os
import hid


# TODO: listen for when devices are connected
# TODO: loop through interfaces and ask them some specific and make kb return something

d = hid.Device(
    path=next(
        dev
        for dev in hid.enumerate(0xFEED, 0x1307)
        if dev['interface_number'] == 1
    )['path']
)


while True:
    msg = ((d.read(8).decode()))
    if msg.startswith('VOL:'):
        split = msg.split(':')
        y = int(split[-1])
        if y > 0:
            os.system(f'pactl set-sink-volume @DEFAULT_SINK@ {y:+}%')
        elif y < 0:
            os.system(f'pactl set-sink-volume @DEFAULT_SINK@ {y:+}%')

Beispiel #43
0
#!/usr/bin/env python3

import hid

REPORT_ID = 1
VENDOR_ID = 0x27b8
PRODUCT_ID = 0x01ed

devs = hid.enumerate( VENDOR_ID, PRODUCT_ID)
#print(devs)
serials = []
for d in devs:
    print(d)
    serials.append(d.get('serial_number'))

serialz = map(lambda d:d.get('serial_number'), devs)

serial_number = None

#devs = map(lambda d: print(d), devs)
print("serials:", serials)
print("serialz:", serialz)

hidraw = hid.device( VENDOR_ID, PRODUCT_ID, serial_number )
hidraw.open( VENDOR_ID, PRODUCT_ID, serial_number )
#hidraw.send_feature_report([0x02, 0x10, 0x00,0x00,0x00,0x00,0x00,0x00])
featureReport = [REPORT_ID, 99, 255, 0, 255, 0, 11, 0, 0];
hidraw.send_feature_report( featureReport )
Beispiel #44
0
def run_hid_process():

    paths = []

    for d in hid.enumerate(VENDOR_ID, PRODUCT_ID):
        if int(d['interface_number']) == 2:
            paths.append(d['path'])
            print(d['path'])
        # keys = list(d.keys())
        # keys.sort()
        # print(d['path'])
        # for key in keys:
        #     print("%s : %s" % (key, d[key]))
        # print()
    #

    # device = hid.device()
    # # device.open(VENDOR_ID, PRODUCT_ID)
    #
    #
    # print(dir(device))
    # print(device)
    #
    # device.close()
    #
    # import sys
    # sys.exit()

    devices = [hid.device(), hid.device()]
    # devices = [hid.device()]
    devices[0].open_path(paths[0])
    devices[1].open_path(paths[1])

    for device in devices:
        # device = hid.device()
        # device.open(VENDOR_ID, PRODUCT_ID)
        print('Connected to ecam {}\n'.format(PRODUCT_ID))

        timeout = 0

        # First just read LED Control status, as a test.

        g_out_packet_buf = [0, 0]
        g_out_packet_buf[0] = CAMERA_CONTROL_FSCAM_CU135
        g_out_packet_buf[1] = GET_LED_CONTROL_FSCAM_CU135

        device.write(g_out_packet_buf)
        time.sleep(0.5)

        data = device.read(BUFFER_LENGTH, timeout)
        print(data)

        # if data[6]==GET_SUCCESS:
        if data[0] == CAMERA_CONTROL_FSCAM_CU135 and data[
                1] == GET_LED_CONTROL_FSCAM_CU135 and data[6] == GET_SUCCESS:
            ledstatus = data[2]
            powerctl = data[3]
            stream = data[4]
            trigger = data[5]
            print("ledstatus {}, powerctl {}, stream {}, trigger {}".format(
                ledstatus, powerctl, stream, trigger))
        else:
            print("GET_FAILED")

        # Now set LED control to indicate when hardware trigger has activated.

        g_out_packet_buf = [0, 0, 0, 0, 0, 0]
        g_out_packet_buf[
            0] = CAMERA_CONTROL_FSCAM_CU135  # /* set camera control code */
        g_out_packet_buf[
            1] = SET_LED_CONTROL_FSCAM_CU135  # /* set led control code */
        g_out_packet_buf[2] = ENABLE_LED_CONTROL_FSCAM_CU135
        g_out_packet_buf[3] = DISABLE_STREAMING_CONTROL_FSCAM_CU135
        g_out_packet_buf[4] = ENABLE_TRIGGERACK_CONTROL_FSCAM_CU135
        g_out_packet_buf[5] = DISABLE_POWERON_CONTROL_FSCAM_CU135
        device.write(g_out_packet_buf)
        time.sleep(0.5)

        data = device.read(BUFFER_LENGTH, timeout)
        #print(data)

        # Finally set trigger control.

        g_out_packet_buf = [0, 0, 0, 0]
        g_out_packet_buf[
            1] = CAMERA_CONTROL_FSCAM_CU135  # /* set camera control code */
        g_out_packet_buf[
            2] = SET_STREAM_MODE_FSCAM_CU135  # /* set stream mode code */
        g_out_packet_buf[
            3] = STREAM_HARDWARE_TRIGGER  # /* actual stream mode */
        # g_out_packet_buf[3] = STREAM_MASTER_CONTINUOUS  # NOTE: Uncomment this to select auto trigger.

        device.write(g_out_packet_buf)

        time.sleep(2)

        data = device.read(BUFFER_LENGTH, timeout)
        if data[0] == CAMERA_CONTROL_FSCAM_CU135 and data[
                1] == SET_STREAM_MODE_FSCAM_CU135 and data[6] == SET_SUCCESS:
            print("SUCCESS")
        else:
            print("FAILED")

        time.sleep(2)

    print("RUNNING HID FRAME GRAB")
    while True:
        sample_time = time.time()
        for device in devices:
            # In hardware trigger mode we must continually request the next frame.
            g_out_packet_buf[
                1] = CAMERA_CONTROL_FSCAM_CU135  # // camera control id
            g_out_packet_buf[2] = GRAB_PREVIEW_FRAME  # // query frame
            g_out_packet_buf[
                3] = QUERY_NEXT_FRAME  # // query next frame - 0x01 , query prev frame - 0x02
            device.write(g_out_packet_buf)
            time.sleep(0.001)
            # data = device.read(BUFFER_LENGTH, timeout)
            # if data[6] == GET_SUCCESS and device == devices[0]:
            #     print(time.time() - sample_time)
            #     sample_time = time.time()
            #print(time.time())
        time.sleep(0.001)
Beispiel #45
0
import hid

for device in hid.enumerate(0, 0):
    prod = device['product_string']
    print(prod)
    if "Polar" in prod:
        vid = device["vendor_id"]
        pid = device["product_id"]

polar = hid.Device(vid, pid)

polar.open()

# hogehoge

polar.close()
Beispiel #46
0
 def hid_enumerate():
     with self.hid_lock:
         return hid.enumerate(0, 0)
Beispiel #47
0
 def __init__(self, VID=0x04D8, PID=0x00DD, dev=0):
     self.mcp2221 = hid.device()
     self.mcp2221.open_path(hid.enumerate(VID, PID)[dev]["path"])
     self.VID = VID
     self.PID = PID
Beispiel #48
0
    def id(self, ) -> Optional[str]:  # pylint: disable=invalid-name,too-many-branches,too-many-return-statements
        """Return a unique id for the detected chip, if any."""
        # There are some times we want to trick the platform detection
        # say if a raspberry pi doesn't have the right ID, or for testing

        # Caching
        if self._chip_id:
            return self._chip_id

        if getattr(os, "environ", None) is not None:
            try:
                return os.environ["BLINKA_FORCECHIP"]
            except KeyError:  # no forced chip, continue with testing!
                pass

            # Special cases controlled by environment var
            if os.environ.get("BLINKA_FT232H"):
                from pyftdi.usbtools import UsbTools

                # look for it based on PID/VID
                count = len(UsbTools.find_all([(0x0403, 0x6014)]))
                if count == 0:
                    raise RuntimeError("BLINKA_FT232H environment variable " +
                                       "set, but no FT232H device found")
                self._chip_id = chips.FT232H
                return self._chip_id
            if os.environ.get("BLINKA_FT2232H"):
                from pyftdi.usbtools import UsbTools

                # look for it based on PID/VID
                count = len(UsbTools.find_all([(0x0403, 0x6010)]))
                if count == 0:
                    raise RuntimeError("BLINKA_FT2232H environment variable " +
                                       "set, but no FT2232H device found")
                self._chip_id = chips.FT2232H
                return self._chip_id
            if os.environ.get("BLINKA_MCP2221"):
                import hid

                # look for it based on PID/VID
                for dev in hid.enumerate():
                    if dev["vendor_id"] == 0x04D8 and dev[
                            "product_id"] == 0x00DD:
                        self._chip_id = chips.MCP2221
                        return self._chip_id
                raise RuntimeError("BLINKA_MCP2221 environment variable " +
                                   "set, but no MCP2221 device found")
            if os.environ.get("BLINKA_U2IF"):
                import hid

                # look for it based on PID/VID
                for dev in hid.enumerate():
                    vendor = dev["vendor_id"]
                    product = dev["product_id"]
                    # NOTE: If any products are added here, they need added
                    # to _rp2040_u2if_id() in board.py as well.
                    if (
                            # Raspberry Pi Pico
                            vendor == 0xCAFE and product == 0x4005
                    ) or (
                            # Feather RP2040
                            # Itsy Bitsy RP2040
                            # QT Py RP2040
                            # QT2040 Trinkey
                            # MacroPad RP2040
                            vendor == 0x239A and product
                            in (0x00F1, 0x00FD, 0x00F7, 0x0109, 0x0107)):
                        self._chip_id = chips.RP2040_U2IF
                        return self._chip_id
                raise RuntimeError("BLINKA_U2IF environment variable " +
                                   "set, but no compatible device found")
            if os.environ.get("BLINKA_GREATFET"):
                import usb

                if usb.core.find(idVendor=0x1D50,
                                 idProduct=0x60E6) is not None:
                    self._chip_id = chips.LPC4330
                    return self._chip_id
                raise RuntimeError("BLINKA_GREATFET environment variable " +
                                   "set, but no GreatFET device found")
            if os.environ.get("BLINKA_NOVA"):
                self._chip_id = chips.BINHO
                return self._chip_id

        platform = sys.platform
        if platform in ("linux", "linux2"):
            self._chip_id = self._linux_id()
            return self._chip_id
        if platform == "esp8266":
            self._chip_id = chips.ESP8266
            return self._chip_id
        if platform == "samd21":
            self._chip_id = chips.SAMD21
            return self._chip_id
        if platform == "pyboard":
            self._chip_id = chips.STM32F405
            return self._chip_id
        if platform == "rp2":
            self._chip_id = chips.RP2040
            return self._chip_id
        # nothing found!
        return None
Beispiel #49
0
"""Driver for TrippLite UPS battery backups."""
import hid

vendor_id = 0x09ae

# These change on each call to `hid.enumerate` so must be cached.
battery_paths = [
    device['path'].decode() for device in hid.enumerate()
    if device['vendor_id'] == vendor_id
]

structure = {
    'config': {
        'voltage': {
            'address': 48,
            'bytes': 1,
            'format': 'i'
        },
        'frequency': {
            'address': 2,
            'bytes': 1,
            'format': 'i'
        },
        'power': {
            'address': 3,
            'bytes': 2,
            'format': 'i'
        }
    },
    'status': {
        'address':
Beispiel #50
0
import hid
import time

print hid.enumerate(0, 0)

h = hid.device(0x461, 0x20)

print h.get_manufacturer_string()
print h.get_product_string()
print h.get_serial_number_string()

h.set_nonblocking(1)

for k in range(10):
    for i in [0, 1]:
        for j in [0, 1]:
            h.write([0x80, i, j])
            d = h.read(5)
            if d:
                print d
            time.sleep(0.05)



Beispiel #51
0
###


import hid
import time
import psutil
import GPUtil
import datetime

vendor_id  = 0x444E
product_id = 0x4450

usage_page = 0xFF60
usage      = 0x61

device_interfaces = hid.enumerate(vendor_id, product_id)
raw_hid_interfaces = [i for i in device_interfaces if i['usage_page'] == usage_page and i['usage'] == usage]

if len(raw_hid_interfaces) == 0:
    print('Couldnt find any interfaces')
    exit()

interface = hid.device()
interface.open_path(raw_hid_interfaces[0]['path'])
print("Manufacturer: %s" % interface.get_manufacturer_string())
print("Product: %s" % interface.get_product_string())
time.sleep(0.05)
while True:
    time.sleep(0.75)
    cpufreq = psutil.cpu_freq()
    currFreq = int(cpufreq.current)
def get_all_devices():
    """ Get all Universal Serial Bus (USB) Human Interface Devices (HID) """

    devices = hid.enumerate(0, 0)

    return devices
Beispiel #53
0
 def __init__(self, idVendor, idProduct):
     if not hid.enumerate(idVendor, idProduct):
         raise IOError("No weather station connected")
     self.hid = hid.device(idVendor, idProduct)
Beispiel #54
0
                            bit_pos - len(self.__buttons_status["b_pos"])])
        except ServiceExit:
            self.__close_device()
        except struct.error:
            self.__read_device()

    @property
    def global_packet_nbr(self):
        return self.__global_packet_nbr.to_bytes(1, byteorder="big")

    @global_packet_nbr.setter
    def global_packet_nbr(self, nbr):
        """
            Range from 0 to 15 following the documentation
        """
        self.__global_packet_nbr = nbr & 0xF

    @staticmethod
    def service_shutdown(signum, frame):
        print("Caught signal %d" % signum)
        raise ServiceExit


if __name__ == "__main__":
    devices = hid.enumerate(0, 0)

    for device in devices:
        if "Joy-Con" in device.get("product_string", ""):
            # print(device)
            nintendo_joycon(device)
            self.gp_set_mode(pin, self.GP_GPIO)  # set to GPIO mode
            self.gpio_set_direction(pin, 1)  # set to INPUT


class MCP2221I2C(_MCP2221I2C):  # pylint: disable=too-few-public-methods
    def __init__(self, mcp2221, *, frequency=100000):
        self._mcp2221 = mcp2221
        self._mcp2221.i2c_configure(frequency)


class I2C(busio.I2C):  # pylint: disable=too-few-public-methods
    def __init__(self, mcp2221_i2c):
        self._i2c = mcp2221_i2c


addresses = [mcp["path"] for mcp in hid.enumerate(0x04D8, 0x00DD)]

i2c_devices = []
i2c_devices.append(I2C(MCP2221I2C(_mcp2221)))

for addr in addresses:
    try:
        i2c_device = I2C(MCP2221I2C(MCP2221(addr)))
        i2c_devices.append(i2c_device)
    except OSError:
        print("Device path: " + str(addr) + " is used")

while True:
    for i2c in i2c_devices:
        addrbuf = bytearray(2)
        addrbuf[0] = ADDRID1 >> 8
Beispiel #56
0
def get_path_to_device_interface(intf):
	for ls in hid.enumerate():
		if ls["vendor_id"] == VID and ls["product_id"] == PID and ls["interface_number"] == intf:
			return ls["path"]

	return ""
Beispiel #57
0
def listHidDevice():
    for d in hid.enumerate():
        keys = list(d.keys())
        keys.sort()
    for key in keys:
        print("%s : %s" % (key, d[key]))
Beispiel #58
0
    return val


def print_usage(input_source_table=None):
    print("Usage: python hid-monitor-control.py <INPUT> [INPUT2]")
    if input_source_table:
        print("       INPUT = " + " | ".join(input_source_table.keys()))
    print("")
    print("       python hid-monitor-control.py switcher")


# enumerate USB devices

if False:
    for des in hid.enumerate():
        keys = list(des.keys())
        keys.sort()
        for key in keys:
            print("%s : %s" % (key, des[key]))
        print("")

# try opening a device, then perform write and read

des = None
for d in hid.enumerate():
    if [d['vendor_id'], d['product_id']] in device_id_pairs:
        des = d
        break

# des = { 'vendor_id': 0x056D, 'product_id': 0x4059 }
Beispiel #59
0
#!/usr/bin/env python

import hid

#Get the list of all devices matching this vendor_id/product_id
vendor_id = 0x1a86
product_id = 0xe008
device_list = hid.enumerate(vendor_id, product_id)

for dev in device_list:
  for key, value in dev.items():
    print("{0}:{1}".format(key,value))
    if key == 'path':
      device = hid.device()
      if device.open_path(value):
      	print(device)
      else:
        print("Error!")



# some stuff
dev = hid.device()
dev.open(vendor_id,product_id)
    def id(self, ):  # pylint: disable=invalid-name,too-many-branches,too-many-return-statements
        """Return a unique id for the detected chip, if any."""
        # There are some times we want to trick the platform detection
        # say if a raspberry pi doesn't have the right ID, or for testing

        # Caching
        if self._chip_id:
            return self._chip_id

        try:
            return os.environ["BLINKA_FORCECHIP"]
        except KeyError:  # no forced chip, continue with testing!
            pass

        # Special cases controlled by environment var
        if os.environ.get("BLINKA_FT232H"):
            from pyftdi.usbtools import UsbTools

            # look for it based on PID/VID
            count = len(UsbTools.find_all([(0x0403, 0x6014)]))
            if count == 0:
                raise RuntimeError("BLINKA_FT232H environment variable " +
                                   "set, but no FT232H device found")
            self._chip_id = chips.FT232H
            return self._chip_id
        if os.environ.get("BLINKA_MCP2221"):
            import hid

            # look for it based on PID/VID
            for dev in hid.enumerate():
                if dev["vendor_id"] == 0x04D8 and dev["product_id"] == 0x00DD:
                    self._chip_id = chips.MCP2221
                    return self._chip_id
            raise RuntimeError("BLINKA_MCP2221 environment variable " +
                               "set, but no MCP2221 device found")
        if os.environ.get("BLINKA_GREATFET"):
            import usb

            if usb.core.find(idVendor=0x1D50, idProduct=0x60E6) is not None:
                self._chip_id = chips.LPC4330
                return self._chip_id
            raise RuntimeError("BLINKA_GREATFET environment variable " +
                               "set, but no GreatFET device found")
        if os.environ.get("BLINKA_NOVA"):
            self._chip_id = chips.BINHO
            return self._chip_id

        platform = sys.platform
        if platform in ("linux", "linux2"):
            self._chip_id = self._linux_id()
            return self._chip_id
        if platform == "esp8266":
            self._chip_id = chips.ESP8266
            return self._chip_id
        if platform == "samd21":
            self._chip_id = chips.SAMD21
            return self._chip_id
        if platform == "pyboard":
            self._chip_id = chips.STM32F405
            return self._chip_id
        # nothing found!
        return None