using System; using System.Collections; using System.Collections.Generic; using System.Linq; using HidSharp; using RGB.NET.Core; namespace RGB.NET.HID; /// /// Represents the data used to define a HID-device. /// /// The type of the identifier leds are mapped to. /// The type of the custom data added to the HID-device. public record HIDDeviceDefinition(int ProductId, RGBDeviceType DeviceType, string Name, LedMapping LedMapping, TData CustomData) where TLed : notnull; /// /// Represents a loaded for HID-devices based on the specified definitions. /// /// The type of the identifier leds are mapped to. /// The type of the custom data added to the HID-device. public sealed class HIDLoader : IEnumerable> where TLed : notnull { #region Properties & Fields private readonly Dictionary> _deviceDefinitions = []; /// /// Gets the vendor id used for this loader. /// public int VendorId { get; } /// /// Gets or sets the filter used to determine which devices should be loaded. /// public RGBDeviceType LoadFilter { get; set; } = RGBDeviceType.All; #endregion #region Constructors /// /// Initializes a new instance of the class. /// /// The vendor id used for this loader. public HIDLoader(int vendorId) { this.VendorId = vendorId; } #endregion #region Methods /// /// Adds a new to this loader. /// /// The product id of the HID-device. /// The type of the device. /// The name of the device. /// The mapping of the leds of the device. /// Some custom data to attach to the device. public void Add(int productId, RGBDeviceType deviceType, string name, LedMapping ledMapping, TData customData) => _deviceDefinitions.Add(productId, new HIDDeviceDefinition(productId, deviceType, name, ledMapping, customData)); /// /// Gets a enumerable containing all devices from the definition-list that are connected and match the . /// /// The enumerable containing the connected devices. public IEnumerable<(HIDDeviceDefinition definition, HidDevice device)> GetConnectedDevices() { IEnumerable devices = DeviceList.Local.GetHidDevices(VendorId); foreach (HidDevice device in devices) { if (_deviceDefinitions.TryGetValue(device.ProductID, out HIDDeviceDefinition? definition)) if (LoadFilter.HasFlag(definition.DeviceType)) yield return (definition, device); } } /// /// Gets a enumerable containing all the first device of each group of devices from the definition-list that are connected and match the . /// The grouping is done by the specified function. /// /// The type of the key used to group the devices. /// The function grouping the devices. /// The enumerable containing the selected devices. public IEnumerable<(HIDDeviceDefinition definition, HidDevice device)> GetConnectedDevices(Func, TKey> groupBy) => GetConnectedDevices().GroupBy(x => groupBy(x.definition)) .Select(group => group.First()); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// public IEnumerator> GetEnumerator() => _deviceDefinitions.Values.GetEnumerator(); #endregion }