### Complete DeviceManager Workflow Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md A full example demonstrating context management, starting the manager, waiting for a device, and stopping the manager. ```csharp using var context = new UsbContext(); var manager = new DeviceManager(context); manager.Start(); try { var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var device = await manager.WaitForDeviceArrival( new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }, TimeSpan.FromSeconds(30), cts.Token); if (device != null) { Console.WriteLine("Device found!"); device.Open(); // Use device... device.Close(); } else { Console.WriteLine("Timeout waiting for device"); } } finally { manager.Stop(); } ``` -------------------------------- ### Initialize and Start DeviceManager Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Instantiate the manager and call Start() to begin monitoring for hotplug events. ```csharp var manager = new DeviceManager(context); manager.Start(); ``` -------------------------------- ### Perform USB control transfer Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/4-types.md Example of creating a setup packet for a descriptor request and executing a control transfer. ```csharp // Get descriptor request var setup = new UsbSetupPacket(0xC0, 0x06, 0x0100, 0, 64); device.ControlTransfer(setup, buffer, 0, 64); ``` -------------------------------- ### Start() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Registers for hotplug events and enables device waiting methods. ```APIDOC ## Start() ### Description Registers for hotplug events and enables the device waiting methods. Must be called before calling any wait methods. ``` -------------------------------- ### Complete USB Device Communication Example Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/3-endpoints.md Demonstrates the full lifecycle of finding a device, opening endpoints, performing read/write operations, and cleaning up resources. ```csharp using var context = new UsbContext(); // Find device var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); if (device == null) { Console.WriteLine("Device not found"); return; } // Open device and claim interface device.Open(); device.SetConfiguration(device.Configs[0].Value); device.ClaimInterface(0); // Open endpoints var reader = device.OpenEndpointReader(ReadEndpointID.Ep01); var writer = device.OpenEndpointWriter(WriteEndpointID.Ep01); // Write data var writeData = new byte[] { 0x01, 0x02, 0x03, 0x04 }; if (writer.Write(writeData, 3000, out var written) == Error.Success) { Console.WriteLine($"Wrote {written} bytes"); } // Read data var readBuffer = new byte[64]; if (reader.Read(readBuffer, 3000, out var read) == Error.Success) { Console.WriteLine($"Read {read} bytes"); Console.WriteLine($"Data: {BitConverter.ToString(readBuffer, 0, read)}"); } // Cleanup device.ReleaseInterface(0); device.Close(); ``` -------------------------------- ### UsbSetupPacket Constructor Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Creates a new setup packet for a USB control transfer. ```APIDOC ## UsbSetupPacket(byte bRequestType, byte bRequest, int wValue, int wIndex, int wlength) ### Description Creates a setup packet used for USB control transfers. The packet contains 8 bytes of control information including request type, request code, and specific parameters. ### Parameters - **bRequestType** (byte) - Request characteristics including direction, type, and recipient. - **bRequest** (byte) - Specific request code. - **wValue** (int) - Request-specific parameter (masked to short). - **wIndex** (int) - Request-specific parameter (masked to short). - **wlength** (int) - Data phase length in bytes (masked to short). ``` -------------------------------- ### Write data example Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/3-endpoints.md Example usage of the Write method to send a byte array to an endpoint. ```csharp var writer = device.OpenEndpointWriter(WriteEndpointID.Ep01); var data = new byte[] { 0x01, 0x02, 0x03, 0x04 }; if (writer.Write(data, 3000, out var transferred) == Error.Success) { Console.WriteLine($"Wrote {transferred} bytes"); } ``` -------------------------------- ### UsbSetupPacket Constructor Signature Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Constructor signature for initializing a new setup packet with request parameters. ```csharp public UsbSetupPacket(byte bRequestType, byte bRequest, int wValue, int wIndex, int wlength) ``` -------------------------------- ### Write range example Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/3-endpoints.md Example usage of the Write method to send a specific range of a buffer. ```csharp var buffer = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }; writer.Write(buffer, 2, 3, 3000, out var transferred); ``` -------------------------------- ### Complete UsbDeviceFinder Usage Examples Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Demonstrates various ways to use UsbDeviceFinder to locate single or multiple devices via UsbContext. ```csharp // Find device by vendor and product ID var finder = new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }; var device = context.Find(finder); // Find all devices from a vendor var finder = new UsbDeviceFinder { Vid = 0x04B4 }; using var devices = context.FindAll(finder); // Find device by serial number var finder = new UsbDeviceFinder { SerialNumber = "ABC123" }; var device = context.Find(finder); // Multiple criteria var finder = new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0, SerialNumber = "ABC123" }; var device = context.Find(finder); ``` -------------------------------- ### Get Interface (0x0A) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Gets the selected alternate interface setting. ```APIDOC ## Get Interface (0x0A) ### Description Retrieves the selected alternate interface setting for a specific interface. ### Method ControlTransfer ### Parameters - **interfaceNumber** (int) - Required - The interface index. ### Code Example ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientInterface, 0x0A, 0, interfaceNumber, 1 ); var buffer = new byte[1]; device.ControlTransfer(setup, buffer, 0, 1); int altSetting = buffer[0]; ``` ``` -------------------------------- ### Get Device Descriptor Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Retrieves device descriptors using a setup packet with the Get Descriptor request code (0x06). ```csharp // Device descriptor request var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientDevice, 0x06, // Get Descriptor (0x01 << 8) | 0, // Descriptor type (1=Device) and index 0, // Interface 64 // Max descriptor length ); var buffer = new byte[64]; int transferred = device.ControlTransfer(setup, buffer, 0, 64); ``` -------------------------------- ### Install LibUsbDotNet via NuGet Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Commands to add the LibUsbDotNet package to your project. ```bash dotnet add package LibUsbDotNet ``` ```bash Install-Package LibUsbDotNet ``` -------------------------------- ### Get Available Configurations Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves a collection of available USB configurations for the device. ```csharp public ReadOnlyCollection Configs { get; } ``` -------------------------------- ### Get Configuration Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves the active configuration value of the device. ```csharp public int Configuration { get; } ``` -------------------------------- ### UsbSetupPacket Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Used for constructing control transfer setup packets for USB control requests. ```APIDOC ## UsbSetupPacket ### Description Represents a control transfer setup packet. ### Usage ```csharp var setup = new UsbSetupPacket(0xC0, 0x06, 0x0100, 0, 64); device.ControlTransfer(setup, buffer, 0, 64); ``` ``` -------------------------------- ### Get Configuration (0x08) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Gets the active configuration value from the device. ```APIDOC ## Get Configuration (0x08) ### Description Retrieves the current active configuration value. ### Method ControlTransfer ### Code Example ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientDevice, 0x08, 0, 0, 1 ); var buffer = new byte[1]; device.ControlTransfer(setup, buffer, 0, 1); int activeConfig = buffer[0]; ``` ``` -------------------------------- ### Define UsbSetupPacket Structure Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md The structure representing the 8-byte setup packet required for USB control transfers. ```csharp [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct UsbSetupPacket { public byte RequestType; // Characteristics of request public byte Request; // Specific request code public short Value; // Request-specific parameter public short Index; // Request-specific parameter public short Length; // Data phase length in bytes } ``` -------------------------------- ### Define Device Interface GUID Criteria Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Sets the device interface GUID for matching. Set to Guid.Empty to ignore. ```csharp public Guid DeviceInterfaceGuid { get; init; } ``` -------------------------------- ### Perform Control Transfer Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Execute a control transfer using a setup packet. ```csharp var setup = new UsbSetupPacket(0xC0, 0x06, 0x0100, 0, 64); device.ControlTransfer(setup, buffer, 0, 64); ``` -------------------------------- ### Get ProductId Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves the USB product ID (PID). ```csharp public ushort ProductId { get; } ``` -------------------------------- ### Get Status Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Retrieves the status of a device, interface, or endpoint. ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientEndpoint, 0x00, // Get Status 0, 0x81, // Endpoint address 2 // Status is 2 bytes ); var buffer = new byte[2]; device.ControlTransfer(setup, buffer, 0, 2); ushort status = (ushort)((buffer[1] << 8) | buffer[0]); ``` -------------------------------- ### Get Active Configuration Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Retrieves the currently active configuration value from the device. ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientDevice, 0x08, // Get Configuration 0, 0, 1 ); var buffer = new byte[1]; device.ControlTransfer(setup, buffer, 0, 1); int activeConfig = buffer[0]; ``` -------------------------------- ### Get Interface Setting Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Retrieves the selected alternate interface setting for a specific interface. ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientInterface, 0x0A, // Get Interface 0, interfaceNumber, 1 // Return 1 byte ); var buffer = new byte[1]; device.ControlTransfer(setup, buffer, 0, 1); int altSetting = buffer[0]; ``` -------------------------------- ### Get Device Info Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves detailed device information such as manufacturer and serial number. ```csharp public UsbDeviceInfo Info { get; } ``` -------------------------------- ### Register HotPlug Events Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Starts a background thread to monitor USB device arrival and removal events. ```csharp context.DeviceEvent += (sender, e) => { if (e is DeviceArrivedEventArgs arrived) { Console.WriteLine($"Device arrived: {arrived.Device}"); } }; context.RegisterHotPlug(); ``` -------------------------------- ### USB Control Transfer Helper Constants Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Constants for defining request recipients, types, and control flags used in setup packets. ```csharp public static class UsbRequestRecipient { public const byte Device = 0x00; public const byte Interface = 0x01; public const byte Endpoint = 0x02; public const byte Other = 0x03; } public static class UsbRequestType { public const byte Standard = 0x00; public const byte Class = 0x20; public const byte Vendor = 0x40; } public static class UsbCtrlFlags { public const byte RequestTypeStandard = 0x00; public const byte RequestTypeClass = 0x20; public const byte RequestTypeVendor = 0x40; public const byte RecipientDevice = 0x00; public const byte RecipientInterface = 0x01; public const byte RecipientEndpoint = 0x02; public const byte RequestIn = 0x80; public const byte RequestOut = 0x00; } ``` -------------------------------- ### Initialize and Read from a USB Device in C# Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/00-START-HERE.md Demonstrates the minimal workflow for initializing a USB context, finding a specific device by VID/PID, claiming an interface, and performing a read operation. ```csharp using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; // Create context using var context = new UsbContext(); // Find device (VID=0x04B4, PID=0x00F0) var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); if (device == null) return; // Open and use device device.Open(); device.ClaimInterface(0); var reader = device.OpenEndpointReader(ReadEndpointID.Ep01); var buffer = new byte[64]; reader.Read(buffer, 3000, out var transferred); Console.WriteLine($"Read {transferred} bytes"); device.Close(); ``` -------------------------------- ### Get Status (0x00) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Gets the status of a device, interface, or endpoint. ```APIDOC ## Get Status (0x00) ### Description Retrieves the status bytes for a device, interface, or endpoint. ### Method ControlTransfer ### Code Example ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientEndpoint, 0x00, 0, 0x81, 2 ); var buffer = new byte[2]; device.ControlTransfer(setup, buffer, 0, 2); ushort status = (ushort)((buffer[1] << 8) | buffer[0]); ``` ``` -------------------------------- ### Configure USB Device Interfaces and Endpoints Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Demonstrates how to open a device, set its configuration, iterate through interfaces and endpoints, and manage interface claims. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; using var context = new UsbContext(); var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); if (device == null) return; device.Open(); // Set configuration int configValue = device.Configs[0].Value; device.SetConfiguration(configValue); Console.WriteLine($"Configuration set to: {configValue}"); // Get and display available interfaces foreach (var config in device.Configs) { Console.WriteLine($"Configuration {config.Value}:"); foreach (var iface in config.Interfaces) { Console.WriteLine($" Interface {iface.Number}:"); foreach (var endpoint in iface.Endpoints) { Console.WriteLine($" Endpoint: {endpoint.EndpointID:X02} " + $"Type: {endpoint.Type} " + $"Max Packet: {endpoint.MaxPacketSize}"); } } } // Claim interface device.ClaimInterface(0); // Set alternate interface if needed device.SetAltInterface(0); // Release when done device.ReleaseInterface(0); device.Close(); ``` -------------------------------- ### Initialize UsbContext and Enumerate Devices Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/00-START-HERE.md Create a new USB context to manage device discovery and filtering. ```csharp var context = new UsbContext(); var devices = context.List(); var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4 }); ``` -------------------------------- ### Open and Configure UsbDevice Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Open a device and claim an interface to prepare for communication. ```csharp device.Open(); device.ClaimInterface(0); var reader = device.OpenEndpointReader(ReadEndpointID.Ep01); ``` -------------------------------- ### Initialize UsbContext Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Create a new USB context to manage devices and handle hotplug events. ```csharp using var context = new UsbContext(); var devices = context.List(); ``` -------------------------------- ### Get LocationId Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves the physical port location identifier. ```csharp public LocationId LocationId { get; } ``` -------------------------------- ### Configure Linux Udev Rules for Access Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/6-errors-and-exceptions.md Create a udev rule file to grant appropriate permissions to a specific USB device on Linux. ```bash # Create /etc/udev/rules.d/99-usb.rules SUBSYSTEMS=="usb", ATTRS{idVendor}=="04b4", ATTRS{idProduct}=="00f0", MODE="0666" sudo udevadm control --reload-rules ``` -------------------------------- ### Get VendorId Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves the USB vendor ID (VID). ```csharp public ushort VendorId { get; } ``` -------------------------------- ### Send a USB control command in C# Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/00-START-HERE.md Constructs a UsbSetupPacket and performs a control transfer to the device. ```csharp var setup = new UsbSetupPacket(0xC0, 0x06, 0x0100, 0, 64); var buffer = new byte[64]; int transferred = device.ControlTransfer(setup, buffer, 0, 64); ``` -------------------------------- ### Async Control Request Sequence in C# Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Demonstrates an asynchronous initialization sequence including setting configuration and claiming an interface. ```csharp public async Task InitializeDeviceAsync(IUsbDevice device) { try { // Set configuration var setConfig = new UsbSetupPacket( UsbCtrlFlags.RequestOut | UsbCtrlFlags.RecipientDevice, 0x09, 1, // Configuration value 0, 0 ); await device.ControlTransferAsync(setConfig); // Claim interface (using synchronous method) device.ClaimInterface(0); // Get device descriptor var getDescriptor = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientDevice, 0x06, (1 << 8) | 0, 0, 18 ); var buffer = new byte[18]; int transferred = await device.ControlTransferAsync(getDescriptor, buffer, 0, 18); Console.WriteLine($"Device descriptor: {transferred} bytes received"); return true; } catch (UsbException ex) { Console.WriteLine($"Device initialization failed: {ex.Message}"); return false; } } ``` -------------------------------- ### Initialize UsbDeviceFinder Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Creates a new instance of the finder with all criteria unset, matching any device. ```csharp public UsbDeviceFinder() ``` -------------------------------- ### GetAltInterface(out int alternateID) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Gets the currently selected alternate interface setting. ```APIDOC ## GetAltInterface(out int alternateID) ### Description Gets the currently selected alternate interface setting. ### Parameters - **alternateID** (out int): The current alternate interface setting ### Returns - `bool`: true on success, false on failure. ``` -------------------------------- ### Use UsbContext with using statement Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Shows the recommended pattern for ensuring resources are released automatically. ```csharp using (var context = new UsbContext()) { // Use context } // Dispose called automatically ``` -------------------------------- ### Initialize UsbDevice Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Constructor for creating a new UsbDevice instance. Typically invoked by UsbContext methods rather than directly. ```csharp public UsbDevice(Device device, UsbContext originatingContext) ``` -------------------------------- ### Initialize UsbContext Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Creates a new libusb session and configures the debug level. ```csharp using var context = new UsbContext(); context.SetDebugLevel(LogLevel.Info); ``` -------------------------------- ### Get Device Collection Count Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Retrieves the number of devices currently in the collection. ```csharp public int Count { get; } ``` -------------------------------- ### Open() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Opens the device for communication. Must be called before performing any I/O operations. ```APIDOC ## Open() ### Description Opens the device for communication. Must be called before performing any I/O operations. ### Signature `public void Open()` ### Throws - `UsbException`: If the device cannot be opened. ``` -------------------------------- ### DeviceManager(UsbContext context, bool disposeContext = false) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Constructor to initialize a new DeviceManager instance. ```APIDOC ## DeviceManager(UsbContext context, bool disposeContext = false) ### Description Creates a new instance of the DeviceManager to monitor USB devices. ### Parameters - **context** (UsbContext) - Required - The USB context to monitor. - **disposeContext** (bool) - Optional - Whether to dispose the context when the manager is disposed. ``` -------------------------------- ### TryOpen() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Attempts to open the device for communication without throwing an exception. ```APIDOC ## TryOpen() ### Description Attempts to open the device for communication without throwing an exception. ### Signature `public bool TryOpen()` ### Returns - `bool`: true if the device was successfully opened, false otherwise. ``` -------------------------------- ### UsbContext() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Initializes a new instance of the UsbContext class and creates an underlying libusb context. ```APIDOC ## Constructor: UsbContext() ### Description Initializes a new instance of the UsbContext class and creates an underlying libusb context. ### Returns A new UsbContext instance. ### Example ```csharp using var context = new UsbContext(); context.SetDebugLevel(LogLevel.Info); ``` ``` -------------------------------- ### RegisterHotPlug() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Registers for USB device hotplug events and starts the event handling thread. ```APIDOC ## RegisterHotPlug() ### Description Registers for USB device hotplug events (device arrival and removal). Automatically starts the event handling thread. ### Example ```csharp context.DeviceEvent += (sender, e) => { if (e is DeviceArrivedEventArgs arrived) { Console.WriteLine($"Device arrived: {arrived.Device}"); } }; context.RegisterHotPlug(); ``` -------------------------------- ### Iterate USB Device Collection Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Demonstrates listing devices and iterating through them to display vendor and product IDs. ```csharp using var devices = context.List(); Console.WriteLine($"Found {devices.Count} devices"); foreach (var device in devices) { Console.WriteLine($"{device.VendorId:X04}:{device.ProductId:X04}"); } ``` -------------------------------- ### Find and Open Device Pattern Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Common pattern to find and open a device if it exists. ```csharp using var context = new UsbContext(); var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); device?.Open(); ``` -------------------------------- ### Get USB Descriptor (Unmanaged) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves a USB descriptor from the device into an unmanaged memory buffer. ```csharp public bool GetDescriptor(byte descriptorType, byte index, short langId, IntPtr buffer, int bufferLength, out int transferLength) ``` -------------------------------- ### Using Dispose with UsbDevice Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Demonstrates automatic resource cleanup using the using statement. ```csharp using (var device = context.Find(...)) { device.Open(); // Use device } // Dispose called automatically ``` -------------------------------- ### Get Descriptor (0x06) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Retrieves device descriptors such as Device, Configuration, String, Interface, or Endpoint descriptors. ```APIDOC ## Get Descriptor (0x06) ### Description Retrieves device descriptors from the USB device. ### Method ControlTransfer ### Parameters - **setup** (UsbSetupPacket) - Required - Contains request type (RequestIn | RecipientDevice), bRequest (0x06), wValue (Descriptor type and index), wIndex (Interface), and wLength (Max length). - **buffer** (byte[]) - Required - Buffer to store the descriptor data. ### Code Example ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientDevice, 0x06, (0x01 << 8) | 0, 0, 64 ); var buffer = new byte[64]; int transferred = device.ControlTransfer(setup, buffer, 0, 64); ``` ``` -------------------------------- ### GetAltInterfaceSetting(byte interfaceID, out byte selectedAltInterfaceID) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Gets the selected alternate interface setting for the specified interface. ```APIDOC ## GetAltInterfaceSetting(byte interfaceID, out byte selectedAltInterfaceID) ### Description Gets the selected alternate interface setting for the specified interface. ### Parameters - **interfaceID** (byte): Interface number - **selectedAltInterfaceID** (out byte): The selected alternate setting ``` -------------------------------- ### Clone Method and Usage Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Creates a reference clone of the device, useful for maintaining access after disposing of a device collection. ```csharp public IUsbDevice Clone() ``` ```csharp IUsbDevice clonedDevice; using (var devices = context.List()) { clonedDevice = devices[0].Clone(); } // Can still use clonedDevice after collection is disposed clonedDevice.Open(); ``` -------------------------------- ### Initialize UsbEndpointWriter Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/3-endpoints.md Constructor signature for initializing a writer for a specific USB endpoint. ```csharp public UsbEndpointWriter(IUsbDevice usbDevice, byte alternateInterfaceID, WriteEndpointID writeEndpointID, EndpointType endpointType) ``` -------------------------------- ### Get USB Descriptor (Managed) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Retrieves a USB descriptor from the device into a managed object such as a byte array or struct. ```csharp public bool GetDescriptor(byte descriptorType, byte index, short langId, object buffer, int bufferLength, out int transferLength) ``` -------------------------------- ### Async Device Arrival Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Wait asynchronously for a device to be connected. ```csharp var device = await manager.WaitForDeviceArrival(finder, timeout, token); ``` -------------------------------- ### Implement USB Error Handling Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Demonstrates a structured approach to handling USB exceptions, access permissions, and operation-specific errors like timeouts or disconnections. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; using var context = new UsbContext(); try { var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); if (device == null) { Console.WriteLine("Device not found"); return; } try { device.Open(); } catch (UsbException ex) when (ex.ErrorCode == Error.Access) { Console.WriteLine("Permission denied. Check device permissions or drivers."); return; } device.ClaimInterface(0); var reader = device.OpenEndpointReader(ReadEndpointID.Ep01); var buffer = new byte[64]; var result = reader.Read(buffer, 3000, out var transferred); if (result == Error.Success) { Console.WriteLine($"Read {transferred} bytes"); } else if (result == Error.Timeout) { Console.WriteLine("Read operation timed out"); } else if (result == Error.NoDevice) { Console.WriteLine("Device was disconnected"); } else { Console.WriteLine($"Read failed with error: {result}"); } device.ReleaseInterface(0); device.Close(); } catch (UsbException ex) { Console.WriteLine($"USB error: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.Message}"); } ``` -------------------------------- ### Initialize UsbEndpointTransferQueueReader Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/3-endpoints.md Constructor for initializing the reader with device, buffer, and queue configuration. ```csharp public UsbEndpointTransferQueueReader(IUsbDevice usbDevice, int readBufferSize, byte alternateInterfaceID, ReadEndpointID readEndpointID, CancellationToken cancellationToken, int transferQueueSize = 1) ``` -------------------------------- ### ToString Method Signature Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Returns a string representation of the device. ```csharp public override string ToString() ``` -------------------------------- ### UsbContext Constructor Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Initializes a new instance of the UsbContext class. ```csharp public UsbContext() ``` -------------------------------- ### Implement Robust USB Device Access with Retries Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/6-errors-and-exceptions.md A C# class demonstrating how to manage device connections, perform reads with retry logic for timeouts, and handle specific USB exceptions. ```csharp public class RobustUsbDeviceAccess { private readonly IUsbDevice device; private readonly int maxRetries = 3; private readonly int timeoutMs = 5000; public RobustUsbDeviceAccess(IUsbDevice device) { this.device = device; } public bool TryReadWithRetry(byte[] buffer, out int bytesRead, out Error error) { bytesRead = 0; error = Error.Other; for (int attempt = 0; attempt < maxRetries; attempt++) { try { if (!device.IsOpen) device.Open(); var reader = device.OpenEndpointReader(ReadEndpointID.Ep01); error = reader.Read(buffer, timeoutMs, out bytesRead); if (error == Error.Success) return true; if (error == Error.NoDevice) { Console.WriteLine("Device disconnected"); return false; // Don't retry } if (error == Error.Timeout && attempt < maxRetries - 1) { System.Threading.Thread.Sleep(100); continue; // Retry } return false; } catch (UsbException ex) { error = ex.ErrorCode; if (ex.ErrorCode == Error.Access) { Console.WriteLine("Permission denied - check device access"); return false; // Don't retry } } } return false; } } ``` -------------------------------- ### List() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Returns a collection of all USB devices currently attached to the system. ```APIDOC ## List() ### Description Returns a collection of all USB devices currently attached to the system. This is the primary entry point for finding USB devices. ### Returns - **UsbDeviceCollection** - A collection containing all detected devices. ### Example ```csharp using var devices = context.List(); foreach (var device in devices) { Console.WriteLine($"Device: {device.VendorId:X04}:{device.ProductId:X04}"); } ``` -------------------------------- ### Clone() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Creates a clone of the device reference. ```APIDOC ## Clone() ### Description Creates a clone of this device (references the same underlying device). ### Returns - **IUsbDevice** - A clone of the device ``` -------------------------------- ### UsbContext Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md The primary entry point for the library, used to manage USB contexts, enumerate devices, and handle hotplug events. ```APIDOC ## UsbContext ### Description Primary entry point for managing USB contexts, enumerating devices, and handling hotplug events. ### Usage ```csharp using var context = new UsbContext(); var devices = context.List(); ``` ``` -------------------------------- ### Equals(object obj) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Compares two device instances. ```APIDOC ## Equals(object obj) ### Description Compares devices by their hash code (underlying device handle). ### Signature `public override bool Equals(object obj)` ``` -------------------------------- ### TryOpen USB Device Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Attempts to open the device without throwing an exception, returning a boolean status. ```csharp var device = context.Find(...); if (device.TryOpen()) { // Device is open } ``` -------------------------------- ### Initialize UsbEndpointReader Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/3-endpoints.md Constructor for creating a reader instance, typically invoked via UsbDevice.OpenEndpointReader(). ```csharp public UsbEndpointReader(IUsbDevice usbDevice, int readBufferSize, byte alternateInterfaceID, ReadEndpointID readEndpointID, EndpointType endpointType) ``` -------------------------------- ### Capability Enumeration Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/9-api-index.md Enumeration for platform-specific USB capabilities. ```csharp public enum Capability : uint ``` -------------------------------- ### TryGetConfigDescriptor(byte configIndex, out UsbConfigInfo descriptor) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Attempts to retrieve a configuration descriptor for the device. ```APIDOC ## TryGetConfigDescriptor(byte configIndex, out UsbConfigInfo descriptor) ### Description Attempts to get a configuration descriptor. ### Parameters - **configIndex** (byte) - Required - Configuration index - **descriptor** (out UsbConfigInfo) - Required - Resulting configuration descriptor ### Returns - **bool** - true if successful, false otherwise ``` -------------------------------- ### Handle DeviceEvent Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Demonstrates subscribing to DeviceEvent to handle device arrival and removal notifications. ```csharp context.DeviceEvent += (sender, e) => { if (e is DeviceArrivedEventArgs arrived) { Console.WriteLine($"Device connected: {arrived.Device.VendorId:X04}:{arrived.Device.ProductId:X04}"); } else if (e is DeviceLeftEventArgs left) { Console.WriteLine($"Device disconnected: {left.DeviceInfo}"); } }; ``` -------------------------------- ### Equals Method Signature Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Compares devices based on their underlying device handle hash code. ```csharp public override bool Equals(object obj) ``` -------------------------------- ### Perform Minimal USB Read Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Locate a device by VID/PID, claim an interface, and read data from a specific endpoint. ```csharp using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; using var context = new UsbContext(); var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); device?.Open(); device?.ClaimInterface(0); var reader = device?.OpenEndpointReader(ReadEndpointID.Ep01); var buffer = new byte[64]; reader?.Read(buffer, 3000, out var read); Console.WriteLine($"Read {read} bytes"); device?.Close(); ``` -------------------------------- ### Retrieve USB Device Information Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Shows how to access device descriptors, strings, and iterate through configurations, interfaces, and endpoints. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; using var context = new UsbContext(); var device = context.Find(new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }); if (device == null) return; device.Open(); var info = device.Info; Console.WriteLine($"Device Information:"); Console.WriteLine($" Vendor ID: 0x{info.VendorId:X04}"); Console.WriteLine($" Product ID: 0x{info.ProductId:X04}"); Console.WriteLine($" Device: {info.Device:X04}"); Console.WriteLine($" Manufacturer: {info.Manufacturer}"); Console.WriteLine($" Product: {info.Product}"); Console.WriteLine($" Serial Number: {info.SerialNumber}"); Console.WriteLine($" USB Version: {info.Usb}"); Console.WriteLine($" Device Class: {info.DeviceClass}"); Console.WriteLine($" Device Subclass: {info.DeviceSubClass}"); Console.WriteLine($" Device Protocol: {info.DeviceProtocol}"); Console.WriteLine($" Max Control Packet Size: {info.MaxPacketSize0}"); Console.WriteLine($" Number of Configurations: {info.NumConfigurations}"); Console.WriteLine($"\nConfigurations:"); foreach (var config in device.Configs) { Console.WriteLine($" Config {config.Value}: {config.Description}"); Console.WriteLine($" Attributes: 0x{config.Attributes:X02}"); Console.WriteLine($" Max Power: {config.MaxPower}mA"); foreach (var iface in config.Interfaces) { Console.WriteLine($" Interface {iface.Number}: {iface.Description}"); Console.WriteLine($" Class: 0x{iface.Class:X02} Subclass: 0x{iface.SubClass:X02}"); foreach (var endpoint in iface.Endpoints) { string dir = (endpoint.EndpointID & 0x80) != 0 ? "IN" : "OUT"; Console.WriteLine($" Endpoint 0x{endpoint.EndpointID:X02} ({dir}): " + $"Type={endpoint.Type} MaxPacketSize={endpoint.MaxPacketSize}"); } } } device.Close(); ``` -------------------------------- ### Enumerate USB Devices Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Lists all connected USB devices and displays their Vendor ID and Product ID. Requires a valid UsbContext instance. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using var context = new UsbContext(); using var devices = context.List(); Console.WriteLine($"Found {devices.Count} USB devices:\n"); foreach (var device in devices) { Console.WriteLine($"VID:PID = {device.VendorId:X04}:{device.ProductId:X04}"); Console.WriteLine($" Device Info: {device.Info}"); Console.WriteLine(); } ``` -------------------------------- ### Test USB Error Handling in C# Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/6-errors-and-exceptions.md Verifies that attempting to open a non-existent device results in the expected UsbException with an Error.NoDevice code. ```csharp [Test] public void TestErrorHandling() { using var context = new UsbContext(); var device = context.Find(new UsbDeviceFinder { Vid = 0x9999 }); Assert.IsNull(device, "Non-existent device should return null"); if (device != null) { try { device.Open(); Assert.Fail("Should not reach here"); } catch (UsbException ex) { Assert.That(ex.ErrorCode, Is.EqualTo(Error.NoDevice)); } } } ``` -------------------------------- ### Send Control Command Pattern Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Send a control command to the device. ```csharp var setup = new UsbSetupPacket(0xC0, 0x06, 0x0100, 0, 64); var buffer = new byte[64]; device.ControlTransfer(setup, buffer, 0, 64); ``` -------------------------------- ### Set Configuration (0x09) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Sets the active configuration for the device. ```APIDOC ## Set Configuration (0x09) ### Description Sets the active configuration of the device. ### Method ControlTransfer ### Parameters - **configValue** (int) - Required - The configuration value to set. ### Code Example ```csharp var setup = new UsbSetupPacket( UsbCtrlFlags.RequestOut | UsbCtrlFlags.RecipientDevice, 0x09, configValue, 0, 0 ); device.ControlTransfer(setup); ``` ``` -------------------------------- ### Monitor Device Hotplug Events Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Shows how to subscribe to device arrival and departure events and register for hotplug notifications. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using System; using var context = new UsbContext(); // Subscribe to device events context.DeviceEvent += (sender, e) => { if (e is DeviceArrivedEventArgs arrived) { var device = arrived.Device; Console.WriteLine($"Device arrived: {device.VendorId:X04}:{device.ProductId:X04}"); } else if (e is DeviceLeftEventArgs left) { Console.WriteLine($"Device left: {left.DeviceInfo}"); } }; // Enable hotplug try { context.RegisterHotPlug(); Console.WriteLine("Hotplug monitoring enabled. Press Enter to exit..."); Console.ReadLine(); } catch (PlatformNotSupportedException) { Console.WriteLine("Hotplug is not supported on this platform"); } finally { context.UnregisterHotPlug(); } ``` -------------------------------- ### Clone USB Device Reference Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Use Clone() to maintain a valid device reference after the parent device collection is disposed. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using var context = new UsbContext(); IUsbDevice myDevice; // Find and clone device using (var devices = context.List()) { var found = devices.FirstOrDefault(d => d.VendorId == 0x04B4); if (found != null) { myDevice = found.Clone(); // Clone to keep reference } else { return; } } // devices collection disposed, but myDevice still valid using (myDevice) { myDevice.Open(); // Use device... myDevice.Close(); } ``` -------------------------------- ### ToString() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Returns a string representation of the device. ```APIDOC ## ToString() ### Description Returns a string representation of the device. Shows device descriptor if open, otherwise shows VID:PID. ### Signature `public override string ToString()` ``` -------------------------------- ### Open Endpoint Writer with Type Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Opens an endpoint for writing with a specified endpoint type. ```csharp public UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID, EndpointType endpointType) ``` -------------------------------- ### Check Device Match Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Tests if a specific device matches the criteria defined in the finder instance. ```csharp public bool Check(IUsbDevice device) ``` -------------------------------- ### Async Device Waiting Pattern Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Wait for a device arrival with a timeout and cancellation token. ```csharp var device = await manager.WaitForDeviceArrival( new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }, TimeSpan.FromSeconds(30), cancellationToken); ``` -------------------------------- ### Read Device Descriptor in C# Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/7-control-transfers.md Uses a UsbSetupPacket to request the device descriptor from a connected USB device. ```csharp public static bool ReadDeviceDescriptor(IUsbDevice device, out byte[] descriptor) { descriptor = null; var setup = new UsbSetupPacket( UsbCtrlFlags.RequestIn | UsbCtrlFlags.RecipientDevice, 0x06, // Get Descriptor (1 << 8) | 0, // Device descriptor, index 0 0, // Language ID (not used for device descriptor) 18 // Device descriptor length ); var buffer = new byte[18]; try { int transferred = device.ControlTransfer(setup, buffer, 0, 18); if (transferred >= 18) { descriptor = buffer; return true; } } catch (UsbException ex) { Console.WriteLine($"Failed to read device descriptor: {ex.Message}"); } return false; } ``` -------------------------------- ### Check IsOpen Status Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Indicates if the device is currently open for communication. ```csharp public bool IsOpen { get; } ``` -------------------------------- ### Set USB Device Configuration Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Sets the active configuration for the device. Only one configuration can be active at a time. ```csharp device.SetConfiguration(device.Configs[0].Value); ``` -------------------------------- ### UsbDeviceFinder Constructor Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Initializes a new instance of the UsbDeviceFinder class with all criteria unset, meaning it will match any device. ```APIDOC ## public UsbDeviceFinder() ### Description Creates a finder with all criteria unset (matches any device). ### Signature `public UsbDeviceFinder()` ``` -------------------------------- ### Handle Device Arrival and Removal Events Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Subscribes to device events to detect when a device is connected or disconnected. ```csharp context.DeviceEvent += (sender, e) => { if (e is DeviceArrivedEventArgs arrived) { Console.WriteLine($"Device arrived: {arrived.Device.VendorId:X04}:{arrived.Device.ProductId:X04}"); } else if (e is DeviceLeftEventArgs left) { Console.WriteLine($"Device left: {left.DeviceInfo}"); } }; ``` -------------------------------- ### Dispose() Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/1-usbcontext.md Closes all open devices on the context and releases all native resources. ```APIDOC ## Dispose() ### Description Closes all open devices on this context and releases all native resources. ### Method public void Dispose() ### Parameters - None ### Returns - None ### Example ```csharp using (var context = new UsbContext()) { // Use context } // Dispose called automatically ``` ``` -------------------------------- ### Wait for USB device arrival asynchronously Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/8-quickstart.md Uses DeviceManager to wait for a specific device by VID/PID with a cancellation token and timeout. ```csharp using LibUsbDotNet; using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; using System.Threading; using var context = new UsbContext(); var manager = new DeviceManager(context); manager.Start(); try { var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var device = await manager.WaitForDeviceArrival( new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }, TimeSpan.FromSeconds(30), cts.Token); if (device != null) { Console.WriteLine("Device found!"); device.Open(); // Use device... device.Close(); } else { Console.WriteLine("Timeout waiting for device"); } } finally { manager.Stop(); } ``` -------------------------------- ### Open USB Endpoint Reader Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Opens a bulk endpoint for reading. Returns a reader instance ready for data transfer. ```csharp var reader = device.OpenEndpointReader(ReadEndpointID.Ep01); var buffer = new byte[64]; reader.Read(buffer, 3000, out var bytesRead); ``` -------------------------------- ### Find Device by Identifiers Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/README.md Locate a specific device using VID and PID. ```csharp var finder = new UsbDeviceFinder { Vid = 0x04B4, Pid = 0x00F0 }; var device = context.Find(finder); ``` -------------------------------- ### UsbException Constructor Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/6-errors-and-exceptions.md Initializes a new instance of the UsbException class with a specific libusb error code. ```APIDOC ## Constructor: UsbException(Error errorCode) ### Description Creates a new exception instance based on a libusb error code. ### Parameters - **errorCode** (Error) - Required - The libusb error that occurred. ### Example ```csharp throw new UsbException(Error.NoDevice); ``` ``` -------------------------------- ### Speed Enumeration Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/9-api-index.md Enumeration for USB device speeds. ```csharp public enum Speed ``` -------------------------------- ### SetConfiguration(int config) Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/2-usbdevice.md Sets the active configuration for this device. ```APIDOC ## SetConfiguration(int config) ### Description Sets the active configuration for this device. Only one configuration can be active at a time. ### Parameters - **config** (int): Configuration value (typically from Configs[i].Value) ### Throws - `UsbException`: On failure. ``` -------------------------------- ### Define Product ID Criteria Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Sets the Product ID for device matching. Use int.MaxValue to ignore this property. ```csharp public int Pid { get; init; } ``` -------------------------------- ### Access Device by Index Source: https://github.com/libusbdotnet/libusbdotnet/blob/master/_autodocs/5-device-finder-and-info.md Provides indexed access to individual IUsbDevice instances within the collection. ```csharp public IUsbDevice this[int index] { get; } ```