### Install hidapi on FreeBSD Source: https://github.com/apmorton/pyhidapi/blob/master/README.md Install the hidapi package on FreeBSD systems. ```bash pkg install -g 'py3*-hid' ``` -------------------------------- ### Install hidapi on macOS Source: https://github.com/apmorton/pyhidapi/blob/master/README.md Install hidapi using the Homebrew package manager. ```bash brew install hidapi ``` -------------------------------- ### Install hidapi on Linux distributions Source: https://github.com/apmorton/pyhidapi/blob/master/README.md Commands to install the hidapi dependency on various Linux distributions. ```bash pacman -Sy hidapi ``` ```bash yum install hidapi ``` ```bash dnf install hidapi ``` ```bash apt install libhidapi-hidraw0 ``` ```bash apt install libhidapi-libusb0 ``` -------------------------------- ### Install pyhidapi via pip Source: https://github.com/apmorton/pyhidapi/blob/master/README.md Install the pyhidapi library using the Python package manager. ```bash pip install hid ``` -------------------------------- ### Get and Send Feature Reports with pyhidapi Source: https://context7.com/apmorton/pyhidapi/llms.txt Use `get_feature_report()` to read device configuration and `send_feature_report()` to write it. The first byte of the report data must be the report ID. ```python import hid vid = 0x046d pid = 0xc534 with hid.Device(vid, pid) as device: # Get feature report - first byte is report ID report_id = 0x06 max_size = 64 try: report = device.get_feature_report(report_id, max_size) print(f"Feature report {report_id}: {report.hex()}") print(f"Report data: {list(report)}") except hid.HIDException as e: print(f"Failed to get feature report: {e}") # Send feature report - first byte must be report ID report_id = 0x06 config_data = bytes([report_id, 0x01, 0x02, 0x03]) try: bytes_sent = device.send_feature_report(config_data) print(f"Sent feature report: {bytes_sent} bytes") except hid.HIDException as e: print(f"Failed to send feature report: {e}") ``` -------------------------------- ### Get Input Reports with pyhidapi Source: https://context7.com/apmorton/pyhidapi/llms.txt Retrieve an input report by its report ID using `get_input_report()`. This is useful for obtaining the current state of device inputs without waiting for an interrupt. ```python import hid vid = 0x046d pid = 0xc534 with hid.Device(vid, pid) as device: # Get input report with specific report ID report_id = 0x01 max_size = 64 try: report = device.get_input_report(report_id, max_size) print(f"Input report {report_id}: {report.hex()}") # Parse report data (device-specific) if len(report) > 1: button_state = report[1] print(f"Button state byte: {bin(button_state)}") except hid.HIDException as e: print(f"Failed to get input report: {e}") ``` -------------------------------- ### Get USB String Descriptors with pyhidapi Source: https://context7.com/apmorton/pyhidapi/llms.txt Retrieve USB string descriptors by index using `get_indexed_string()`. This provides access to additional device strings beyond the standard manufacturer, product, and serial number. ```python import hid vid = 0x046d pid = 0xc534 with hid.Device(vid, pid) as device: # USB string descriptor indices (device-specific) # Index 0 is usually language IDs # Index 1 is usually manufacturer # Index 2 is usually product # Index 3 is usually serial number for index in range(1, 5): try: string = device.get_indexed_string(index) print(f"String descriptor {index}: {string}") except hid.HIDException: print(f"String descriptor {index}: Not available") break ``` -------------------------------- ### Get HID Report Descriptor with pyhidapi Source: https://context7.com/apmorton/pyhidapi/llms.txt Retrieve the HID report descriptor using `get_report_descriptor()`. This method requires hidapi version 0.14.0 or later and describes the format of reports. ```python import hid vid = 0x046d pid = 0xc534 with hid.Device(vid, pid) as device: try: # Get the HID report descriptor (max 4096 bytes by default) descriptor = device.get_report_descriptor() print(f"Report descriptor ({len(descriptor)} bytes):") print(descriptor.hex()) # Parse descriptor bytes for i, byte in enumerate(descriptor): print(f" [{i:3d}] 0x{byte:02X}") except AttributeError: print("get_report_descriptor() requires hidapi >= 0.14.0") except hid.HIDException as e: print(f"Failed to get descriptor: {e}") ``` -------------------------------- ### Configure Arch Linux community repository Source: https://github.com/apmorton/pyhidapi/blob/master/README.md Enable the community repository in the pacman configuration file. ```ini [community] Include = /etc/pacman.d/mirrorlist ``` -------------------------------- ### Handle HIDException for device errors Source: https://context7.com/apmorton/pyhidapi/llms.txt Demonstrates catching HIDException during device initialization and communication failures. Use this to manage errors when interacting with invalid or closed devices. ```python import hid vid = 0xFFFF # Invalid vendor ID pid = 0xFFFF # Invalid product ID try: device = hid.Device(vid, pid) except hid.HIDException as e: print(f"HID Error: {e}") try: # Attempting operations on closed device device = hid.Device(0x046d, 0xc534) device.close() device.read(64) # Will raise HIDException except hid.HIDException as e: print(f"Device closed error: {e}") try: # Invalid initialization device = hid.Device() # No vid/pid or path except ValueError as e: print(f"Initialization error: {e}") ``` -------------------------------- ### Enumerate HID Devices Source: https://context7.com/apmorton/pyhidapi/llms.txt Use the enumerate() function to list all connected HID devices. Optionally filter by vendor ID and product ID to find specific devices. Device information includes vendor ID, product ID, product string, manufacturer string, path, serial number, and interface number. ```python import hid # Enumerate all connected HID devices all_devices = hid.enumerate() for device in all_devices: print(f"Vendor ID: {hex(device['vendor_id'])}") print(f"Product ID: {hex(device['product_id'])}") print(f"Product: {device['product_string']}") print(f"Manufacturer: {device['manufacturer_string']}") print(f"Path: {device['path']}") print(f"Serial: {device['serial_number']}") print(f"Interface: {device['interface_number']}") print("---") # Enumerate only devices with specific vendor/product ID vid = 0x046d # Logitech pid = 0xc534 # USB Receiver logitech_devices = hid.enumerate(vid, pid) print(f"Found {len(logitech_devices)} Logitech device(s)") ``` -------------------------------- ### Communicate with HID devices Source: https://context7.com/apmorton/pyhidapi/llms.txt Provides a complete workflow for enumerating, connecting, and performing read/write operations on an HID device. The context manager protocol is recommended for safe device handling. ```python import hid import time def find_and_communicate(target_vid, target_pid): # Step 1: Enumerate and find target device print("Scanning for HID devices...") devices = hid.enumerate(target_vid, target_pid) if not devices: print(f"No device found with VID={hex(target_vid)} PID={hex(target_pid)}") return print(f"Found {len(devices)} matching device(s)") device_info = devices[0] print(f" Product: {device_info['product_string']}") print(f" Manufacturer: {device_info['manufacturer_string']}") print(f" Path: {device_info['path']}") # Step 2: Open and communicate with device try: with hid.Device(path=device_info['path']) as dev: print(f"\nConnected to: {dev.product}") print(f"Manufacturer: {dev.manufacturer}") print(f"Serial: {dev.serial}") # Set non-blocking mode for polling dev.nonblocking = True # Step 3: Send command command = bytes([0x00, 0x01, 0x00, 0x00]) bytes_written = dev.write(command) print(f"\nSent {bytes_written} bytes") # Step 4: Read response with polling print("Waiting for response...") for _ in range(10): data = dev.read(64) if data: print(f"Received: {data.hex()}") break time.sleep(0.1) else: print("No response received") except hid.HIDException as e: print(f"Communication error: {e}") # Example usage if __name__ == "__main__": find_and_communicate(0x046d, 0xc534) ``` -------------------------------- ### Print HID device details Source: https://github.com/apmorton/pyhidapi/blob/master/README.md Access and print manufacturer, product, and serial number information for a specific HID device. ```python import hid vid = 0x046d # Change it for your device pid = 0xc534 # Change it for your device with hid.Device(vid, pid) as h: print(f'Device manufacturer: {h.manufacturer}') print(f'Product: {h.product}') print(f'Serial Number: {h.serial}') ``` -------------------------------- ### Open and Manage HID Devices Source: https://context7.com/apmorton/pyhidapi/llms.txt The Device class represents a connection to an HID device. It can be opened by vendor/product ID, serial number, or device path. Using a context manager (with statement) is recommended for automatic resource cleanup. ```python import hid # Open device by vendor ID and product ID vid = 0x046d pid = 0xc534 try: # Using context manager (recommended) with hid.Device(vid, pid) as device: print(f"Manufacturer: {device.manufacturer}") print(f"Product: {device.product}") print(f"Serial Number: {device.serial}") except hid.HIDException as e: print(f"Failed to open device: {e}") # Open device by path (useful when multiple devices have same vid/pid) devices = hid.enumerate(vid, pid) if devices: path = devices[0]['path'] with hid.Device(path=path) as device: print(f"Opened device at path: {path}") # Open device by serial number serial = "ABC123" with hid.Device(vid, pid, serial=serial) as device: print(f"Opened device with serial: {serial}") # Manual open/close without context manager device = hid.Device(vid, pid) print(f"Device: {device.product}") device.close() ``` -------------------------------- ### Device Class - Open and Manage HID Devices Source: https://context7.com/apmorton/pyhidapi/llms.txt The `Device` class represents a connection to an HID device. It supports opening by vendor/product ID, serial number, or device path, and includes context manager support for automatic resource cleanup. ```python import hid vid = 0x046d pid = 0xc534 try: # Using context manager (recommended) with hid.Device(vid, pid) as device: print(f"Manufacturer: {device.manufacturer}") print(f"Product: {device.product}") print(f"Serial Number: {device.serial}") except hid.HIDException as e: print(f"Failed to open device: {e}") # Open device by path (useful when multiple devices have same vid/pid) devices = hid.enumerate(vid, pid) if devices: path = devices[0]['path'] with hid.Device(path=path) as device: print(f"Opened device at path: {path}") # Open device by serial number serial = "ABC123" with hid.Device(vid, pid, serial=serial) as device: print(f"Opened device with serial: {serial}") # Manual open/close without context manager device = hid.Device(vid, pid) print(f"Device: {device.product}") device.close() ``` -------------------------------- ### Send Data to HID Device Source: https://context7.com/apmorton/pyhidapi/llms.txt The write() method sends a raw data buffer to the HID device. The first byte is typically the report ID (use 0x00 if the device doesn't use numbered reports). Returns the number of bytes written. Ensure the device is opened before writing. ```python import hid vid = 0x046d pid = 0xc534 with hid.Device(vid, pid) as device: # Send command to device (first byte is report ID) # Example: Turn on LED with command 0x01 report_id = 0x00 command = bytes([report_id, 0x01, 0xFF, 0x00, 0x00]) try: bytes_written = device.write(command) print(f"Sent {bytes_written} bytes to device") except hid.HIDException as e: print(f"Write failed: {e}") # Send RGB color data to LED controller red, green, blue = 255, 128, 0 led_data = bytes([0x00, 0x05, red, green, blue]) device.write(led_data) ``` -------------------------------- ### Enumerate Devices and Check Bus Type with pyhidapi Source: https://context7.com/apmorton/pyhidapi/llms.txt Enumerate connected HID devices and check their connection type using the `BusType` enum. This feature is available with hidapi version 0.13.0 or later. ```python import hid # Enumerate and check bus type devices = hid.enumerate() for device in devices: if 'bus_type' in device: bus = device['bus_type'] print(f"{device['product_string']}: {bus.name}") if bus == hid.BusType.USB: print(" Connected via USB") elif bus == hid.BusType.BLUETOOTH: print(" Connected via Bluetooth") elif bus == hid.BusType.I2C: print(" Connected via I2C") elif bus == hid.BusType.SPI: print(" Connected via SPI") else: print(" Unknown connection type") ``` -------------------------------- ### Receive Data from HID Device Source: https://context7.com/apmorton/pyhidapi/llms.txt The read() method receives data from the HID device. Specify the maximum number of bytes to read and an optional timeout in milliseconds. Returns the received data as bytes. Can be blocking, with a timeout, or non-blocking. ```python import hid vid = 0x046d pid = 0xc534 with hid.Device(vid, pid) as device: # Blocking read - waits until data is available data = device.read(64) print(f"Received {len(data)} bytes: {data.hex()}") # Read with timeout (1000ms) - returns empty if no data within timeout data = device.read(64, timeout=1000) if data: print(f"Data received: {list(data)}") else: print("No data received within timeout") # Non-blocking read using nonblocking property device.nonblocking = True data = device.read(64) # Returns immediately, may be empty if data: print(f"Got data: {data}") device.nonblocking = False # Restore blocking mode ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.