1
0
mirror of https://github.com/DarthAffe/RGB.NET.git synced 2025-12-13 10:08:31 +00:00

Fixed warnings

This commit is contained in:
Darth Affe 2021-02-02 23:37:56 +01:00
parent 57dc9afb32
commit a0a1521658
118 changed files with 802 additions and 1181 deletions

View File

@ -29,7 +29,7 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _origin, value); set => SetProperty(ref _origin, value);
} }
private Point _center = new Point(0.5, 0.5); private Point _center = new(0.5, 0.5);
/// <summary> /// <summary>
/// Gets or sets the center <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="ConicalGradientBrush"/>. (default: 0.5, 0.5) /// Gets or sets the center <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="ConicalGradientBrush"/>. (default: 0.5, 0.5)
/// </summary> /// </summary>
@ -39,12 +39,12 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _center, value); set => SetProperty(ref _center, value);
} }
private IGradient _gradient; private IGradient? _gradient;
/// <inheritdoc /> /// <inheritdoc />
/// <summary> /// <summary>
/// Gets or sets the gradient drawn by the brush. If null it will default to full transparent. /// Gets or sets the gradient drawn by the brush. If null it will default to full transparent.
/// </summary> /// </summary>
public IGradient Gradient public IGradient? Gradient
{ {
get => _gradient; get => _gradient;
set => SetProperty(ref _gradient, value); set => SetProperty(ref _gradient, value);
@ -104,6 +104,8 @@ namespace RGB.NET.Brushes
/// <inheritdoc /> /// <inheritdoc />
protected override Color GetColorAtPoint(Rectangle rectangle, BrushRenderTarget renderTarget) protected override Color GetColorAtPoint(Rectangle rectangle, BrushRenderTarget renderTarget)
{ {
if (Gradient == null) return Color.Transparent;
double centerX = rectangle.Size.Width * Center.X; double centerX = rectangle.Size.Width * Center.X;
double centerY = rectangle.Size.Height * Center.Y; double centerY = rectangle.Size.Height * Center.Y;

View File

@ -12,6 +12,6 @@ namespace RGB.NET.Brushes
/// <summary> /// <summary>
/// Gets the <see cref="IGradient"/> used by this <see cref="IGradientBrush"/>. /// Gets the <see cref="IGradient"/> used by this <see cref="IGradientBrush"/>.
/// </summary> /// </summary>
IGradient Gradient { get; } IGradient? Gradient { get; }
} }
} }

View File

@ -20,7 +20,7 @@ namespace RGB.NET.Brushes
{ {
#region Properties & Fields #region Properties & Fields
private Point _startPoint = new Point(0, 0.5); private Point _startPoint = new(0, 0.5);
/// <summary> /// <summary>
/// Gets or sets the start <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="LinearGradientBrush"/>. (default: 0.0, 0.5) /// Gets or sets the start <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="LinearGradientBrush"/>. (default: 0.0, 0.5)
/// </summary> /// </summary>
@ -30,7 +30,7 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _startPoint, value); set => SetProperty(ref _startPoint, value);
} }
private Point _endPoint = new Point(1, 0.5); private Point _endPoint = new(1, 0.5);
/// <summary> /// <summary>
/// Gets or sets the end <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="LinearGradientBrush"/>. (default: 1.0, 0.5) /// Gets or sets the end <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="LinearGradientBrush"/>. (default: 1.0, 0.5)
/// </summary> /// </summary>
@ -40,9 +40,9 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _endPoint, value); set => SetProperty(ref _endPoint, value);
} }
private IGradient _gradient; private IGradient? _gradient;
/// <inheritdoc /> /// <inheritdoc />
public IGradient Gradient public IGradient? Gradient
{ {
get => _gradient; get => _gradient;
set => SetProperty(ref _gradient, value); set => SetProperty(ref _gradient, value);
@ -97,8 +97,8 @@ namespace RGB.NET.Brushes
{ {
if (Gradient == null) return Color.Transparent; if (Gradient == null) return Color.Transparent;
Point startPoint = new Point(StartPoint.X * rectangle.Size.Width, StartPoint.Y * rectangle.Size.Height); Point startPoint = new(StartPoint.X * rectangle.Size.Width, StartPoint.Y * rectangle.Size.Height);
Point endPoint = new Point(EndPoint.X * rectangle.Size.Width, EndPoint.Y * rectangle.Size.Height); Point endPoint = new(EndPoint.X * rectangle.Size.Width, EndPoint.Y * rectangle.Size.Height);
double offset = GradientHelper.CalculateLinearGradientOffset(startPoint, endPoint, renderTarget.Point); double offset = GradientHelper.CalculateLinearGradientOffset(startPoint, endPoint, renderTarget.Point);
return Gradient.GetColor(offset); return Gradient.GetColor(offset);

View File

@ -18,7 +18,7 @@ namespace RGB.NET.Brushes
{ {
#region Properties & Fields #region Properties & Fields
private Point _center = new Point(0.5, 0.5); private Point _center = new(0.5, 0.5);
/// <summary> /// <summary>
/// Gets or sets the center <see cref="Point"/> (as percentage in the range [0..1]) around which the <see cref="RadialGradientBrush"/> should be drawn. (default: 0.5, 0.5) /// Gets or sets the center <see cref="Point"/> (as percentage in the range [0..1]) around which the <see cref="RadialGradientBrush"/> should be drawn. (default: 0.5, 0.5)
/// </summary> /// </summary>
@ -28,9 +28,9 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _center, value); set => SetProperty(ref _center, value);
} }
private IGradient _gradient; private IGradient? _gradient;
/// <inheritdoc /> /// <inheritdoc />
public IGradient Gradient public IGradient? Gradient
{ {
get => _gradient; get => _gradient;
set => SetProperty(ref _gradient, value); set => SetProperty(ref _gradient, value);
@ -78,7 +78,7 @@ namespace RGB.NET.Brushes
{ {
if (Gradient == null) return Color.Transparent; if (Gradient == null) return Color.Transparent;
Point centerPoint = new Point(rectangle.Location.X + (rectangle.Size.Width * Center.X), rectangle.Location.Y + (rectangle.Size.Height * Center.Y)); Point centerPoint = new(rectangle.Location.X + (rectangle.Size.Width * Center.X), rectangle.Location.Y + (rectangle.Size.Height * Center.Y));
// Calculate the distance to the farthest point from the center as reference (this has to be a corner) // Calculate the distance to the farthest point from the center as reference (this has to be a corner)
// ReSharper disable once RedundantCast - never trust this ... // ReSharper disable once RedundantCast - never trust this ...

View File

@ -52,7 +52,7 @@ namespace RGB.NET.Brushes
/// Converts a <see cref="Color" /> to a <see cref="SolidColorBrush" />. /// Converts a <see cref="Color" /> to a <see cref="SolidColorBrush" />.
/// </summary> /// </summary>
/// <param name="color">The <see cref="Color"/> to convert.</param> /// <param name="color">The <see cref="Color"/> to convert.</param>
public static explicit operator SolidColorBrush(Color color) => new SolidColorBrush(color); public static explicit operator SolidColorBrush(Color color) => new(color);
/// <summary> /// <summary>
/// Converts a <see cref="SolidColorBrush" /> to a <see cref="Color" />. /// Converts a <see cref="SolidColorBrush" /> to a <see cref="Color" />.

View File

@ -23,7 +23,7 @@ namespace RGB.NET.Brushes.Gradients
/// <summary> /// <summary>
/// Gets a list of the stops used by this <see cref="AbstractGradient"/>. /// Gets a list of the stops used by this <see cref="AbstractGradient"/>.
/// </summary> /// </summary>
public ObservableCollection<GradientStop> GradientStops { get; } = new ObservableCollection<GradientStop>(); public ObservableCollection<GradientStop> GradientStops { get; } = new();
private bool _wrapGradient; private bool _wrapGradient;
/// <summary> /// <summary>
@ -42,7 +42,7 @@ namespace RGB.NET.Brushes.Gradients
#region Events #region Events
/// <inheritdoc /> /// <inheritdoc />
public event EventHandler GradientChanged; public event EventHandler? GradientChanged;
#endregion #endregion
@ -54,7 +54,7 @@ namespace RGB.NET.Brushes.Gradients
protected AbstractGradient() protected AbstractGradient()
{ {
GradientStops.CollectionChanged += GradientCollectionChanged; GradientStops.CollectionChanged += GradientCollectionChanged;
PropertyChanged += (sender, args) => OnGradientChanged(); PropertyChanged += (_, _) => OnGradientChanged();
} }
/// <summary> /// <summary>
@ -64,7 +64,7 @@ namespace RGB.NET.Brushes.Gradients
protected AbstractGradient(params GradientStop[] gradientStops) protected AbstractGradient(params GradientStop[] gradientStops)
{ {
GradientStops.CollectionChanged += GradientCollectionChanged; GradientStops.CollectionChanged += GradientCollectionChanged;
PropertyChanged += (sender, args) => OnGradientChanged(); PropertyChanged += (_, _) => OnGradientChanged();
foreach (GradientStop gradientStop in gradientStops) foreach (GradientStop gradientStop in gradientStops)
GradientStops.Add(gradientStop); GradientStops.Add(gradientStop);
@ -80,7 +80,7 @@ namespace RGB.NET.Brushes.Gradients
this.WrapGradient = wrapGradient; this.WrapGradient = wrapGradient;
GradientStops.CollectionChanged += GradientCollectionChanged; GradientStops.CollectionChanged += GradientCollectionChanged;
PropertyChanged += (sender, args) => OnGradientChanged(); PropertyChanged += (_, _) => OnGradientChanged();
foreach (GradientStop gradientStop in gradientStops) foreach (GradientStop gradientStop in gradientStops)
GradientStops.Add(gradientStop); GradientStops.Add(gradientStop);
@ -128,9 +128,9 @@ namespace RGB.NET.Brushes.Gradients
/// <summary> /// <summary>
/// Should be called to indicate that the gradient was changed. /// Should be called to indicate that the gradient was changed.
/// </summary> /// </summary>
protected void OnGradientChanged() => GradientChanged?.Invoke(this, null); protected void OnGradientChanged() => GradientChanged?.Invoke(this, EventArgs.Empty);
private void GradientCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) private void GradientCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{ {
if (e.OldItems != null) if (e.OldItems != null)
foreach (GradientStop gradientStop in e.OldItems) foreach (GradientStop gradientStop in e.OldItems)
@ -143,7 +143,7 @@ namespace RGB.NET.Brushes.Gradients
OnGradientChanged(); OnGradientChanged();
} }
private void GradientStopChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) => OnGradientChanged(); private void GradientStopChanged(object? sender, PropertyChangedEventArgs propertyChangedEventArgs) => OnGradientChanged();
#endregion #endregion
} }

View File

@ -16,7 +16,7 @@ namespace RGB.NET.Brushes.Gradients
#region Properties & Fields #region Properties & Fields
private bool _isOrderedGradientListDirty = true; private bool _isOrderedGradientListDirty = true;
private LinkedList<GradientStop> _orderedGradientStops; private LinkedList<GradientStop> _orderedGradientStops = new();
#endregion #endregion
@ -60,12 +60,12 @@ namespace RGB.NET.Brushes.Gradients
private void Initialize() private void Initialize()
{ {
void OnGradientStopOnPropertyChanged(object sender, PropertyChangedEventArgs args) => _isOrderedGradientListDirty = true; void OnGradientStopOnPropertyChanged(object? sender, PropertyChangedEventArgs args) => _isOrderedGradientListDirty = true;
foreach (GradientStop gradientStop in GradientStops) foreach (GradientStop gradientStop in GradientStops)
gradientStop.PropertyChanged += OnGradientStopOnPropertyChanged; gradientStop.PropertyChanged += OnGradientStopOnPropertyChanged;
GradientStops.CollectionChanged += (sender, args) => GradientStops.CollectionChanged += (_, args) =>
{ {
if (args.OldItems != null) if (args.OldItems != null)
foreach (GradientStop gradientStop in args.OldItems) foreach (GradientStop gradientStop in args.OldItems)
@ -114,18 +114,18 @@ namespace RGB.NET.Brushes.Gradients
/// <returns></returns> /// <returns></returns>
protected virtual (GradientStop gsBefore, GradientStop gsAfter) GetEnclosingGradientStops(double offset, LinkedList<GradientStop> orderedStops, bool wrap) protected virtual (GradientStop gsBefore, GradientStop gsAfter) GetEnclosingGradientStops(double offset, LinkedList<GradientStop> orderedStops, bool wrap)
{ {
LinkedList<GradientStop> gradientStops = new LinkedList<GradientStop>(orderedStops); LinkedList<GradientStop> gradientStops = new(orderedStops);
if (wrap) if (wrap)
{ {
GradientStop gsBefore, gsAfter; GradientStop? gsBefore, gsAfter;
do do
{ {
gsBefore = gradientStops.LastOrDefault(n => n.Offset <= offset); gsBefore = gradientStops.LastOrDefault(n => n.Offset <= offset);
if (gsBefore == null) if (gsBefore == null)
{ {
GradientStop lastStop = gradientStops.Last.Value; GradientStop lastStop = gradientStops.Last!.Value;
gradientStops.AddFirst(new GradientStop(lastStop.Offset - 1, lastStop.Color)); gradientStops.AddFirst(new GradientStop(lastStop.Offset - 1, lastStop.Color));
gradientStops.RemoveLast(); gradientStops.RemoveLast();
} }
@ -133,7 +133,7 @@ namespace RGB.NET.Brushes.Gradients
gsAfter = gradientStops.FirstOrDefault(n => n.Offset >= offset); gsAfter = gradientStops.FirstOrDefault(n => n.Offset >= offset);
if (gsAfter == null) if (gsAfter == null)
{ {
GradientStop firstStop = gradientStops.First.Value; GradientStop firstStop = gradientStops.First!.Value;
gradientStops.AddLast(new GradientStop(firstStop.Offset + 1, firstStop.Color)); gradientStops.AddLast(new GradientStop(firstStop.Offset + 1, firstStop.Color));
gradientStops.RemoveFirst(); gradientStops.RemoveFirst();
} }

View File

@ -41,7 +41,7 @@ namespace RGB.NET.Brushes.Gradients
#region Events #region Events
/// <inheritdoc /> /// <inheritdoc />
public event EventHandler GradientChanged; public event EventHandler? GradientChanged;
#endregion #endregion
@ -57,7 +57,7 @@ namespace RGB.NET.Brushes.Gradients
this.StartHue = startHue; this.StartHue = startHue;
this.EndHue = endHue; this.EndHue = endHue;
PropertyChanged += (sender, args) => OnGradientChanged(); PropertyChanged += (_, _) => OnGradientChanged();
} }
#endregion #endregion
@ -101,7 +101,7 @@ namespace RGB.NET.Brushes.Gradients
/// <summary> /// <summary>
/// Should be called to indicate that the gradient was changed. /// Should be called to indicate that the gradient was changed.
/// </summary> /// </summary>
protected void OnGradientChanged() => GradientChanged?.Invoke(this, null); protected void OnGradientChanged() => GradientChanged?.Invoke(this, EventArgs.Empty);
#endregion #endregion
} }

View File

@ -35,7 +35,7 @@ namespace RGB.NET.Core
public Rectangle RenderedRectangle { get; protected set; } public Rectangle RenderedRectangle { get; protected set; }
/// <inheritdoc /> /// <inheritdoc />
public Dictionary<BrushRenderTarget, Color> RenderedTargets { get; } = new Dictionary<BrushRenderTarget, Color>(); public Dictionary<BrushRenderTarget, Color> RenderedTargets { get; } = new();
#endregion #endregion

View File

@ -15,7 +15,7 @@
/// </summary> /// </summary>
/// <param name="obj">The object to test.</param> /// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Color" /> equivalent to this <see cref="Color" />; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Color" /> equivalent to this <see cref="Color" />; otherwise, <c>false</c>.</returns>
public virtual bool Equals(Color color, object obj) public virtual bool Equals(Color color, object? obj)
{ {
if (!(obj is Color)) return false; if (!(obj is Color)) return false;

View File

@ -29,7 +29,7 @@ namespace RGB.NET.Core
/// <summary> /// <summary>
/// Gets a readonly-list of all <see cref="IDecoratable"/> this decorator is attached to. /// Gets a readonly-list of all <see cref="IDecoratable"/> this decorator is attached to.
/// </summary> /// </summary>
protected List<IDecoratable> DecoratedObjects { get; } = new List<IDecoratable>(); protected List<IDecoratable> DecoratedObjects { get; } = new();
#endregion #endregion
@ -46,7 +46,7 @@ namespace RGB.NET.Core
/// </summary> /// </summary>
protected virtual void Detach() protected virtual void Detach()
{ {
List<IDecoratable> decoratables = new List<IDecoratable>(DecoratedObjects); List<IDecoratable> decoratables = new(DecoratedObjects);
foreach (IDecoratable decoratable in decoratables) foreach (IDecoratable decoratable in decoratables)
{ {
IEnumerable<Type> types = decoratable.GetType().GetInterfaces().Where(t => t.IsGenericType IEnumerable<Type> types = decoratable.GetType().GetInterfaces().Where(t => t.IsGenericType

View File

@ -131,7 +131,7 @@ namespace RGB.NET.Core
DeviceUpdate(); DeviceUpdate();
// Send LEDs to SDK // Send LEDs to SDK
List<Led> ledsToUpdate = GetLedsToUpdate(flushLeds)?.ToList() ?? new List<Led>(); List<Led> ledsToUpdate = GetLedsToUpdate(flushLeds).ToList();
foreach (Led ledToUpdate in ledsToUpdate) foreach (Led ledToUpdate in ledsToUpdate)
ledToUpdate.Update(); ledToUpdate.Update();

View File

@ -13,7 +13,7 @@ namespace RGB.NET.Core
/// <param name="x">The x-ammount to move.</param> /// <param name="x">The x-ammount to move.</param>
/// <param name="y">The y-ammount to move.</param> /// <param name="y">The y-ammount to move.</param>
/// <returns>The new location of the point.</returns> /// <returns>The new location of the point.</returns>
public static Point Translate(this Point point, double x = 0, double y = 0) => new Point(point.X + x, point.Y + y); public static Point Translate(this Point point, double x = 0, double y = 0) => new(point.X + x, point.Y + y);
/// <summary> /// <summary>
/// Rotates the specified <see cref="Point"/> by the given amuont around the given origin. /// Rotates the specified <see cref="Point"/> by the given amuont around the given origin.
@ -22,7 +22,7 @@ namespace RGB.NET.Core
/// <param name="rotation">The rotation.</param> /// <param name="rotation">The rotation.</param>
/// <param name="origin">The origin to rotate around. [0,0] if not set.</param> /// <param name="origin">The origin to rotate around. [0,0] if not set.</param>
/// <returns>The new location of the point.</returns> /// <returns>The new location of the point.</returns>
public static Point Rotate(this Point point, Rotation rotation, Point origin = new Point()) public static Point Rotate(this Point point, Rotation rotation, Point origin = new())
{ {
double sin = Math.Sin(rotation.Radians); double sin = Math.Sin(rotation.Radians);
double cos = Math.Cos(rotation.Radians); double cos = Math.Cos(rotation.Radians);

View File

@ -1,44 +0,0 @@
using System;
using System.Globalization;
using System.Runtime.InteropServices;
namespace RGB.NET.Core
{
/// <summary>
/// Offers some helper-methods for culture related things.
/// </summary>
public static class CultureHelper
{
#region DLLImports
[DllImport("user32.dll")]
private static extern IntPtr GetKeyboardLayout(uint thread);
#endregion
#region Constructors
#endregion
#region Methods
/// <summary>
/// Gets the current keyboard-layout from the OS.
/// </summary>
/// <returns>The current keyboard-layout</returns>
public static CultureInfo GetCurrentCulture()
{
try
{
int keyboardLayout = GetKeyboardLayout(0).ToInt32() & 0xFFFF;
return new CultureInfo(keyboardLayout);
}
catch
{
return new CultureInfo(1033); // en-US on error.
}
}
#endregion
}
}

View File

@ -14,7 +14,7 @@ namespace RGB.NET.Core
{ {
#region Properties & Fields #region Properties & Fields
private readonly object _dataLock = new object(); private readonly object _dataLock = new();
private readonly IDeviceUpdateTrigger _updateTrigger; private readonly IDeviceUpdateTrigger _updateTrigger;
private Dictionary<TIdentifier, TData>? _currentDataSet; private Dictionary<TIdentifier, TData>? _currentDataSet;

View File

@ -5,6 +5,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Globalization; using System.Globalization;
using System.Linq;
using AuraServiceLib; using AuraServiceLib;
using RGB.NET.Core; using RGB.NET.Core;
@ -18,7 +19,7 @@ namespace RGB.NET.Devices.Asus
{ {
#region Properties & Fields #region Properties & Fields
private static AsusDeviceProvider _instance; private static AsusDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="AsusDeviceProvider"/> instance. /// Gets the singleton <see cref="AsusDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -31,26 +32,14 @@ namespace RGB.NET.Devices.Asus
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
/// <summary> public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for asus devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for asus devices.
/// </summary> /// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; } public DeviceUpdateTrigger UpdateTrigger { get; private set; }
private IAuraSdk2 _sdk; private IAuraSdk2? _sdk;
#endregion #endregion
@ -79,7 +68,7 @@ namespace RGB.NET.Devices.Asus
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
// ReSharper disable once SuspiciousTypeConversion.Global // ReSharper disable once SuspiciousTypeConversion.Global
_sdk = (IAuraSdk2)new AuraSdk(); _sdk = (IAuraSdk2)new AuraSdk();
@ -141,7 +130,7 @@ namespace RGB.NET.Devices.Asus
} }
} }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;

View File

@ -24,7 +24,7 @@ namespace RGB.NET.Devices.Asus
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected AsusUpdateQueue UpdateQueue { get; set; } protected AsusUpdateQueue? UpdateQueue { get; set; }
#endregion #endregion
@ -52,7 +52,7 @@ namespace RGB.NET.Devices.Asus
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
@ -66,7 +66,7 @@ namespace RGB.NET.Devices.Asus
protected abstract void InitializeLayout(); protected abstract void InitializeLayout();
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -38,7 +38,7 @@ namespace RGB.NET.Devices.Asus
/// <param name="device">The <see cref="IAuraSyncDevice"/> backing this RGB.NET device.</param> /// <param name="device">The <see cref="IAuraSyncDevice"/> backing this RGB.NET device.</param>
/// <param name="manufacturer">The manufacturer-name of the <see cref="IRGBDevice"/>.</param> /// <param name="manufacturer">The manufacturer-name of the <see cref="IRGBDevice"/>.</param>
/// <param name="model">The model-name of the <see cref="IRGBDevice"/>.</param> /// <param name="model">The model-name of the <see cref="IRGBDevice"/>.</param>
internal AsusRGBDeviceInfo(RGBDeviceType deviceType, IAuraSyncDevice device, string model = null, string manufacturer = "Asus") internal AsusRGBDeviceInfo(RGBDeviceType deviceType, IAuraSyncDevice device, string? model = null, string manufacturer = "Asus")
{ {
this.DeviceType = deviceType; this.DeviceType = deviceType;
this.Device = device; this.Device = device;

View File

@ -15,7 +15,7 @@ namespace RGB.NET.Devices.Asus
/// <summary> /// <summary>
/// The device to be updated. /// The device to be updated.
/// </summary> /// </summary>
protected IAuraSyncDevice Device { get; private set; } protected IAuraSyncDevice? Device { get; private set; }
#endregion #endregion
@ -45,15 +45,16 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc /> /// <inheritdoc />
protected override void Update(Dictionary<object, Color> dataSet) protected override void Update(Dictionary<object, Color> dataSet)
{ {
if (Device == null) return;
try try
{ {
if ((Device.Type == (uint)AsusDeviceType.KEYBOARD_RGB) || (Device.Type == (uint)AsusDeviceType.NB_KB_RGB)) if ((Device.Type == (uint)AsusDeviceType.KEYBOARD_RGB) || (Device.Type == (uint)AsusDeviceType.NB_KB_RGB))
{ {
foreach (KeyValuePair<object, Color> data in dataSet) foreach ((object key, Color value) in dataSet)
{ {
AsusLedId index = (AsusLedId)data.Key; AsusLedId index = (AsusLedId)key;
IAuraSyncKeyboard keyboard = (IAuraSyncKeyboard)Device; if (Device is IAuraSyncKeyboard keyboard)
if (keyboard != null)
{ {
IAuraRgbLight light = index switch IAuraRgbLight light = index switch
{ {
@ -72,7 +73,7 @@ namespace RGB.NET.Devices.Asus
_ => light _ => light
}; };
(_, byte r, byte g, byte b) = data.Value.GetRGBBytes(); (_, byte r, byte g, byte b) = value.GetRGBBytes();
light.Red = r; light.Red = r;
light.Green = g; light.Green = g;
light.Blue = b; light.Blue = b;
@ -81,12 +82,12 @@ namespace RGB.NET.Devices.Asus
} }
else else
{ {
foreach (KeyValuePair<object, Color> data in dataSet) foreach ((object key, Color value) in dataSet)
{ {
int index = (int)data.Key; int index = (int)key;
IAuraRgbLight light = Device.Lights[index]; IAuraRgbLight light = Device.Lights[index];
(_, byte r, byte g, byte b) = data.Value.GetRGBBytes(); (_, byte r, byte g, byte b) = value.GetRGBBytes();
light.Red = r; light.Red = r;
light.Green = g; light.Green = g;
light.Blue = b; light.Blue = b;

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Asus
{ {
internal static class AsusKeyboardLedMapping internal static class AsusKeyboardLedMapping
{ {
public static readonly Dictionary<LedId, AsusLedId> MAPPING = new Dictionary<LedId, AsusLedId> public static readonly Dictionary<LedId, AsusLedId> MAPPING = new()
{ {
{ LedId.Keyboard_Escape, AsusLedId.KEY_ESCAPE }, { LedId.Keyboard_Escape, AsusLedId.KEY_ESCAPE },
{ LedId.Keyboard_F1, AsusLedId.KEY_F1 }, { LedId.Keyboard_F1, AsusLedId.KEY_F1 },
{ LedId.Keyboard_F2, AsusLedId.KEY_F2 }, { LedId.Keyboard_F2, AsusLedId.KEY_F2 },

View File

@ -4,7 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Globalization; using System.Linq;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.CoolerMaster.Helper; using RGB.NET.Devices.CoolerMaster.Helper;
using RGB.NET.Devices.CoolerMaster.Native; using RGB.NET.Devices.CoolerMaster.Native;
@ -19,7 +19,7 @@ namespace RGB.NET.Devices.CoolerMaster
{ {
#region Properties & Fields #region Properties & Fields
private static CoolerMasterDeviceProvider _instance; private static CoolerMasterDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="CoolerMasterDeviceProvider"/> instance. /// Gets the singleton <see cref="CoolerMasterDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -29,13 +29,13 @@ namespace RGB.NET.Devices.CoolerMaster
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/CMSDK.dll" }; public static List<string> PossibleX86NativePaths { get; } = new() { "x86/CMSDK.dll" };
/// <summary> /// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/CMSDK.dll" }; public static List<string> PossibleX64NativePaths { get; } = new() { "x64/CMSDK.dll" };
/// <inheritdoc /> /// <inheritdoc />
/// <summary> /// <summary>
@ -43,30 +43,13 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary> /// </summary>
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _CoolerMasterSDK.LoadedArchitecture;
/// <inheritdoc /> /// <inheritdoc />
/// <summary> public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for cooler master devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for cooler master devices.
/// </summary> /// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; } public DeviceUpdateTrigger UpdateTrigger { get; }
#endregion #endregion
@ -95,7 +78,7 @@ namespace RGB.NET.Devices.CoolerMaster
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
_CoolerMasterSDK.Reload(); _CoolerMasterSDK.Reload();
if (_CoolerMasterSDK.GetSDKVersion() <= 0) return false; if (_CoolerMasterSDK.GetSDKVersion() <= 0) return false;
@ -118,7 +101,7 @@ namespace RGB.NET.Devices.CoolerMaster
{ {
case RGBDeviceType.Keyboard: case RGBDeviceType.Keyboard:
CoolerMasterPhysicalKeyboardLayout physicalLayout = _CoolerMasterSDK.GetDeviceLayout(index); CoolerMasterPhysicalKeyboardLayout physicalLayout = _CoolerMasterSDK.GetDeviceLayout(index);
device = new CoolerMasterKeyboardRGBDevice(new CoolerMasterKeyboardRGBDeviceInfo(index, physicalLayout, GetCulture())); device = new CoolerMasterKeyboardRGBDevice(new CoolerMasterKeyboardRGBDeviceInfo(index, physicalLayout));
break; break;
case RGBDeviceType.Mouse: case RGBDeviceType.Mouse:
@ -142,7 +125,7 @@ namespace RGB.NET.Devices.CoolerMaster
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
} }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;

View File

@ -1,15 +0,0 @@
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace RGB.NET.Devices.CoolerMaster
{
/// <summary>
/// Contains list of available logical layouts for cooler master keyboards.
/// </summary>
public enum CoolerMasterLogicalKeyboardLayout
{
DE
};
}

View File

@ -26,7 +26,7 @@ namespace RGB.NET.Devices.CoolerMaster
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected CoolerMasterUpdateQueue UpdateQueue { get; set; } protected CoolerMasterUpdateQueue? UpdateQueue { get; set; }
#endregion #endregion
@ -55,7 +55,7 @@ namespace RGB.NET.Devices.CoolerMaster
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
@ -68,7 +68,7 @@ namespace RGB.NET.Devices.CoolerMaster
protected abstract void InitializeLayout(); protected abstract void InitializeLayout();
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <inheritdoc cref="IDisposable.Dispose" /> /// <inheritdoc cref="IDisposable.Dispose" />
/// <inheritdoc cref="AbstractRGBDevice{TDeviceInfo}.Dispose" /> /// <inheritdoc cref="AbstractRGBDevice{TDeviceInfo}.Dispose" />

View File

@ -1,5 +1,4 @@
using System; using RGB.NET.Core;
using RGB.NET.Core;
using RGB.NET.Devices.CoolerMaster.Helper; using RGB.NET.Devices.CoolerMaster.Helper;
namespace RGB.NET.Devices.CoolerMaster namespace RGB.NET.Devices.CoolerMaster
@ -45,7 +44,7 @@ namespace RGB.NET.Devices.CoolerMaster
this.DeviceType = deviceType; this.DeviceType = deviceType;
this.DeviceIndex = deviceIndex; this.DeviceIndex = deviceIndex;
Model = deviceIndex.GetDescription(); Model = deviceIndex.GetDescription() ?? "Unknown";
DeviceName = $"{Manufacturer} {Model}"; DeviceName = $"{Manufacturer} {Model}";
} }

View File

@ -14,38 +14,29 @@ namespace RGB.NET.Devices.CoolerMaster.Helper
/// Gets the value of the <see cref="DescriptionAttribute"/>. /// Gets the value of the <see cref="DescriptionAttribute"/>.
/// </summary> /// </summary>
/// <param name="source">The enum value to get the description from.</param> /// <param name="source">The enum value to get the description from.</param>
/// <typeparam name="T">The generic enum-type</typeparam>
/// <returns>The value of the <see cref="DescriptionAttribute"/> or the <see cref="Enum.ToString()" /> result of the source.</returns> /// <returns>The value of the <see cref="DescriptionAttribute"/> or the <see cref="Enum.ToString()" /> result of the source.</returns>
internal static string GetDescription<T>(this T source) internal static string? GetDescription(this Enum source)
where T : struct => source.GetAttribute<DescriptionAttribute>()?.Description ?? source.ToString();
{
return source.GetAttribute<DescriptionAttribute, T>()?.Description ?? source.ToString();
}
/// <summary> /// <summary>
/// Gets the value of the <see cref="DeviceTypeAttribute"/>. /// Gets the value of the <see cref="DeviceTypeAttribute"/>.
/// </summary> /// </summary>
/// <param name="source">The enum value to get the description from.</param> /// <param name="source">The enum value to get the description from.</param>
/// <typeparam name="T">The generic enum-type</typeparam>
/// <returns>The value of the <see cref="DeviceTypeAttribute"/> or the <see cref="Enum.ToString()" /> result of the source.</returns> /// <returns>The value of the <see cref="DeviceTypeAttribute"/> or the <see cref="Enum.ToString()" /> result of the source.</returns>
internal static RGBDeviceType GetDeviceType<T>(this T source) internal static RGBDeviceType GetDeviceType(this Enum source)
where T : struct => source.GetAttribute<DeviceTypeAttribute>()?.DeviceType ?? RGBDeviceType.Unknown;
{
return source.GetAttribute<DeviceTypeAttribute, T>()?.DeviceType ?? RGBDeviceType.Unknown;
}
/// <summary> /// <summary>
/// Gets the attribute of type T. /// Gets the attribute of type T.
/// </summary> /// </summary>
/// <param name="source">The enum value to get the attribute from</param> /// <param name="source">The enum value to get the attribute from</param>
/// <typeparam name="T">The generic attribute type</typeparam> /// <typeparam name="T">The generic attribute type</typeparam>
/// <typeparam name="TEnum">The generic enum-type</typeparam>
/// <returns>The <see cref="Attribute"/>.</returns> /// <returns>The <see cref="Attribute"/>.</returns>
private static T GetAttribute<T, TEnum>(this TEnum source) private static T? GetAttribute<T>(this Enum source)
where T : Attribute where T : Attribute
where TEnum : struct
{ {
FieldInfo fi = source.GetType().GetField(source.ToString()); FieldInfo? fi = source.GetType().GetField(source.ToString());
if (fi == null) return null;
T[] attributes = (T[])fi.GetCustomAttributes(typeof(T), false); T[] attributes = (T[])fi.GetCustomAttributes(typeof(T), false);
return attributes.Length > 0 ? attributes[0] : null; return attributes.Length > 0 ? attributes[0] : null;
} }

View File

@ -14,8 +14,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysL #region MasterKeysL
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_US = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_US = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -131,8 +131,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,20) } { LedId.Keyboard_NumPeriodAndDelete, (5,20) }
}; };
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_EU = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_EU = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -253,8 +253,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysM #region MasterKeysM
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_US = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_US = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -354,8 +354,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,17) } { LedId.Keyboard_NumPeriodAndDelete, (5,17) }
}; };
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_EU = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_EU = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -460,8 +460,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysS #region MasterKeysS
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_US = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_US = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -556,8 +556,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_ArrowRight, (5,17) } { LedId.Keyboard_ArrowRight, (5,17) }
}; };
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_EU = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_EU = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -657,8 +657,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysMK750 #region MasterKeysMK750
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_US = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_US = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -801,8 +801,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_Custom22, (6,17) }, { LedId.Keyboard_Custom22, (6,17) },
}; };
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_EU = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_EU = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -946,8 +946,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_Custom22, (6,17) } { LedId.Keyboard_Custom22, (6,17) }
}; };
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_JP = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_JP = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -1099,8 +1099,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region CKxxx #region CKxxx
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_US = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> CKxxx_US = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -1212,8 +1212,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,20) } { LedId.Keyboard_NumPeriodAndDelete, (5,20) }
}; };
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_EU = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> CKxxx_EU = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -1326,8 +1326,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,20) } { LedId.Keyboard_NumPeriodAndDelete, (5,20) }
}; };
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_JP = new Dictionary<LedId, (int row, int column)> private static readonly Dictionary<LedId, (int row, int column)> CKxxx_JP = new()
{ {
{ LedId.Keyboard_Escape, (0,0) }, { LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) }, { LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) }, { LedId.Keyboard_F2, (0,2) },
@ -1450,7 +1450,7 @@ namespace RGB.NET.Devices.CoolerMaster
/// Contains all the hardware-id mappings for CoolerMaster devices. /// Contains all the hardware-id mappings for CoolerMaster devices.
/// </summary> /// </summary>
public static readonly Dictionary<CoolerMasterDevicesIndexes, Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>> Mapping = public static readonly Dictionary<CoolerMasterDevicesIndexes, Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>> Mapping =
new Dictionary<CoolerMasterDevicesIndexes, Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>> new()
{ {
{ CoolerMasterDevicesIndexes.MasterKeys_L, new Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>> { CoolerMasterDevicesIndexes.MasterKeys_L, new Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>
{ {

View File

@ -27,13 +27,13 @@ namespace RGB.NET.Devices.CoolerMaster
/// <inheritdoc /> /// <inheritdoc />
protected override void InitializeLayout() protected override void InitializeLayout()
{ {
if (!CoolerMasterKeyboardLedMappings.Mapping.TryGetValue(DeviceInfo.DeviceIndex, out Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>> deviceMappings)) if (!CoolerMasterKeyboardLedMappings.Mapping.TryGetValue(DeviceInfo.DeviceIndex, out Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>? deviceMappings))
throw new RGBDeviceException($"Failed to find a CoolerMasterKeyboardLedMapping for device index {DeviceInfo.DeviceIndex}"); throw new RGBDeviceException($"Failed to find a CoolerMasterKeyboardLedMapping for device index {DeviceInfo.DeviceIndex}");
if (!deviceMappings.TryGetValue(DeviceInfo.PhysicalLayout, out Dictionary<LedId, (int row, int column)> mapping)) if (!deviceMappings.TryGetValue(DeviceInfo.PhysicalLayout, out Dictionary<LedId, (int row, int column)>? mapping))
throw new RGBDeviceException($"Failed to find a CoolerMasterKeyboardLedMapping for device index {DeviceInfo.DeviceIndex} with physical layout {DeviceInfo.PhysicalLayout}"); throw new RGBDeviceException($"Failed to find a CoolerMasterKeyboardLedMapping for device index {DeviceInfo.DeviceIndex} with physical layout {DeviceInfo.PhysicalLayout}");
foreach (KeyValuePair<LedId, (int row, int column)> led in mapping) foreach ((LedId ledId, (int row, int column)) in mapping)
AddLed(led.Key, new Point(led.Value.column * 19, led.Value.row * 19), new Size(19, 19)); AddLed(ledId, new Point(column * 19, row * 19), new Size(19, 19));
} }
/// <inheritdoc /> /// <inheritdoc />

View File

@ -1,5 +1,4 @@
using System.Globalization; using RGB.NET.Core;
using RGB.NET.Core;
namespace RGB.NET.Devices.CoolerMaster namespace RGB.NET.Devices.CoolerMaster
{ {
@ -16,11 +15,6 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary> /// </summary>
public CoolerMasterPhysicalKeyboardLayout PhysicalLayout { get; } public CoolerMasterPhysicalKeyboardLayout PhysicalLayout { get; }
/// <summary>
/// Gets the <see cref="CoolerMasterLogicalKeyboardLayout"/> of the <see cref="CoolerMasterKeyboardRGBDevice"/>.
/// </summary>
public CoolerMasterLogicalKeyboardLayout LogicalLayout { get; private set; }
#endregion #endregion
#region Constructors #region Constructors
@ -32,23 +26,10 @@ namespace RGB.NET.Devices.CoolerMaster
/// <param name="deviceIndex">The index of the <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterKeyboardRGBDevice" />.</param> /// <param name="deviceIndex">The index of the <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterKeyboardRGBDevice" />.</param>
/// <param name="physicalKeyboardLayout">The <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterPhysicalKeyboardLayout" /> of the <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterKeyboardRGBDevice" />.</param> /// <param name="physicalKeyboardLayout">The <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterPhysicalKeyboardLayout" /> of the <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterKeyboardRGBDevice" />.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> of the layout this keyboard is using</param> /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> of the layout this keyboard is using</param>
internal CoolerMasterKeyboardRGBDeviceInfo(CoolerMasterDevicesIndexes deviceIndex, CoolerMasterPhysicalKeyboardLayout physicalKeyboardLayout, CultureInfo culture) internal CoolerMasterKeyboardRGBDeviceInfo(CoolerMasterDevicesIndexes deviceIndex, CoolerMasterPhysicalKeyboardLayout physicalKeyboardLayout)
: base(RGBDeviceType.Keyboard, deviceIndex) : base(RGBDeviceType.Keyboard, deviceIndex)
{ {
this.PhysicalLayout = physicalKeyboardLayout; this.PhysicalLayout = physicalKeyboardLayout;
SetLayouts(culture.KeyboardLayoutId);
}
private void SetLayouts(int keyboardLayoutId)
{
switch (keyboardLayoutId)
{
//TODO DarthAffe 02.04.2017: Check all available keyboards and there layout-ids
default:
LogicalLayout = CoolerMasterLogicalKeyboardLayout.DE;
break;
}
} }
#endregion #endregion

View File

@ -15,7 +15,7 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary> /// </summary>
// ReSharper disable once InconsistentNaming // ReSharper disable once InconsistentNaming
public static readonly Dictionary<CoolerMasterDevicesIndexes, Dictionary<LedId, (int row, int column)>> Mapping = public static readonly Dictionary<CoolerMasterDevicesIndexes, Dictionary<LedId, (int row, int column)>> Mapping =
new Dictionary<CoolerMasterDevicesIndexes, Dictionary<LedId, (int row, int column)>> new()
{ {
{ CoolerMasterDevicesIndexes.MasterMouse_L, new Dictionary<LedId, (int row, int column)> { CoolerMasterDevicesIndexes.MasterMouse_L, new Dictionary<LedId, (int row, int column)>
{ {

View File

@ -17,11 +17,6 @@ namespace RGB.NET.Devices.CoolerMaster.Native
private static IntPtr _dllHandle = IntPtr.Zero; private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary> /// <summary>
/// Reloads the SDK. /// Reloads the SDK.
/// </summary> /// </summary>
@ -37,7 +32,7 @@ namespace RGB.NET.Devices.CoolerMaster.Native
// HACK: Load library at runtime to support both, x86 and x64 with one managed dll // HACK: Load library at runtime to support both, x86 and x64 with one managed dll
List<string> possiblePathList = Environment.Is64BitProcess ? CoolerMasterDeviceProvider.PossibleX64NativePaths : CoolerMasterDeviceProvider.PossibleX86NativePaths; List<string> possiblePathList = Environment.Is64BitProcess ? CoolerMasterDeviceProvider.PossibleX64NativePaths : CoolerMasterDeviceProvider.PossibleX86NativePaths;
string dllPath = possiblePathList.FirstOrDefault(File.Exists); string? dllPath = possiblePathList.FirstOrDefault(File.Exists);
if (dllPath == null) throw new RGBDeviceException($"Can't find the CoolerMaster-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'"); if (dllPath == null) throw new RGBDeviceException($"Can't find the CoolerMaster-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'");
_dllHandle = LoadLibrary(dllPath); _dllHandle = LoadLibrary(dllPath);
@ -76,14 +71,14 @@ namespace RGB.NET.Devices.CoolerMaster.Native
#region Pointers #region Pointers
private static GetSDKVersionPointer _getSDKVersionPointer; private static GetSDKVersionPointer? _getSDKVersionPointer;
private static SetControlDevicePointer _setControlDevicenPointer; private static SetControlDevicePointer? _setControlDevicenPointer;
private static IsDevicePlugPointer _isDevicePlugPointer; private static IsDevicePlugPointer? _isDevicePlugPointer;
private static GetDeviceLayoutPointer _getDeviceLayoutPointer; private static GetDeviceLayoutPointer? _getDeviceLayoutPointer;
private static EnableLedControlPointer _enableLedControlPointer; private static EnableLedControlPointer? _enableLedControlPointer;
private static RefreshLedPointer _refreshLedPointer; private static RefreshLedPointer? _refreshLedPointer;
private static SetLedColorPointer _setLedColorPointer; private static SetLedColorPointer? _setLedColorPointer;
private static SetAllLedColorPointer _setAllLedColorPointer; private static SetAllLedColorPointer? _setAllLedColorPointer;
#endregion #endregion
@ -125,49 +120,49 @@ namespace RGB.NET.Devices.CoolerMaster.Native
/// <summary> /// <summary>
/// CM-SDK: Get SDK Dll's Version. /// CM-SDK: Get SDK Dll's Version.
/// </summary> /// </summary>
internal static int GetSDKVersion() => _getSDKVersionPointer(); internal static int GetSDKVersion() => (_getSDKVersionPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke();
/// <summary> /// <summary>
/// CM-SDK: set operating device /// CM-SDK: set operating device
/// </summary> /// </summary>
internal static void SetControlDevice(CoolerMasterDevicesIndexes devicesIndexes) internal static void SetControlDevice(CoolerMasterDevicesIndexes devicesIndexes)
=> _setControlDevicenPointer(devicesIndexes); => (_setControlDevicenPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(devicesIndexes);
/// <summary> /// <summary>
/// CM-SDK: verify if the deviced is plugged in /// CM-SDK: verify if the deviced is plugged in
/// </summary> /// </summary>
internal static bool IsDevicePlugged(CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default) internal static bool IsDevicePlugged(CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _isDevicePlugPointer(devIndex); => (_isDevicePlugPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(devIndex);
/// <summary> /// <summary>
/// CM-SDK: Obtain current device layout /// CM-SDK: Obtain current device layout
/// </summary> /// </summary>
internal static CoolerMasterPhysicalKeyboardLayout GetDeviceLayout(CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default) internal static CoolerMasterPhysicalKeyboardLayout GetDeviceLayout(CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _getDeviceLayoutPointer(devIndex); => (_getDeviceLayoutPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(devIndex);
/// <summary> /// <summary>
/// CM-SDK: set control over devices LED /// CM-SDK: set control over devices LED
/// </summary> /// </summary>
internal static bool EnableLedControl(bool value, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default) internal static bool EnableLedControl(bool value, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _enableLedControlPointer(value, devIndex); => (_enableLedControlPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(value, devIndex);
/// <summary> /// <summary>
/// CM-SDK: Print out the lights setting from Buffer to LED /// CM-SDK: Print out the lights setting from Buffer to LED
/// </summary> /// </summary>
internal static bool RefreshLed(bool autoRefresh, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default) internal static bool RefreshLed(bool autoRefresh, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _refreshLedPointer(autoRefresh, devIndex); => (_refreshLedPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(autoRefresh, devIndex);
/// <summary> /// <summary>
/// CM-SDK: Set single Key LED color /// CM-SDK: Set single Key LED color
/// </summary> /// </summary>
internal static bool SetLedColor(int row, int column, byte r, byte g, byte b, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default) internal static bool SetLedColor(int row, int column, byte r, byte g, byte b, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _setLedColorPointer(row, column, r, g, b, devIndex); => (_setLedColorPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(row, column, r, g, b, devIndex);
/// <summary> /// <summary>
/// CM-SDK: Set Keyboard "every LED" color /// CM-SDK: Set Keyboard "every LED" color
/// </summary> /// </summary>
internal static bool SetAllLedColor(_CoolerMasterColorMatrix colorMatrix, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default) internal static bool SetAllLedColor(_CoolerMasterColorMatrix colorMatrix, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _setAllLedColorPointer(colorMatrix, devIndex); => (_setAllLedColorPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(colorMatrix, devIndex);
// ReSharper restore EventExceptionNotDocumented // ReSharper restore EventExceptionNotDocumented

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.Corsair.Native; using RGB.NET.Devices.Corsair.Native;
@ -18,7 +19,7 @@ namespace RGB.NET.Devices.Corsair
{ {
#region Properties & Fields #region Properties & Fields
private static CorsairDeviceProvider _instance; private static CorsairDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="CorsairDeviceProvider"/> instance. /// Gets the singleton <see cref="CorsairDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -28,13 +29,13 @@ namespace RGB.NET.Devices.Corsair
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/CUESDK.dll", "x86/CUESDK_2015.dll", "x86/CUESDK_2013.dll" }; public static List<string> PossibleX86NativePaths { get; } = new() { "x86/CUESDK.dll", "x86/CUESDK_2015.dll", "x86/CUESDK_2013.dll" };
/// <summary> /// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/CUESDK.dll", "x64/CUESDK_2015.dll", "x64/CUESDK_2013.dll" }; public static List<string> PossibleX64NativePaths { get; } = new() { "x64/CUESDK.dll", "x64/CUESDK_2015.dll", "x64/CUESDK_2013.dll" };
/// <inheritdoc /> /// <inheritdoc />
/// <summary> /// <summary>
@ -42,21 +43,10 @@ namespace RGB.NET.Devices.Corsair
/// </summary> /// </summary>
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _CUESDK.LoadedArchitecture;
/// <summary> /// <summary>
/// Gets the protocol details for the current SDK-connection. /// Gets the protocol details for the current SDK-connection.
/// </summary> /// </summary>
public CorsairProtocolDetails ProtocolDetails { get; private set; } public CorsairProtocolDetails? ProtocolDetails { get; private set; }
/// <inheritdoc />
/// <summary>
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
/// <summary> /// <summary>
/// Gets the last error documented by CUE. /// Gets the last error documented by CUE.
@ -64,7 +54,7 @@ namespace RGB.NET.Devices.Corsair
public CorsairError LastError => _CUESDK.CorsairGetLastError(); public CorsairError LastError => _CUESDK.CorsairGetLastError();
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; } public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for corsair devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for corsair devices.
@ -100,7 +90,7 @@ namespace RGB.NET.Devices.Corsair
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
_CUESDK.Reload(); _CUESDK.Reload();
@ -115,33 +105,23 @@ namespace RGB.NET.Devices.Corsair
+ $"CUE-Version: {ProtocolDetails.ServerVersion} (Protocol {ProtocolDetails.ServerProtocolVersion})\r\n" + $"CUE-Version: {ProtocolDetails.ServerVersion} (Protocol {ProtocolDetails.ServerProtocolVersion})\r\n"
+ $"SDK-Version: {ProtocolDetails.SdkVersion} (Protocol {ProtocolDetails.SdkProtocolVersion})"); + $"SDK-Version: {ProtocolDetails.SdkVersion} (Protocol {ProtocolDetails.SdkProtocolVersion})");
if (exclusiveAccessIfPossible) // DarthAffe 02.02.2021: 127 is iCUE
{ if (!_CUESDK.CorsairSetLayerPriority(128))
if (!_CUESDK.CorsairRequestControl(CorsairAccessMode.ExclusiveLightingControl))
throw new CUEException(LastError);
HasExclusiveAccess = true;
}
else
HasExclusiveAccess = false;
// DarthAffe 07.07.2018: 127 is CUE, we want to directly compete with it as in older versions.
if (!_CUESDK.CorsairSetLayerPriority(127))
throw new CUEException(LastError); throw new CUEException(LastError);
Dictionary<string, int> modelCounter = new Dictionary<string, int>(); Dictionary<string, int> modelCounter = new();
IList<IRGBDevice> devices = new List<IRGBDevice>(); IList<IRGBDevice> devices = new List<IRGBDevice>();
int deviceCount = _CUESDK.CorsairGetDeviceCount(); int deviceCount = _CUESDK.CorsairGetDeviceCount();
for (int i = 0; i < deviceCount; i++) for (int i = 0; i < deviceCount; i++)
{ {
try try
{ {
_CorsairDeviceInfo nativeDeviceInfo = (_CorsairDeviceInfo)Marshal.PtrToStructure(_CUESDK.CorsairGetDeviceInfo(i), typeof(_CorsairDeviceInfo)); _CorsairDeviceInfo nativeDeviceInfo = (_CorsairDeviceInfo)Marshal.PtrToStructure(_CUESDK.CorsairGetDeviceInfo(i), typeof(_CorsairDeviceInfo))!;
CorsairRGBDeviceInfo info = new CorsairRGBDeviceInfo(i, RGBDeviceType.Unknown, nativeDeviceInfo, modelCounter); CorsairRGBDeviceInfo info = new(i, RGBDeviceType.Unknown, nativeDeviceInfo, modelCounter);
if (!info.CapsMask.HasFlag(CorsairDeviceCaps.Lighting)) if (!info.CapsMask.HasFlag(CorsairDeviceCaps.Lighting))
continue; // Everything that doesn't support lighting control is useless continue; // Everything that doesn't support lighting control is useless
CorsairDeviceUpdateQueue deviceUpdateQueue = null; CorsairDeviceUpdateQueue? deviceUpdateQueue = null;
foreach (ICorsairRGBDevice device in GetRGBDevice(info, i, nativeDeviceInfo, modelCounter)) foreach (ICorsairRGBDevice device in GetRGBDevice(info, i, nativeDeviceInfo, modelCounter))
{ {
if ((device == null) || !loadFilter.HasFlag(device.DeviceInfo.DeviceType)) continue; if ((device == null) || !loadFilter.HasFlag(device.DeviceInfo.DeviceType)) continue;
@ -161,7 +141,7 @@ namespace RGB.NET.Devices.Corsair
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
} }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;
@ -207,7 +187,7 @@ namespace RGB.NET.Devices.Corsair
case CorsairDeviceType.Cooler: case CorsairDeviceType.Cooler:
case CorsairDeviceType.CommanderPro: case CorsairDeviceType.CommanderPro:
case CorsairDeviceType.LightningNodePro: case CorsairDeviceType.LightningNodePro:
_CorsairChannelsInfo channelsInfo = nativeDeviceInfo.channels; _CorsairChannelsInfo? channelsInfo = nativeDeviceInfo.channels;
if (channelsInfo != null) if (channelsInfo != null)
{ {
IntPtr channelInfoPtr = channelsInfo.channels; IntPtr channelInfoPtr = channelsInfo.channels;
@ -217,14 +197,14 @@ namespace RGB.NET.Devices.Corsair
CorsairLedId referenceLed = GetChannelReferenceId(info.CorsairDeviceType, channel); CorsairLedId referenceLed = GetChannelReferenceId(info.CorsairDeviceType, channel);
if (referenceLed == CorsairLedId.Invalid) continue; if (referenceLed == CorsairLedId.Invalid) continue;
_CorsairChannelInfo channelInfo = (_CorsairChannelInfo)Marshal.PtrToStructure(channelInfoPtr, typeof(_CorsairChannelInfo)); _CorsairChannelInfo channelInfo = (_CorsairChannelInfo)Marshal.PtrToStructure(channelInfoPtr, typeof(_CorsairChannelInfo))!;
int channelDeviceInfoStructSize = Marshal.SizeOf(typeof(_CorsairChannelDeviceInfo)); int channelDeviceInfoStructSize = Marshal.SizeOf(typeof(_CorsairChannelDeviceInfo));
IntPtr channelDeviceInfoPtr = channelInfo.devices; IntPtr channelDeviceInfoPtr = channelInfo.devices;
for (int device = 0; device < channelInfo.devicesCount; device++) for (int device = 0; device < channelInfo.devicesCount; device++)
{ {
_CorsairChannelDeviceInfo channelDeviceInfo = (_CorsairChannelDeviceInfo)Marshal.PtrToStructure(channelDeviceInfoPtr, typeof(_CorsairChannelDeviceInfo)); _CorsairChannelDeviceInfo channelDeviceInfo = (_CorsairChannelDeviceInfo)Marshal.PtrToStructure(channelDeviceInfoPtr, typeof(_CorsairChannelDeviceInfo))!;
yield return new CorsairCustomRGBDevice(new CorsairCustomRGBDeviceInfo(info, nativeDeviceInfo, channelDeviceInfo, referenceLed, modelCounter)); yield return new CorsairCustomRGBDevice(new CorsairCustomRGBDeviceInfo(info, nativeDeviceInfo, channelDeviceInfo, referenceLed, modelCounter));
referenceLed += channelDeviceInfo.deviceLedCount; referenceLed += channelDeviceInfo.deviceLedCount;
@ -278,8 +258,7 @@ namespace RGB.NET.Devices.Corsair
private void Reset() private void Reset()
{ {
ProtocolDetails = null; ProtocolDetails = null;
HasExclusiveAccess = false; Devices = Enumerable.Empty<IRGBDevice>();
Devices = null;
IsInitialized = false; IsInitialized = false;
} }

View File

@ -14,7 +14,7 @@ namespace RGB.NET.Devices.Corsair
{ {
#region Properties & Fields #region Properties & Fields
private readonly Dictionary<LedId, CorsairLedId> _idMapping = new Dictionary<LedId, CorsairLedId>(); private readonly Dictionary<LedId, CorsairLedId> _idMapping = new();
#endregion #endregion

View File

@ -40,11 +40,11 @@ namespace RGB.NET.Devices.Corsair
{ {
int structSize = Marshal.SizeOf(typeof(_CorsairLedColor)); int structSize = Marshal.SizeOf(typeof(_CorsairLedColor));
IntPtr ptr = Marshal.AllocHGlobal(structSize * dataSet.Count); IntPtr ptr = Marshal.AllocHGlobal(structSize * dataSet.Count);
IntPtr addPtr = new IntPtr(ptr.ToInt64()); IntPtr addPtr = new(ptr.ToInt64());
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
{ {
_CorsairLedColor color = new _CorsairLedColor _CorsairLedColor color = new()
{ {
ledId = (int)data.Key, ledId = (int)data.Key,
r = data.Value.GetR(), r = data.Value.GetR(),
g = data.Value.GetG(), g = data.Value.GetG(),

View File

@ -18,12 +18,12 @@ namespace RGB.NET.Devices.Corsair
/// String containing version of SDK(like "1.0.0.1"). /// String containing version of SDK(like "1.0.0.1").
/// Always contains valid value even if there was no CUE found. /// Always contains valid value even if there was no CUE found.
/// </summary> /// </summary>
public string SdkVersion { get; } public string? SdkVersion { get; }
/// <summary> /// <summary>
/// String containing version of CUE(like "1.0.0.1") or NULL if CUE was not found. /// String containing version of CUE(like "1.0.0.1") or NULL if CUE was not found.
/// </summary> /// </summary>
public string ServerVersion { get; } public string? ServerVersion { get; }
/// <summary> /// <summary>
/// Integer that specifies version of protocol that is implemented by current SDK. /// Integer that specifies version of protocol that is implemented by current SDK.

View File

@ -1,9 +1,6 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.Corsair.Native;
namespace RGB.NET.Devices.Corsair namespace RGB.NET.Devices.Corsair
{ {
@ -27,13 +24,13 @@ namespace RGB.NET.Devices.Corsair
/// Gets a dictionary containing all <see cref="Led"/> of the <see cref="CorsairRGBDevice{TDeviceInfo}"/>. /// Gets a dictionary containing all <see cref="Led"/> of the <see cref="CorsairRGBDevice{TDeviceInfo}"/>.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected Dictionary<CorsairLedId, Led> InternalLedMapping { get; } = new Dictionary<CorsairLedId, Led>(); protected Dictionary<CorsairLedId, Led> InternalLedMapping { get; } = new();
/// <summary> /// <summary>
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected CorsairDeviceUpdateQueue DeviceUpdateQueue { get; set; } protected CorsairDeviceUpdateQueue? DeviceUpdateQueue { get; set; }
#endregion #endregion
@ -45,7 +42,7 @@ namespace RGB.NET.Devices.Corsair
/// <param name="ledId">The <see cref="CorsairLedId"/> of the <see cref="Led"/> to get.</param> /// <param name="ledId">The <see cref="CorsairLedId"/> of the <see cref="Led"/> to get.</param>
/// <returns>The <see cref="Led"/> with the specified <see cref="CorsairLedId"/> or null if no <see cref="Led"/> is found.</returns> /// <returns>The <see cref="Led"/> with the specified <see cref="CorsairLedId"/> or null if no <see cref="Led"/> is found.</returns>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
public Led this[CorsairLedId ledId] => InternalLedMapping.TryGetValue(ledId, out Led led) ? led : null; public Led? this[CorsairLedId ledId] => InternalLedMapping.TryGetValue(ledId, out Led? led) ? led : null;
#endregion #endregion
@ -75,14 +72,13 @@ namespace RGB.NET.Devices.Corsair
foreach (Led led in LedMapping.Values) foreach (Led led in LedMapping.Values)
{ {
CorsairLedId ledId = (CorsairLedId)led.CustomData; if (led.CustomData is CorsairLedId ledId && (ledId != CorsairLedId.Invalid))
if (ledId != CorsairLedId.Invalid)
InternalLedMapping.Add(ledId, led); InternalLedMapping.Add(ledId, led);
} }
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
} }
@ -94,7 +90,7 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate)
=> DeviceUpdateQueue.SetData(ledsToUpdate.Where(x => (x.Color.A > 0) && (x.CustomData is CorsairLedId ledId && (ledId != CorsairLedId.Invalid)))); => DeviceUpdateQueue?.SetData(ledsToUpdate.Where(x => (x.Color.A > 0) && (x.CustomData is CorsairLedId ledId && (ledId != CorsairLedId.Invalid))));
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class HeadsetIdMapping internal static class HeadsetIdMapping
{ {
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{ {
{ LedId.Headset1, CorsairLedId.LeftLogo }, { LedId.Headset1, CorsairLedId.LeftLogo },
{ LedId.Headset2, CorsairLedId.RightLogo }, { LedId.Headset2, CorsairLedId.RightLogo },
}; };

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class HeadsetStandIdMapping internal static class HeadsetStandIdMapping
{ {
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{ {
{ LedId.HeadsetStand1, CorsairLedId.HeadsetStandZone1 }, { LedId.HeadsetStand1, CorsairLedId.HeadsetStandZone1 },
{ LedId.HeadsetStand2, CorsairLedId.HeadsetStandZone2 }, { LedId.HeadsetStand2, CorsairLedId.HeadsetStandZone2 },
{ LedId.HeadsetStand3, CorsairLedId.HeadsetStandZone3 }, { LedId.HeadsetStand3, CorsairLedId.HeadsetStandZone3 },

View File

@ -5,6 +5,9 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class DictionaryExtension internal static class DictionaryExtension
{ {
public static Dictionary<TValue, TKey> SwapKeyValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary) => dictionary.ToDictionary(x => x.Value, x => x.Key); public static Dictionary<TValue, TKey> SwapKeyValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
where TKey : notnull
where TValue : notnull
=> dictionary.ToDictionary(x => x.Value, x => x.Key);
} }
} }

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class KeyboardIdMapping internal static class KeyboardIdMapping
{ {
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{ {
{ LedId.Invalid, CorsairLedId.Invalid }, { LedId.Invalid, CorsairLedId.Invalid },
{ LedId.Logo, CorsairLedId.Logo }, { LedId.Logo, CorsairLedId.Logo },
{ LedId.Keyboard_Escape, CorsairLedId.Escape }, { LedId.Keyboard_Escape, CorsairLedId.Escape },

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class MemoryIdMapping internal static class MemoryIdMapping
{ {
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{ {
{ LedId.Invalid, CorsairLedId.Invalid }, { LedId.Invalid, CorsairLedId.Invalid },
{ LedId.DRAM1, CorsairLedId.DRAM1 }, { LedId.DRAM1, CorsairLedId.DRAM1 },
{ LedId.DRAM2, CorsairLedId.DRAM2 }, { LedId.DRAM2, CorsairLedId.DRAM2 },

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class MouseIdMapping internal static class MouseIdMapping
{ {
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{ {
{ LedId.Mouse1, CorsairLedId.B1 }, { LedId.Mouse1, CorsairLedId.B1 },
{ LedId.Mouse2, CorsairLedId.B2 }, { LedId.Mouse2, CorsairLedId.B2 },
{ LedId.Mouse3, CorsairLedId.B3 }, { LedId.Mouse3, CorsairLedId.B3 },
@ -15,15 +15,15 @@ namespace RGB.NET.Devices.Corsair
{ LedId.Mouse6, CorsairLedId.B6 }, { LedId.Mouse6, CorsairLedId.B6 },
}; };
internal static readonly Dictionary<LedId, CorsairLedId> GLAIVE = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> GLAIVE = new()
{ {
{ LedId.Mouse1, CorsairLedId.B1 }, { LedId.Mouse1, CorsairLedId.B1 },
{ LedId.Mouse2, CorsairLedId.B2 }, { LedId.Mouse2, CorsairLedId.B2 },
{ LedId.Mouse3, CorsairLedId.B5 }, { LedId.Mouse3, CorsairLedId.B5 },
}; };
internal static readonly Dictionary<LedId, CorsairLedId> M65_RGB_ELITE = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> M65_RGB_ELITE = new()
{ {
{ LedId.Mouse1, CorsairLedId.B1 }, { LedId.Mouse1, CorsairLedId.B1 },
{ LedId.Mouse2, CorsairLedId.B3 }, { LedId.Mouse2, CorsairLedId.B3 },
}; };

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{ {
internal static class MousepadIdMapping internal static class MousepadIdMapping
{ {
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId> internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{ {
{ LedId.Mousepad1, CorsairLedId.Zone1 }, { LedId.Mousepad1, CorsairLedId.Zone1 },
{ LedId.Mousepad2, CorsairLedId.Zone2 }, { LedId.Mousepad2, CorsairLedId.Zone2 },
{ LedId.Mousepad3, CorsairLedId.Zone3 }, { LedId.Mousepad3, CorsairLedId.Zone3 },

View File

@ -17,11 +17,6 @@ namespace RGB.NET.Devices.Corsair.Native
private static IntPtr _dllHandle = IntPtr.Zero; private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary> /// <summary>
/// Reloads the SDK. /// Reloads the SDK.
/// </summary> /// </summary>
@ -37,7 +32,7 @@ namespace RGB.NET.Devices.Corsair.Native
// HACK: Load library at runtime to support both, x86 and x64 with one managed dll // HACK: Load library at runtime to support both, x86 and x64 with one managed dll
List<string> possiblePathList = Environment.Is64BitProcess ? CorsairDeviceProvider.PossibleX64NativePaths : CorsairDeviceProvider.PossibleX86NativePaths; List<string> possiblePathList = Environment.Is64BitProcess ? CorsairDeviceProvider.PossibleX64NativePaths : CorsairDeviceProvider.PossibleX86NativePaths;
string dllPath = possiblePathList.FirstOrDefault(File.Exists); string? dllPath = possiblePathList.FirstOrDefault(File.Exists);
if (dllPath == null) throw new RGBDeviceException($"Can't find the CUE-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'"); if (dllPath == null) throw new RGBDeviceException($"Can't find the CUE-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'");
_dllHandle = LoadLibrary(dllPath); _dllHandle = LoadLibrary(dllPath);
@ -80,18 +75,18 @@ namespace RGB.NET.Devices.Corsair.Native
#region Pointers #region Pointers
private static CorsairSetLedsColorsBufferByDeviceIndexPointer _corsairSetLedsColorsBufferByDeviceIndexPointer; private static CorsairSetLedsColorsBufferByDeviceIndexPointer? _corsairSetLedsColorsBufferByDeviceIndexPointer;
private static CorsairSetLedsColorsFlushBufferPointer _corsairSetLedsColorsFlushBufferPointer; private static CorsairSetLedsColorsFlushBufferPointer? _corsairSetLedsColorsFlushBufferPointer;
private static CorsairGetLedsColorsByDeviceIndexPointer _corsairGetLedsColorsByDeviceIndexPointer; private static CorsairGetLedsColorsByDeviceIndexPointer? _corsairGetLedsColorsByDeviceIndexPointer;
private static CorsairSetLayerPriorityPointer _corsairSetLayerPriorityPointer; private static CorsairSetLayerPriorityPointer? _corsairSetLayerPriorityPointer;
private static CorsairGetDeviceCountPointer _corsairGetDeviceCountPointer; private static CorsairGetDeviceCountPointer? _corsairGetDeviceCountPointer;
private static CorsairGetDeviceInfoPointer _corsairGetDeviceInfoPointer; private static CorsairGetDeviceInfoPointer? _corsairGetDeviceInfoPointer;
private static CorsairGetLedIdForKeyNamePointer _corsairGetLedIdForKeyNamePointer; private static CorsairGetLedIdForKeyNamePointer? _corsairGetLedIdForKeyNamePointer;
private static CorsairGetLedPositionsByDeviceIndexPointer _corsairGetLedPositionsByDeviceIndexPointer; private static CorsairGetLedPositionsByDeviceIndexPointer? _corsairGetLedPositionsByDeviceIndexPointer;
private static CorsairRequestControlPointer _corsairRequestControlPointer; private static CorsairRequestControlPointer? _corsairRequestControlPointer;
private static CorsairReleaseControlPointer _corsairReleaseControlPointer; private static CorsairReleaseControlPointer? _corsairReleaseControlPointer;
private static CorsairPerformProtocolHandshakePointer _corsairPerformProtocolHandshakePointer; private static CorsairPerformProtocolHandshakePointer? _corsairPerformProtocolHandshakePointer;
private static CorsairGetLastErrorPointer _corsairGetLastErrorPointer; private static CorsairGetLastErrorPointer? _corsairGetLastErrorPointer;
#endregion #endregion
@ -144,68 +139,70 @@ namespace RGB.NET.Devices.Corsair.Native
/// and follows after one or more calls of CorsairSetLedsColorsBufferByDeviceIndex to set the LEDs buffer. /// and follows after one or more calls of CorsairSetLedsColorsBufferByDeviceIndex to set the LEDs buffer.
/// This function does not take logical layout into account. /// This function does not take logical layout into account.
/// </summary> /// </summary>
internal static bool CorsairSetLedsColorsBufferByDeviceIndex(int deviceIndex, int size, IntPtr ledsColors) => _corsairSetLedsColorsBufferByDeviceIndexPointer(deviceIndex, size, ledsColors); internal static bool CorsairSetLedsColorsBufferByDeviceIndex(int deviceIndex, int size, IntPtr ledsColors)
=> (_corsairSetLedsColorsBufferByDeviceIndexPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(deviceIndex, size, ledsColors);
/// <summary> /// <summary>
/// CUE-SDK: writes to the devices LEDs colors buffer which is previously filled by the CorsairSetLedsColorsBufferByDeviceIndex function. /// CUE-SDK: writes to the devices LEDs colors buffer which is previously filled by the CorsairSetLedsColorsBufferByDeviceIndex function.
/// This function executes synchronously, if you are concerned about delays consider using CorsairSetLedsColorsFlushBufferAsync /// This function executes synchronously, if you are concerned about delays consider using CorsairSetLedsColorsFlushBufferAsync
/// </summary> /// </summary>
internal static bool CorsairSetLedsColorsFlushBuffer() => _corsairSetLedsColorsFlushBufferPointer(); internal static bool CorsairSetLedsColorsFlushBuffer() => (_corsairSetLedsColorsFlushBufferPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke();
/// <summary> /// <summary>
/// CUE-SDK: get current color for the list of requested LEDs. /// CUE-SDK: get current color for the list of requested LEDs.
/// The color should represent the actual state of the hardware LED, which could be a combination of SDK and/or CUE input. /// The color should represent the actual state of the hardware LED, which could be a combination of SDK and/or CUE input.
/// This function works for keyboard, mouse, mousemat, headset, headset stand and DIY-devices. /// This function works for keyboard, mouse, mousemat, headset, headset stand and DIY-devices.
/// </summary> /// </summary>
internal static bool CorsairGetLedsColorsByDeviceIndex(int deviceIndex, int size, IntPtr ledsColors) => _corsairGetLedsColorsByDeviceIndexPointer(deviceIndex, size, ledsColors); internal static bool CorsairGetLedsColorsByDeviceIndex(int deviceIndex, int size, IntPtr ledsColors)
=> (_corsairGetLedsColorsByDeviceIndexPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(deviceIndex, size, ledsColors);
/// <summary> /// <summary>
/// CUE-SDK: set layer priority for this shared client. /// CUE-SDK: set layer priority for this shared client.
/// By default CUE has priority of 127 and all shared clients have priority of 128 if they dont call this function. /// By default CUE has priority of 127 and all shared clients have priority of 128 if they dont call this function.
/// Layers with higher priority value are shown on top of layers with lower priority. /// Layers with higher priority value are shown on top of layers with lower priority.
/// </summary> /// </summary>
internal static bool CorsairSetLayerPriority(int priority) => _corsairSetLayerPriorityPointer(priority); internal static bool CorsairSetLayerPriority(int priority) => (_corsairSetLayerPriorityPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(priority);
/// <summary> /// <summary>
/// CUE-SDK: returns number of connected Corsair devices that support lighting control. /// CUE-SDK: returns number of connected Corsair devices that support lighting control.
/// </summary> /// </summary>
internal static int CorsairGetDeviceCount() => _corsairGetDeviceCountPointer(); internal static int CorsairGetDeviceCount() => (_corsairGetDeviceCountPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke();
/// <summary> /// <summary>
/// CUE-SDK: returns information about device at provided index. /// CUE-SDK: returns information about device at provided index.
/// </summary> /// </summary>
internal static IntPtr CorsairGetDeviceInfo(int deviceIndex) => _corsairGetDeviceInfoPointer(deviceIndex); internal static IntPtr CorsairGetDeviceInfo(int deviceIndex) => (_corsairGetDeviceInfoPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(deviceIndex);
/// <summary> /// <summary>
/// CUE-SDK: provides list of keyboard or mousepad LEDs with their physical positions. /// CUE-SDK: provides list of keyboard or mousepad LEDs with their physical positions.
/// </summary> /// </summary>
internal static IntPtr CorsairGetLedPositionsByDeviceIndex(int deviceIndex) => _corsairGetLedPositionsByDeviceIndexPointer(deviceIndex); internal static IntPtr CorsairGetLedPositionsByDeviceIndex(int deviceIndex) => (_corsairGetLedPositionsByDeviceIndexPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(deviceIndex);
/// <summary> /// <summary>
/// CUE-SDK: retrieves led id for key name taking logical layout into account. /// CUE-SDK: retrieves led id for key name taking logical layout into account.
/// </summary> /// </summary>
internal static CorsairLedId CorsairGetLedIdForKeyName(char keyName) => _corsairGetLedIdForKeyNamePointer(keyName); internal static CorsairLedId CorsairGetLedIdForKeyName(char keyName) => (_corsairGetLedIdForKeyNamePointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(keyName);
/// <summary> /// <summary>
/// CUE-SDK: requestes control using specified access mode. /// CUE-SDK: requestes control using specified access mode.
/// By default client has shared control over lighting so there is no need to call CorsairRequestControl unless client requires exclusive control. /// By default client has shared control over lighting so there is no need to call CorsairRequestControl unless client requires exclusive control.
/// </summary> /// </summary>
internal static bool CorsairRequestControl(CorsairAccessMode accessMode) => _corsairRequestControlPointer(accessMode); internal static bool CorsairRequestControl(CorsairAccessMode accessMode) => (_corsairRequestControlPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(accessMode);
/// <summary> /// <summary>
/// CUE-SDK: releases previously requested control for specified access mode. /// CUE-SDK: releases previously requested control for specified access mode.
/// </summary> /// </summary>
internal static bool CorsairReleaseControl(CorsairAccessMode accessMode) => _corsairReleaseControlPointer(accessMode); internal static bool CorsairReleaseControl(CorsairAccessMode accessMode) => (_corsairReleaseControlPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke(accessMode);
/// <summary> /// <summary>
/// CUE-SDK: checks file and protocol version of CUE to understand which of SDK functions can be used with this version of CUE. /// CUE-SDK: checks file and protocol version of CUE to understand which of SDK functions can be used with this version of CUE.
/// </summary> /// </summary>
internal static _CorsairProtocolDetails CorsairPerformProtocolHandshake() => _corsairPerformProtocolHandshakePointer(); internal static _CorsairProtocolDetails CorsairPerformProtocolHandshake() => (_corsairPerformProtocolHandshakePointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke();
/// <summary> /// <summary>
/// CUE-SDK: returns last error that occured while using any of Corsair* functions. /// CUE-SDK: returns last error that occured while using any of Corsair* functions.
/// </summary> /// </summary>
internal static CorsairError CorsairGetLastError() => _corsairGetLastErrorPointer(); internal static CorsairError CorsairGetLastError() => (_corsairGetLastErrorPointer ?? throw new RGBDeviceException("The Corsair-SDK is not initialized.")).Invoke();
// ReSharper restore EventExceptionNotDocumented // ReSharper restore EventExceptionNotDocumented

View File

@ -47,6 +47,6 @@ namespace RGB.NET.Devices.Corsair.Native
/// <summary> /// <summary>
/// CUE-SDK: structure that describes channels of the DIY-devices /// CUE-SDK: structure that describes channels of the DIY-devices
/// </summary> /// </summary>
internal _CorsairChannelsInfo channels; internal _CorsairChannelsInfo? channels;
} }
} }

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.DMX.E131; using RGB.NET.Devices.DMX.E131;
@ -17,7 +18,7 @@ namespace RGB.NET.Devices.DMX
{ {
#region Properties & Fields #region Properties & Fields
private static DMXDeviceProvider _instance; private static DMXDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="DMXDeviceProvider"/> instance. /// Gets the singleton <see cref="DMXDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -27,20 +28,17 @@ namespace RGB.NET.Devices.DMX
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; } public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// <inheritdoc />
public bool HasExclusiveAccess => false;
/// <summary> /// <summary>
/// Gets a list of all defined device-definitions. /// Gets a list of all defined device-definitions.
/// </summary> /// </summary>
public List<IDMXDeviceDefinition> DeviceDefinitions { get; } = new List<IDMXDeviceDefinition>(); public List<IDMXDeviceDefinition> DeviceDefinitions { get; } = new();
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for dmx devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for dmx devices.
/// </summary> /// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; } public DeviceUpdateTrigger UpdateTrigger { get; }
#endregion #endregion
@ -87,7 +85,7 @@ namespace RGB.NET.Devices.DMX
{ {
if (e131DMXDeviceDefinition.Leds.Count > 0) if (e131DMXDeviceDefinition.Leds.Count > 0)
{ {
E131Device device = new E131Device(new E131DeviceInfo(e131DMXDeviceDefinition), e131DMXDeviceDefinition.Leds); E131Device device = new(new E131DeviceInfo(e131DMXDeviceDefinition), e131DMXDeviceDefinition.Leds);
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }

View File

@ -45,7 +45,7 @@ namespace RGB.NET.Devices.DMX.E131
/// Gets or sets the CID of the device (null will generate a random CID) /// Gets or sets the CID of the device (null will generate a random CID)
/// </summary> /// </summary>
// ReSharper disable once InconsistentNaming // ReSharper disable once InconsistentNaming
public byte[] CID { get; set; } public byte[]? CID { get; set; }
/// <summary> /// <summary>
/// Gets or sets the universe the device belongs to. /// Gets or sets the universe the device belongs to.
@ -55,7 +55,7 @@ namespace RGB.NET.Devices.DMX.E131
/// <summary> /// <summary>
/// Gets or sets the led-mappings used to create the device. /// Gets or sets the led-mappings used to create the device.
/// </summary> /// </summary>
public Dictionary<LedId, List<(int channel, Func<Color, byte> getValueFunc)>> Leds { get; } = new Dictionary<LedId, List<(int channel, Func<Color, byte> getValueFunc)>>(); public Dictionary<LedId, List<(int channel, Func<Color, byte> getValueFunc)>> Leds { get; } = new();
#endregion #endregion

View File

@ -17,7 +17,7 @@ namespace RGB.NET.Devices.DMX.E131
private readonly Dictionary<LedId, List<(int channel, Func<Color, byte> getValueFunc)>> _ledMappings; private readonly Dictionary<LedId, List<(int channel, Func<Color, byte> getValueFunc)>> _ledMappings;
private E131UpdateQueue _updateQueue; private E131UpdateQueue? _updateQueue;
#endregion #endregion
@ -42,7 +42,7 @@ namespace RGB.NET.Devices.DMX.E131
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
@ -56,7 +56,7 @@ namespace RGB.NET.Devices.DMX.E131
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => _updateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => _updateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -66,15 +66,17 @@ namespace RGB.NET.Devices.DMX.E131
this.Model = deviceDefinition.Model; this.Model = deviceDefinition.Model;
this.Hostname = deviceDefinition.Hostname; this.Hostname = deviceDefinition.Hostname;
this.Port = deviceDefinition.Port; this.Port = deviceDefinition.Port;
this.CID = deviceDefinition.CID;
this.Universe = deviceDefinition.Universe; this.Universe = deviceDefinition.Universe;
byte[]? cid = deviceDefinition.CID;
if ((CID == null) || (CID.Length != CID_LENGTH)) if ((CID == null) || (CID.Length != CID_LENGTH))
{ {
CID = new byte[CID_LENGTH]; CID = new byte[CID_LENGTH];
new Random().NextBytes(CID); new Random().NextBytes(CID);
} }
CID = cid!;
DeviceName = $"{Manufacturer} {Model}"; DeviceName = $"{Manufacturer} {Model}";
} }

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Layout; using RGB.NET.Layout;
@ -17,7 +18,7 @@ namespace RGB.NET.Devices.Debug
{ {
#region Properties & Fields #region Properties & Fields
private static DebugDeviceProvider _instance; private static DebugDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="DebugDeviceProvider"/> instance. /// Gets the singleton <see cref="DebugDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -27,10 +28,9 @@ namespace RGB.NET.Devices.Debug
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; } public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
private List<(IDeviceLayout layout, string imageLayout, Action<IEnumerable<Led>>? updateLedsAction)> _fakeDeviceDefinitions private List<(IDeviceLayout layout, string imageLayout, Action<IEnumerable<Led>>? updateLedsAction)> _fakeDeviceDefinitions = new();
= new List<(IDeviceLayout layout, string imageLayout, Action<IEnumerable<Led>>? updateLedsAction)>();
#endregion #endregion
@ -70,10 +70,10 @@ namespace RGB.NET.Devices.Debug
IsInitialized = false; IsInitialized = false;
try try
{ {
List<IRGBDevice> devices = new List<IRGBDevice>(); List<IRGBDevice> devices = new();
foreach ((IDeviceLayout layout, string imageLayout, Action<IEnumerable<Led>>? updateLedsAction) in _fakeDeviceDefinitions) foreach ((IDeviceLayout layout, string imageLayout, Action<IEnumerable<Led>>? updateLedsAction) in _fakeDeviceDefinitions)
{ {
DebugRGBDevice device = new DebugRGBDevice(layout, updateLedsAction); DebugRGBDevice device = new(layout, updateLedsAction);
devices.Add(device); devices.Add(device);
} }

View File

@ -22,7 +22,7 @@ namespace RGB.NET.Devices.Logitech
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected UpdateQueue UpdateQueue { get; set; } protected UpdateQueue? UpdateQueue { get; set; }
#endregion #endregion

View File

@ -34,16 +34,6 @@ namespace RGB.NET.Devices.Logitech
/// </summary> /// </summary>
public int Zones { get; } public int Zones { get; }
/// <summary>
/// Gets the layout used to decide which images to load.
/// </summary>
internal string ImageLayout { get; }
/// <summary>
/// Gets the path/name of the layout-file.
/// </summary>
internal string LayoutPath { get; }
#endregion #endregion
#region Constructors #region Constructors
@ -57,15 +47,12 @@ namespace RGB.NET.Devices.Logitech
/// <param name="zones">The amount of zones the device is able to control.</param> /// <param name="zones">The amount of zones the device is able to control.</param>
/// <param name="imageLayout">The layout used to decide which images to load.</param> /// <param name="imageLayout">The layout used to decide which images to load.</param>
/// <param name="layoutPath">The path/name of the layout-file.</param> /// <param name="layoutPath">The path/name of the layout-file.</param>
internal LogitechRGBDeviceInfo(RGBDeviceType deviceType, string model, LogitechDeviceCaps deviceCaps, internal LogitechRGBDeviceInfo(RGBDeviceType deviceType, string model, LogitechDeviceCaps deviceCaps, int zones)
int zones, string imageLayout, string layoutPath)
{ {
this.DeviceType = deviceType; this.DeviceType = deviceType;
this.Model = model; this.Model = model;
this.DeviceCaps = deviceCaps; this.DeviceCaps = deviceCaps;
this.Zones = zones; this.Zones = zones;
this.ImageLayout = imageLayout;
this.LayoutPath = layoutPath;
DeviceName = $"{Manufacturer} {Model}"; DeviceName = $"{Manufacturer} {Model}";
} }

View File

@ -5,83 +5,81 @@ using RGB.NET.Core;
namespace RGB.NET.Devices.Logitech.HID namespace RGB.NET.Devices.Logitech.HID
{ {
//TODO DarthAffe 04.02.2017: Rewrite this once the SDK supports per-device lighting to get all the devices connected.
internal static class DeviceChecker internal static class DeviceChecker
{ {
#region Constants #region Constants
private const int VENDOR_ID = 0x046D; private const int VENDOR_ID = 0x046D;
//TODO DarthAffe 14.11.2017: Add devices private static readonly List<(string model, RGBDeviceType deviceType, int id, int zones)> PER_KEY_DEVICES
private static readonly List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> PER_KEY_DEVICES = new()
= new List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> {
{ ("G910", RGBDeviceType.Keyboard, 0xC32B, 0),
("G910", RGBDeviceType.Keyboard, 0xC32B, 0, "DE", @"Keyboards\G910\UK"), //TODO DarthAffe 15.11.2017: Somehow detect the current layout ("G910v2", RGBDeviceType.Keyboard, 0xC335, 0),
("G910v2", RGBDeviceType.Keyboard, 0xC335, 0, "DE", @"Keyboards\G910\UK"), ("G915", RGBDeviceType.Keyboard, 0xC541, 0),
("G915", RGBDeviceType.Keyboard, 0xC541, 0, "DE", @"Keyboards\G915\UK"), ("G810", RGBDeviceType.Keyboard, 0xC337, 0),
("G810", RGBDeviceType.Keyboard, 0xC337, 0, "DE", @"Keyboards\G810\UK"), ("G810", RGBDeviceType.Keyboard, 0xC331, 0),
("G810", RGBDeviceType.Keyboard, 0xC331, 0, "DE", @"Keyboards\G810\UK"), ("G610", RGBDeviceType.Keyboard, 0xC333, 0),
("G610", RGBDeviceType.Keyboard, 0xC333, 0, "DE", @"Keyboards\G610\UK"), ("G512", RGBDeviceType.Keyboard, 0xC33C, 0),
("G512", RGBDeviceType.Keyboard, 0xC33C, 0, "DE", @"Keyboards\G512\UK"), ("G512 SE", RGBDeviceType.Keyboard, 0xC342, 0),
("G512 SE", RGBDeviceType.Keyboard, 0xC342, 0, "DE", @"Keyboards\G512SE\UK"), ("G410", RGBDeviceType.Keyboard, 0xC330, 0),
("G410", RGBDeviceType.Keyboard, 0xC330, 0, "DE", @"Keyboards\G410\UK"), ("G213", RGBDeviceType.Keyboard, 0xC336, 0),
("G213", RGBDeviceType.Keyboard, 0xC336, 0, "DE", @"Keyboards\G213\UK"), ("Pro", RGBDeviceType.Keyboard, 0xC339, 0),
("Pro", RGBDeviceType.Keyboard, 0xC339, 0, "DE", @"Keyboards\Pro\UK"), ("G915 TKL", RGBDeviceType.Keyboard, 0xC343, 0),
("G915 TKL", RGBDeviceType.Keyboard, 0xC343, 0, "DE", @"Keyboards\G915TKL\UK"), ("Lightspeed Keyboard Dongle", RGBDeviceType.Keyboard, 0xC545, 0),
("Lightspeed Keyboard Dongle", RGBDeviceType.Keyboard, 0xC545, 0, "DE", @"Keyboards\G915\UK"), };
};
private static readonly List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> PER_DEVICE_DEVICES private static readonly List<(string model, RGBDeviceType deviceType, int id, int zones)> PER_DEVICE_DEVICES
= new List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> = new()
{ {
("G19", RGBDeviceType.Keyboard, 0xC228, 0, "DE", @"Keyboards\G19\UK"), ("G19", RGBDeviceType.Keyboard, 0xC228, 0),
("G19s", RGBDeviceType.Keyboard, 0xC229, 0, "DE", @"Keyboards\G19s\UK"), ("G19s", RGBDeviceType.Keyboard, 0xC229, 0),
("G600", RGBDeviceType.Mouse, 0xC24A, 0, "default", @"Mice\G600"), ("G600", RGBDeviceType.Mouse, 0xC24A, 0),
("G300s", RGBDeviceType.Mouse, 0xC246, 0, "default", @"Mice\G300s"), ("G300s", RGBDeviceType.Mouse, 0xC246, 0),
("G510", RGBDeviceType.Keyboard, 0xC22D, 0, "DE", @"Keyboards\G510\UK"), ("G510", RGBDeviceType.Keyboard, 0xC22D, 0),
("G510s", RGBDeviceType.Keyboard, 0xC22E, 0, "DE", @"Keyboards\G510s\UK"), ("G510s", RGBDeviceType.Keyboard, 0xC22E, 0),
("G13", RGBDeviceType.Keypad, 0xC21C, 0, "DE", @"Keypads\G13\UK"), ("G13", RGBDeviceType.Keypad, 0xC21C, 0),
("G110", RGBDeviceType.Keyboard, 0xC22B, 0, "DE", @"Keyboards\G110\UK"), ("G110", RGBDeviceType.Keyboard, 0xC22B, 0),
("G710+", RGBDeviceType.Keyboard, 0xC24D, 0, "DE", @"Keyboards\G710+\UK"), ("G710+", RGBDeviceType.Keyboard, 0xC24D, 0),
("G105", RGBDeviceType.Keyboard, 0xC248, 0, "DE", @"Keyboards\G105\UK"), ("G105", RGBDeviceType.Keyboard, 0xC248, 0),
("G15", RGBDeviceType.Keyboard, 0xC222, 0, "DE", @"Keyboards\G15\UK"), ("G15", RGBDeviceType.Keyboard, 0xC222, 0),
("G11", RGBDeviceType.Keyboard, 0xC225, 0, "DE", @"Keyboards\G11\UK"), ("G11", RGBDeviceType.Keyboard, 0xC225, 0),
}; };
private static readonly List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> ZONE_DEVICES private static readonly List<(string model, RGBDeviceType deviceType, int id, int zones)> ZONE_DEVICES
= new List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> = new()
{ {
("G213", RGBDeviceType.Keyboard, 0xC336, 5, "default", @"Keyboards\G213"), ("G213", RGBDeviceType.Keyboard, 0xC336, 5),
("G903", RGBDeviceType.Mouse, 0xC086, 2, "default", @"Mice\G903"), ("G903", RGBDeviceType.Mouse, 0xC086, 2),
("Lightspeed Mouse Dongle", RGBDeviceType.Mouse, 0xC539, 2, "default", @"Mice\G900"), ("Lightspeed Mouse Dongle", RGBDeviceType.Mouse, 0xC539, 2),
("G703", RGBDeviceType.Mouse, 0xC087, 2, "default", @"Mice\G703"), ("G703", RGBDeviceType.Mouse, 0xC087, 2),
("G502 HERO", RGBDeviceType.Mouse, 0xC08B, 2, "default", @"Mice\G502"), ("G502 HERO", RGBDeviceType.Mouse, 0xC08B, 2),
("G502 Lightspeed", RGBDeviceType.Mouse, 0xC08D, 2, "default", @"Mice\G502"), ("G502 Lightspeed", RGBDeviceType.Mouse, 0xC08D, 2),
("G502", RGBDeviceType.Mouse, 0xC332, 2, "default", @"Mice\G502"), ("G502", RGBDeviceType.Mouse, 0xC332, 2),
("G403", RGBDeviceType.Mouse, 0xC083, 2, "default", @"Mice\G403"), ("G403", RGBDeviceType.Mouse, 0xC083, 2),
("G303", RGBDeviceType.Mouse, 0xC080, 2, "default", @"Mice\G303"), ("G303", RGBDeviceType.Mouse, 0xC080, 2),
("G203", RGBDeviceType.Mouse, 0xC084, 1, "default", @"Mice\G203"), ("G203", RGBDeviceType.Mouse, 0xC084, 1),
("G Pro", RGBDeviceType.Mouse, 0xC085, 1, "default", @"Mice\GPro"), ("G Pro", RGBDeviceType.Mouse, 0xC085, 1),
("G Pro Wireless", RGBDeviceType.Mouse, 0xC088, 2, "default", @"Mice\GProWireless"), ("G Pro Wireless", RGBDeviceType.Mouse, 0xC088, 2),
("G Pro Hero", RGBDeviceType.Mouse, 0xC08C, 1, "default", @"Mice\GProHero"), ("G Pro Hero", RGBDeviceType.Mouse, 0xC08C, 1),
("G633", RGBDeviceType.Headset, 0x0A5C, 2, "default", @"Headsets\G633"), ("G633", RGBDeviceType.Headset, 0x0A5C, 2),
("G933", RGBDeviceType.Headset, 0x0A5B, 2, "default", @"Headsets\G933"), ("G933", RGBDeviceType.Headset, 0x0A5B, 2),
("G935", RGBDeviceType.Headset, 0x0A87, 2, "default", @"Headsets\G935"), ("G935", RGBDeviceType.Headset, 0x0A87, 2),
("G560", RGBDeviceType.Speaker, 0x0A78, 4, "default", @"Speakers\G560"), ("G560", RGBDeviceType.Speaker, 0x0A78, 4),
}; };
#endregion #endregion
#region Properties & Fields #region Properties & Fields
public static bool IsPerKeyDeviceConnected { get; private set; } public static bool IsPerKeyDeviceConnected { get; private set; }
public static (string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath) PerKeyDeviceData { get; private set; } public static (string model, RGBDeviceType deviceType, int id, int zones) PerKeyDeviceData { get; private set; }
public static bool IsPerDeviceDeviceConnected { get; private set; } public static bool IsPerDeviceDeviceConnected { get; private set; }
public static (string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath) PerDeviceDeviceData { get; private set; } public static (string model, RGBDeviceType deviceType, int id, int zones) PerDeviceDeviceData { get; private set; }
public static bool IsZoneDeviceConnected { get; private set; } public static bool IsZoneDeviceConnected { get; private set; }
public static IEnumerable<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> ZoneDeviceData { get; private set; } public static IEnumerable<(string model, RGBDeviceType deviceType, int id, int zones)> ZoneDeviceData { get; private set; } = Enumerable.Empty<(string model, RGBDeviceType deviceType, int id, int zones)>();
#endregion #endregion
@ -91,7 +89,7 @@ namespace RGB.NET.Devices.Logitech.HID
{ {
List<int> ids = DeviceList.Local.GetHidDevices(VENDOR_ID).Select(x => x.ProductID).Distinct().ToList(); List<int> ids = DeviceList.Local.GetHidDevices(VENDOR_ID).Select(x => x.ProductID).Distinct().ToList();
foreach ((string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath) deviceData in PER_KEY_DEVICES) foreach ((string model, RGBDeviceType deviceType, int id, int zones) deviceData in PER_KEY_DEVICES)
if (ids.Contains(deviceData.id)) if (ids.Contains(deviceData.id))
{ {
IsPerKeyDeviceConnected = true; IsPerKeyDeviceConnected = true;
@ -99,7 +97,7 @@ namespace RGB.NET.Devices.Logitech.HID
break; break;
} }
foreach ((string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath) deviceData in PER_DEVICE_DEVICES) foreach ((string model, RGBDeviceType deviceType, int id, int zones) deviceData in PER_DEVICE_DEVICES)
if (ids.Contains(deviceData.id)) if (ids.Contains(deviceData.id))
{ {
IsPerDeviceDeviceConnected = true; IsPerDeviceDeviceConnected = true;
@ -107,21 +105,19 @@ namespace RGB.NET.Devices.Logitech.HID
break; break;
} }
Dictionary<RGBDeviceType, List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)>> connectedZoneDevices Dictionary<RGBDeviceType, List<(string model, RGBDeviceType deviceType, int id, int zones)>> connectedZoneDevices = new();
= new Dictionary<RGBDeviceType, List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)>>(); foreach ((string model, RGBDeviceType deviceType, int id, int zones) deviceData in ZONE_DEVICES)
foreach ((string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath) deviceData in ZONE_DEVICES)
{ {
if (ids.Contains(deviceData.id)) if (ids.Contains(deviceData.id))
{ {
IsZoneDeviceConnected = true; IsZoneDeviceConnected = true;
if (!connectedZoneDevices.TryGetValue(deviceData.deviceType, out List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> deviceList)) if (!connectedZoneDevices.TryGetValue(deviceData.deviceType, out List<(string model, RGBDeviceType deviceType, int id, int zones)>? deviceList))
connectedZoneDevices.Add(deviceData.deviceType, deviceList = new List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)>()); connectedZoneDevices.Add(deviceData.deviceType, deviceList = new List<(string model, RGBDeviceType deviceType, int id, int zones)>());
deviceList.Add(deviceData); deviceList.Add(deviceData);
} }
} }
List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)> zoneDeviceData List<(string model, RGBDeviceType deviceType, int id, int zones)> zoneDeviceData = new();
= new List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)>(); foreach (KeyValuePair<RGBDeviceType, List<(string model, RGBDeviceType deviceType, int id, int zones)>> connectedZoneDevice in connectedZoneDevices)
foreach (KeyValuePair<RGBDeviceType, List<(string model, RGBDeviceType deviceType, int id, int zones, string imageLayout, string layoutPath)>> connectedZoneDevice in connectedZoneDevices)
{ {
int maxZones = connectedZoneDevice.Value.Max(x => x.zones); int maxZones = connectedZoneDevice.Value.Max(x => x.zones);
zoneDeviceData.Add(connectedZoneDevice.Value.First(x => x.zones == maxZones)); zoneDeviceData.Add(connectedZoneDevice.Value.First(x => x.zones == maxZones));

View File

@ -4,7 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Globalization; using System.Linq;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.Logitech.HID; using RGB.NET.Devices.Logitech.HID;
using RGB.NET.Devices.Logitech.Native; using RGB.NET.Devices.Logitech.Native;
@ -19,7 +19,7 @@ namespace RGB.NET.Devices.Logitech
{ {
#region Properties & Fields #region Properties & Fields
private static LogitechDeviceProvider _instance; private static LogitechDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="LogitechDeviceProvider"/> instance. /// Gets the singleton <see cref="LogitechDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -29,40 +29,27 @@ namespace RGB.NET.Devices.Logitech
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/LogitechLedEnginesWrapper.dll" }; public static List<string> PossibleX86NativePaths { get; } = new() { "x86/LogitechLedEnginesWrapper.dll" };
/// <summary> /// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/LogitechLedEnginesWrapper.dll" }; public static List<string> PossibleX64NativePaths { get; } = new() { "x64/LogitechLedEnginesWrapper.dll" };
/// <inheritdoc /> /// <inheritdoc />
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _LogitechGSDK.LoadedArchitecture;
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; } public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// <inheritdoc />
public bool HasExclusiveAccess => false; // Exclusive access isn't possible for logitech devices.
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for logitech devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for logitech devices.
/// </summary> /// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; } public DeviceUpdateTrigger UpdateTrigger { get; }
// ReSharper disable once CollectionNeverQueried.Local - for now this is just to make sure they're never collected // ReSharper disable once CollectionNeverQueried.Local - for now this is just to make sure they're never collected
private readonly Dictionary<RGBDeviceType, LogitechZoneUpdateQueue> _zoneUpdateQueues = new Dictionary<RGBDeviceType, LogitechZoneUpdateQueue>(); private readonly Dictionary<RGBDeviceType, LogitechZoneUpdateQueue> _zoneUpdateQueues = new();
private LogitechPerDeviceUpdateQueue _perDeviceUpdateQueue; private LogitechPerDeviceUpdateQueue _perDeviceUpdateQueue;
private LogitechPerKeyUpdateQueue _perKeyUpdateQueue; private LogitechPerKeyUpdateQueue _perKeyUpdateQueue;
@ -102,7 +89,7 @@ namespace RGB.NET.Devices.Logitech
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
_LogitechGSDK.Reload(); _LogitechGSDK.Reload();
if (!_LogitechGSDK.LogiLedInit()) return false; if (!_LogitechGSDK.LogiLedInit()) return false;
@ -116,10 +103,10 @@ namespace RGB.NET.Devices.Logitech
{ {
if (DeviceChecker.IsPerKeyDeviceConnected) if (DeviceChecker.IsPerKeyDeviceConnected)
{ {
(string model, RGBDeviceType deviceType, int _, int _, string imageLayout, string layoutPath) = DeviceChecker.PerKeyDeviceData; (string model, RGBDeviceType deviceType, int _, int _) = DeviceChecker.PerKeyDeviceData;
if (loadFilter.HasFlag(deviceType)) //TODO DarthAffe 07.12.2017: Check if it's worth to try another device if the one returned doesn't match the filter if (loadFilter.HasFlag(deviceType)) //TODO DarthAffe 07.12.2017: Check if it's worth to try another device if the one returned doesn't match the filter
{ {
ILogitechRGBDevice device = new LogitechPerKeyRGBDevice(new LogitechRGBDeviceInfo(deviceType, model, LogitechDeviceCaps.PerKeyRGB, 0, imageLayout, layoutPath)); ILogitechRGBDevice device = new LogitechPerKeyRGBDevice(new LogitechRGBDeviceInfo(deviceType, model, LogitechDeviceCaps.PerKeyRGB, 0));
device.Initialize(_perKeyUpdateQueue); device.Initialize(_perKeyUpdateQueue);
devices.Add(device); devices.Add(device);
} }
@ -131,10 +118,10 @@ namespace RGB.NET.Devices.Logitech
{ {
if (DeviceChecker.IsPerDeviceDeviceConnected) if (DeviceChecker.IsPerDeviceDeviceConnected)
{ {
(string model, RGBDeviceType deviceType, int _, int _, string imageLayout, string layoutPath) = DeviceChecker.PerDeviceDeviceData; (string model, RGBDeviceType deviceType, int _, int _) = DeviceChecker.PerDeviceDeviceData;
if (loadFilter.HasFlag(deviceType)) //TODO DarthAffe 07.12.2017: Check if it's worth to try another device if the one returned doesn't match the filter if (loadFilter.HasFlag(deviceType)) //TODO DarthAffe 07.12.2017: Check if it's worth to try another device if the one returned doesn't match the filter
{ {
ILogitechRGBDevice device = new LogitechPerDeviceRGBDevice(new LogitechRGBDeviceInfo(deviceType, model, LogitechDeviceCaps.DeviceRGB, 0, imageLayout, layoutPath)); ILogitechRGBDevice device = new LogitechPerDeviceRGBDevice(new LogitechRGBDeviceInfo(deviceType, model, LogitechDeviceCaps.DeviceRGB, 0));
device.Initialize(_perDeviceUpdateQueue); device.Initialize(_perDeviceUpdateQueue);
devices.Add(device); devices.Add(device);
} }
@ -146,13 +133,13 @@ namespace RGB.NET.Devices.Logitech
{ {
if (DeviceChecker.IsZoneDeviceConnected) if (DeviceChecker.IsZoneDeviceConnected)
{ {
foreach ((string model, RGBDeviceType deviceType, int _, int zones, string imageLayout, string layoutPath) in DeviceChecker.ZoneDeviceData) foreach ((string model, RGBDeviceType deviceType, int _, int zones) in DeviceChecker.ZoneDeviceData)
try try
{ {
if (loadFilter.HasFlag(deviceType)) if (loadFilter.HasFlag(deviceType))
{ {
LogitechZoneUpdateQueue updateQueue = new LogitechZoneUpdateQueue(UpdateTrigger, deviceType); LogitechZoneUpdateQueue updateQueue = new(UpdateTrigger, deviceType);
ILogitechRGBDevice device = new LogitechZoneRGBDevice(new LogitechRGBDeviceInfo(deviceType, model, LogitechDeviceCaps.DeviceRGB, zones, imageLayout, layoutPath)); ILogitechRGBDevice device = new LogitechZoneRGBDevice(new LogitechRGBDeviceInfo(deviceType, model, LogitechDeviceCaps.DeviceRGB, zones));
device.Initialize(updateQueue); device.Initialize(updateQueue);
devices.Add(device); devices.Add(device);
_zoneUpdateQueues.Add(deviceType, updateQueue); _zoneUpdateQueues.Add(deviceType, updateQueue);
@ -163,7 +150,7 @@ namespace RGB.NET.Devices.Logitech
} }
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;

View File

@ -18,11 +18,6 @@ namespace RGB.NET.Devices.Logitech.Native
private static IntPtr _dllHandle = IntPtr.Zero; private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary> /// <summary>
/// Reloads the SDK. /// Reloads the SDK.
/// </summary> /// </summary>
@ -38,7 +33,7 @@ namespace RGB.NET.Devices.Logitech.Native
// HACK: Load library at runtime to support both, x86 and x64 with one managed dll // HACK: Load library at runtime to support both, x86 and x64 with one managed dll
List<string> possiblePathList = Environment.Is64BitProcess ? LogitechDeviceProvider.PossibleX64NativePaths : LogitechDeviceProvider.PossibleX86NativePaths; List<string> possiblePathList = Environment.Is64BitProcess ? LogitechDeviceProvider.PossibleX64NativePaths : LogitechDeviceProvider.PossibleX86NativePaths;
string dllPath = possiblePathList.FirstOrDefault(File.Exists); string? dllPath = possiblePathList.FirstOrDefault(File.Exists);
if (dllPath == null) throw new RGBDeviceException($"Can't find the Logitech-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'"); if (dllPath == null) throw new RGBDeviceException($"Can't find the Logitech-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'");
_dllHandle = LoadLibrary(dllPath); _dllHandle = LoadLibrary(dllPath);
@ -81,16 +76,16 @@ namespace RGB.NET.Devices.Logitech.Native
#region Pointers #region Pointers
private static LogiLedInitPointer _logiLedInitPointer; private static LogiLedInitPointer? _logiLedInitPointer;
private static LogiLedShutdownPointer _logiLedShutdownPointer; private static LogiLedShutdownPointer? _logiLedShutdownPointer;
private static LogiLedSetTargetDevicePointer _logiLedSetTargetDevicePointer; private static LogiLedSetTargetDevicePointer? _logiLedSetTargetDevicePointer;
private static LogiLedGetSdkVersionPointer _logiLedGetSdkVersionPointer; private static LogiLedGetSdkVersionPointer? _logiLedGetSdkVersionPointer;
private static LogiLedSaveCurrentLightingPointer _lgiLedSaveCurrentLightingPointer; private static LogiLedSaveCurrentLightingPointer? _lgiLedSaveCurrentLightingPointer;
private static LogiLedRestoreLightingPointer _logiLedRestoreLightingPointer; private static LogiLedRestoreLightingPointer? _logiLedRestoreLightingPointer;
private static LogiLedSetLightingPointer _logiLedSetLightingPointer; private static LogiLedSetLightingPointer? _logiLedSetLightingPointer;
private static LogiLedSetLightingForKeyWithKeyNamePointer _logiLedSetLightingForKeyWithKeyNamePointer; private static LogiLedSetLightingForKeyWithKeyNamePointer? _logiLedSetLightingForKeyWithKeyNamePointer;
private static LogiLedSetLightingFromBitmapPointer _logiLedSetLightingFromBitmapPointer; private static LogiLedSetLightingFromBitmapPointer? _logiLedSetLightingFromBitmapPointer;
private static LogiLedSetLightingForTargetZonePointer _logiLedSetLightingForTargetZonePointer; private static LogiLedSetLightingForTargetZonePointer? _logiLedSetLightingForTargetZonePointer;
#endregion #endregion
@ -130,11 +125,11 @@ namespace RGB.NET.Devices.Logitech.Native
// ReSharper disable EventExceptionNotDocumented // ReSharper disable EventExceptionNotDocumented
internal static bool LogiLedInit() => _logiLedInitPointer(); internal static bool LogiLedInit() => (_logiLedInitPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke();
internal static void LogiLedShutdown() => _logiLedShutdownPointer(); internal static void LogiLedShutdown() => (_logiLedShutdownPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke();
internal static bool LogiLedSetTargetDevice(LogitechDeviceCaps targetDevice) => _logiLedSetTargetDevicePointer((int)targetDevice); internal static bool LogiLedSetTargetDevice(LogitechDeviceCaps targetDevice) => (_logiLedSetTargetDevicePointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke((int)targetDevice);
internal static string LogiLedGetSdkVersion() internal static string LogiLedGetSdkVersion()
{ {
@ -146,21 +141,23 @@ namespace RGB.NET.Devices.Logitech.Native
return $"{major}.{minor}.{build}"; return $"{major}.{minor}.{build}";
} }
internal static bool LogiLedGetSdkVersion(ref int majorNum, ref int minorNum, ref int buildNum) => _logiLedGetSdkVersionPointer(ref majorNum, ref minorNum, ref buildNum); internal static bool LogiLedGetSdkVersion(ref int majorNum, ref int minorNum, ref int buildNum) =>
(_logiLedGetSdkVersionPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke(ref majorNum, ref minorNum, ref buildNum);
internal static bool LogiLedSaveCurrentLighting() => _lgiLedSaveCurrentLightingPointer(); internal static bool LogiLedSaveCurrentLighting() => (_lgiLedSaveCurrentLightingPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke();
internal static bool LogiLedRestoreLighting() => _logiLedRestoreLightingPointer(); internal static bool LogiLedRestoreLighting() => (_logiLedRestoreLightingPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke();
internal static bool LogiLedSetLighting(int redPercentage, int greenPercentage, int bluePercentage) => _logiLedSetLightingPointer(redPercentage, greenPercentage, bluePercentage); internal static bool LogiLedSetLighting(int redPercentage, int greenPercentage, int bluePercentage) =>
(_logiLedSetLightingPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke(redPercentage, greenPercentage, bluePercentage);
internal static bool LogiLedSetLightingForKeyWithKeyName(int keyCode, int redPercentage, int greenPercentage, int bluePercentage) internal static bool LogiLedSetLightingForKeyWithKeyName(int keyCode, int redPercentage, int greenPercentage, int bluePercentage)
=> _logiLedSetLightingForKeyWithKeyNamePointer(keyCode, redPercentage, greenPercentage, bluePercentage); => (_logiLedSetLightingForKeyWithKeyNamePointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke(keyCode, redPercentage, greenPercentage, bluePercentage);
internal static bool LogiLedSetLightingFromBitmap(byte[] bitmap) => _logiLedSetLightingFromBitmapPointer(bitmap); internal static bool LogiLedSetLightingFromBitmap(byte[] bitmap) => (_logiLedSetLightingFromBitmapPointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke(bitmap);
internal static bool LogiLedSetLightingForTargetZone(LogitechDeviceType deviceType, int zone, int redPercentage, int greenPercentage, int bluePercentage) internal static bool LogiLedSetLightingForTargetZone(LogitechDeviceType deviceType, int zone, int redPercentage, int greenPercentage, int bluePercentage)
=> _logiLedSetLightingForTargetZonePointer(deviceType, zone, redPercentage, greenPercentage, bluePercentage); => (_logiLedSetLightingForTargetZonePointer ?? throw new RGBDeviceException("The Logitech-GSDK is not initialized.")).Invoke(deviceType, zone, redPercentage, greenPercentage, bluePercentage);
// ReSharper restore EventExceptionNotDocumented // ReSharper restore EventExceptionNotDocumented

View File

@ -33,10 +33,10 @@ namespace RGB.NET.Devices.Logitech
AddLed(LedId.Custom1, new Point(0, 0), new Size(10, 10)); AddLed(LedId.Custom1, new Point(0, 0), new Size(10, 10));
} }
/// <inheritdoc /> /// <inheritdoc />
protected override object? GetLedCustomData(LedId ledId) => (ledId, LogitechLedId.DEVICE); protected override object GetLedCustomData(LedId ledId) => (ledId, LogitechLedId.DEVICE);
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0).Take(1)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0).Take(1));
#endregion #endregion
} }

View File

@ -14,8 +14,8 @@ namespace RGB.NET.Devices.Logitech
#region Properties & Fields #region Properties & Fields
internal static Dictionary<LedId, int> BitmapOffset { get; } = new Dictionary<LedId, int> internal static Dictionary<LedId, int> BitmapOffset { get; } = new()
{ {
{ LedId.Keyboard_Escape, 0 }, { LedId.Keyboard_Escape, 0 },
{ LedId.Keyboard_F1, 4 }, { LedId.Keyboard_F1, 4 },
{ LedId.Keyboard_F2, 8 }, { LedId.Keyboard_F2, 8 },

View File

@ -29,7 +29,7 @@ namespace RGB.NET.Devices.Logitech
protected override object? GetLedCustomData(LedId ledId) => (ledId, PerKeyIdMapping.DEFAULT.TryGetValue(ledId, out LogitechLedId logitechLedId) ? logitechLedId : LogitechLedId.Invalid); protected override object? GetLedCustomData(LedId ledId) => (ledId, PerKeyIdMapping.DEFAULT.TryGetValue(ledId, out LogitechLedId logitechLedId) ? logitechLedId : LogitechLedId.Invalid);
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
#endregion #endregion
} }

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Logitech
{ {
internal static class PerKeyIdMapping internal static class PerKeyIdMapping
{ {
internal static readonly Dictionary<LedId, LogitechLedId> DEFAULT = new Dictionary<LedId, LogitechLedId> internal static readonly Dictionary<LedId, LogitechLedId> DEFAULT = new()
{ {
{ LedId.Invalid, LogitechLedId.Invalid }, { LedId.Invalid, LogitechLedId.Invalid },
{ LedId.Keyboard_Escape, LogitechLedId.ESC }, { LedId.Keyboard_Escape, LogitechLedId.ESC },
{ LedId.Keyboard_F1, LogitechLedId.F1 }, { LedId.Keyboard_F1, LogitechLedId.F1 },

View File

@ -12,13 +12,13 @@ namespace RGB.NET.Devices.Logitech
{ {
#region Constants #region Constants
private static readonly Dictionary<RGBDeviceType, LedId> BASE_LED_MAPPING = new Dictionary<RGBDeviceType, LedId> private static readonly Dictionary<RGBDeviceType, LedId> BASE_LED_MAPPING = new()
{ {
{RGBDeviceType.Keyboard, LedId.Keyboard_Programmable1}, { RGBDeviceType.Keyboard, LedId.Keyboard_Programmable1 },
{RGBDeviceType.Mouse, LedId.Mouse1}, { RGBDeviceType.Mouse, LedId.Mouse1 },
{RGBDeviceType.Headset, LedId.Headset1}, { RGBDeviceType.Headset, LedId.Headset1 },
{RGBDeviceType.Mousepad, LedId.Mousepad1}, { RGBDeviceType.Mousepad, LedId.Mousepad1 },
{RGBDeviceType.Speaker, LedId.Speaker1} { RGBDeviceType.Speaker, LedId.Speaker1 }
}; };
#endregion #endregion
@ -59,7 +59,7 @@ namespace RGB.NET.Devices.Logitech
protected override object? GetLedCustomData(LedId ledId) => (int)(ledId - _baseLedId); protected override object? GetLedCustomData(LedId ledId) => (int)(ledId - _baseLedId);
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
#endregion #endregion
} }

View File

@ -12,8 +12,8 @@ namespace RGB.NET.Devices.Logitech
{ {
#region Constants #region Constants
private static readonly Dictionary<RGBDeviceType, LogitechDeviceType> DEVICE_TYPE_MAPPING = new Dictionary<RGBDeviceType, LogitechDeviceType> private static readonly Dictionary<RGBDeviceType, LogitechDeviceType> DEVICE_TYPE_MAPPING = new()
{ {
{RGBDeviceType.Keyboard, LogitechDeviceType.Keyboard}, {RGBDeviceType.Keyboard, LogitechDeviceType.Keyboard},
{RGBDeviceType.Mouse, LogitechDeviceType.Mouse}, {RGBDeviceType.Mouse, LogitechDeviceType.Mouse},
{RGBDeviceType.Headset, LogitechDeviceType.Headset}, {RGBDeviceType.Headset, LogitechDeviceType.Headset},

View File

@ -24,7 +24,7 @@ namespace RGB.NET.Devices.Msi
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected MsiDeviceUpdateQueue DeviceUpdateQueue { get; set; } protected MsiDeviceUpdateQueue? DeviceUpdateQueue { get; set; }
#endregion #endregion
@ -54,7 +54,7 @@ namespace RGB.NET.Devices.Msi
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
} }
@ -66,7 +66,7 @@ namespace RGB.NET.Devices.Msi
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate)
=> DeviceUpdateQueue.SetData(ledsToUpdate.Where(x => (x.Color.A > 0) && (x.CustomData is int))); => DeviceUpdateQueue?.SetData(ledsToUpdate.Where(x => (x.Color.A > 0) && (x.CustomData is int)));
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -5,6 +5,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Globalization; using System.Globalization;
using System.Linq;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.Msi.Exceptions; using RGB.NET.Devices.Msi.Exceptions;
using RGB.NET.Devices.Msi.Native; using RGB.NET.Devices.Msi.Native;
@ -19,7 +20,7 @@ namespace RGB.NET.Devices.Msi
{ {
#region Properties & Fields #region Properties & Fields
private static MsiDeviceProvider _instance; private static MsiDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="MsiDeviceProvider"/> instance. /// Gets the singleton <see cref="MsiDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -29,13 +30,13 @@ namespace RGB.NET.Devices.Msi
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/MysticLight_SDK.dll" }; public static List<string> PossibleX86NativePaths { get; } = new() { "x86/MysticLight_SDK.dll" };
/// <summary> /// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/MysticLight_SDK.dll" }; public static List<string> PossibleX64NativePaths { get; } = new() { "x64/MysticLight_SDK.dll" };
/// <inheritdoc /> /// <inheritdoc />
/// <summary> /// <summary>
@ -43,24 +44,8 @@ namespace RGB.NET.Devices.Msi
/// </summary> /// </summary>
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _MsiSDK.LoadedArchitecture;
/// <inheritdoc /> /// <inheritdoc />
/// <summary> public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for corsair devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for corsair devices.
@ -94,7 +79,7 @@ namespace RGB.NET.Devices.Msi
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
_MsiSDK.Reload(); _MsiSDK.Reload();
@ -117,7 +102,7 @@ namespace RGB.NET.Devices.Msi
//Hex3l: MSI_MB provide access to the motherboard "leds" where a led must be intended as a led header (JRGB, JRAINBOW etc..) (Tested on MSI X570 Unify) //Hex3l: MSI_MB provide access to the motherboard "leds" where a led must be intended as a led header (JRGB, JRAINBOW etc..) (Tested on MSI X570 Unify)
if (deviceType.Equals("MSI_MB")) if (deviceType.Equals("MSI_MB"))
{ {
MsiDeviceUpdateQueue updateQueue = new MsiDeviceUpdateQueue(UpdateTrigger, deviceType); MsiDeviceUpdateQueue updateQueue = new(UpdateTrigger, deviceType);
IMsiRGBDevice motherboard = new MsiMainboardRGBDevice(new MsiRGBDeviceInfo(RGBDeviceType.Mainboard, deviceType, "MSI", "Motherboard")); IMsiRGBDevice motherboard = new MsiMainboardRGBDevice(new MsiRGBDeviceInfo(RGBDeviceType.Mainboard, deviceType, "MSI", "Motherboard"));
motherboard.Initialize(updateQueue, ledCount); motherboard.Initialize(updateQueue, ledCount);
devices.Add(motherboard); devices.Add(motherboard);
@ -127,7 +112,7 @@ namespace RGB.NET.Devices.Msi
//Hex3l: Every led under MSI_VGA should be a different graphics card. Handling all the cards together seems a good way to avoid overlapping of leds //Hex3l: Every led under MSI_VGA should be a different graphics card. Handling all the cards together seems a good way to avoid overlapping of leds
//Hex3l: The led name is the name of the card (e.g. NVIDIA GeForce RTX 2080 Ti) we could provide it in device info. //Hex3l: The led name is the name of the card (e.g. NVIDIA GeForce RTX 2080 Ti) we could provide it in device info.
MsiDeviceUpdateQueue updateQueue = new MsiDeviceUpdateQueue(UpdateTrigger, deviceType); MsiDeviceUpdateQueue updateQueue = new(UpdateTrigger, deviceType);
IMsiRGBDevice graphicscard = new MsiGraphicsCardRGBDevice(new MsiRGBDeviceInfo(RGBDeviceType.GraphicsCard, deviceType, "MSI", "GraphicsCard")); IMsiRGBDevice graphicscard = new MsiGraphicsCardRGBDevice(new MsiRGBDeviceInfo(RGBDeviceType.GraphicsCard, deviceType, "MSI", "GraphicsCard"));
graphicscard.Initialize(updateQueue, ledCount); graphicscard.Initialize(updateQueue, ledCount);
devices.Add(graphicscard); devices.Add(graphicscard);
@ -137,7 +122,7 @@ namespace RGB.NET.Devices.Msi
//Hex3l: Every led under MSI_MOUSE should be a different mouse. Handling all the mouses together seems a good way to avoid overlapping of leds //Hex3l: Every led under MSI_MOUSE should be a different mouse. Handling all the mouses together seems a good way to avoid overlapping of leds
//Hex3l: The led name is the name of the mouse (e.g. msi CLUTCH GM11) we could provide it in device info. //Hex3l: The led name is the name of the mouse (e.g. msi CLUTCH GM11) we could provide it in device info.
MsiDeviceUpdateQueue updateQueue = new MsiDeviceUpdateQueue(UpdateTrigger, deviceType); MsiDeviceUpdateQueue updateQueue = new(UpdateTrigger, deviceType);
IMsiRGBDevice mouses = new MsiMouseRGBDevice(new MsiRGBDeviceInfo(RGBDeviceType.Mouse, deviceType, "MSI", "Mouse")); IMsiRGBDevice mouses = new MsiMouseRGBDevice(new MsiRGBDeviceInfo(RGBDeviceType.Mouse, deviceType, "MSI", "Mouse"));
mouses.Initialize(updateQueue, ledCount); mouses.Initialize(updateQueue, ledCount);
devices.Add(mouses); devices.Add(mouses);
@ -148,7 +133,7 @@ namespace RGB.NET.Devices.Msi
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
} }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;

View File

@ -17,11 +17,6 @@ namespace RGB.NET.Devices.Msi.Native
private static IntPtr _dllHandle = IntPtr.Zero; private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary> /// <summary>
/// Reloads the SDK. /// Reloads the SDK.
/// </summary> /// </summary>
@ -37,10 +32,10 @@ namespace RGB.NET.Devices.Msi.Native
// HACK: Load library at runtime to support both, x86 and x64 with one managed dll // HACK: Load library at runtime to support both, x86 and x64 with one managed dll
List<string> possiblePathList = Environment.Is64BitProcess ? MsiDeviceProvider.PossibleX64NativePaths : MsiDeviceProvider.PossibleX86NativePaths; List<string> possiblePathList = Environment.Is64BitProcess ? MsiDeviceProvider.PossibleX64NativePaths : MsiDeviceProvider.PossibleX86NativePaths;
string dllPath = possiblePathList.FirstOrDefault(File.Exists); string? dllPath = possiblePathList.FirstOrDefault(File.Exists);
if (dllPath == null) throw new RGBDeviceException($"Can't find the Msi-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'"); if (dllPath == null) throw new RGBDeviceException($"Can't find the Msi-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'");
SetDllDirectory(Path.GetDirectoryName(Path.GetFullPath(dllPath))); SetDllDirectory(Path.GetDirectoryName(Path.GetFullPath(dllPath))!);
_dllHandle = LoadLibrary(dllPath); _dllHandle = LoadLibrary(dllPath);
@ -87,20 +82,20 @@ namespace RGB.NET.Devices.Msi.Native
#region Pointers #region Pointers
private static InitializePointer _initializePointer; private static InitializePointer? _initializePointer;
private static GetDeviceInfoPointer _getDeviceInfoPointer; private static GetDeviceInfoPointer? _getDeviceInfoPointer;
private static GetLedInfoPointer _getLedInfoPointer; private static GetLedInfoPointer? _getLedInfoPointer;
private static GetLedColorPointer _getLedColorPointer; private static GetLedColorPointer? _getLedColorPointer;
private static GetLedStylePointer _getLedStylePointer; private static GetLedStylePointer? _getLedStylePointer;
private static GetLedMaxBrightPointer _getLedMaxBrightPointer; private static GetLedMaxBrightPointer? _getLedMaxBrightPointer;
private static GetLedBrightPointer _getLedBrightPointer; private static GetLedBrightPointer? _getLedBrightPointer;
private static GetLedMaxSpeedPointer _getLedMaxSpeedPointer; private static GetLedMaxSpeedPointer? _getLedMaxSpeedPointer;
private static GetLedSpeedPointer _getLedSpeedPointer; private static GetLedSpeedPointer? _getLedSpeedPointer;
private static SetLedColorPointer _setLedColorPointer; private static SetLedColorPointer? _setLedColorPointer;
private static SetLedStylePointer _setLedStylePointer; private static SetLedStylePointer? _setLedStylePointer;
private static SetLedBrightPointer _setLedBrightPointer; private static SetLedBrightPointer? _setLedBrightPointer;
private static SetLedSpeedPointer _setLedSpeedPointer; private static SetLedSpeedPointer? _setLedSpeedPointer;
private static GetErrorMessagePointer _getErrorMessagePointer; private static GetErrorMessagePointer? _getErrorMessagePointer;
#endregion #endregion
@ -192,11 +187,11 @@ namespace RGB.NET.Devices.Msi.Native
#endregion #endregion
internal static int Initialize() => _initializePointer(); internal static int Initialize() => (_initializePointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke();
internal static int GetDeviceInfo(out string[] pDevType, out int[] pLedCount) internal static int GetDeviceInfo(out string[] pDevType, out int[] pLedCount)
{ {
// HACK - SDK GetDeviceInfo returns a string[] for ledCount, so we'll parse that to int. // HACK - SDK GetDeviceInfo returns a string[] for ledCount, so we'll parse that to int.
int result = _getDeviceInfoPointer(out pDevType, out string[] ledCount); int result = (_getDeviceInfoPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(out pDevType, out string[] ledCount);
pLedCount = new int[ledCount.Length]; pLedCount = new int[ledCount.Length];
for (int i = 0; i < ledCount.Length; i++) for (int i = 0; i < ledCount.Length; i++)
@ -205,21 +200,21 @@ namespace RGB.NET.Devices.Msi.Native
return result; return result;
} }
internal static int GetLedInfo(string type, int index, out string pName, out string[] pLedStyles) => _getLedInfoPointer(type, index, out pName, out pLedStyles); internal static int GetLedInfo(string type, int index, out string pName, out string[] pLedStyles) => (_getLedInfoPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out pName, out pLedStyles);
internal static int GetLedColor(string type, int index, out int r, out int g, out int b) => _getLedColorPointer(type, index, out r, out g, out b); internal static int GetLedColor(string type, int index, out int r, out int g, out int b) => (_getLedColorPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out r, out g, out b);
internal static int GetLedStyle(string type, int index, out string style) => _getLedStylePointer(type, index, out style); internal static int GetLedStyle(string type, int index, out string style) => (_getLedStylePointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out style);
internal static int GetLedMaxBright(string type, int index, out int maxLevel) => _getLedMaxBrightPointer(type, index, out maxLevel); internal static int GetLedMaxBright(string type, int index, out int maxLevel) => (_getLedMaxBrightPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out maxLevel);
internal static int GetLedBright(string type, int index, out int currentLevel) => _getLedBrightPointer(type, index, out currentLevel); internal static int GetLedBright(string type, int index, out int currentLevel) => (_getLedBrightPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out currentLevel);
internal static int GetLedMaxSpeed(string type, int index, out int maxSpeed) => _getLedMaxSpeedPointer(type, index, out maxSpeed); internal static int GetLedMaxSpeed(string type, int index, out int maxSpeed) => (_getLedMaxSpeedPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out maxSpeed);
internal static int GetLedSpeed(string type, int index, out int currentSpeed) => _getLedSpeedPointer(type, index, out currentSpeed); internal static int GetLedSpeed(string type, int index, out int currentSpeed) => (_getLedSpeedPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, out currentSpeed);
internal static int SetLedColor(string type, int index, int r, int g, int b) => _setLedColorPointer(type, index, r, g, b); internal static int SetLedColor(string type, int index, int r, int g, int b) => (_setLedColorPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, r, g, b);
internal static int SetLedStyle(string type, int index, string style) => _setLedStylePointer(type, index, style); internal static int SetLedStyle(string type, int index, string style) => (_setLedStylePointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, style);
internal static int SetLedBright(string type, int index, int level) => _setLedBrightPointer(type, index, level); internal static int SetLedBright(string type, int index, int level) => (_setLedBrightPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, level);
internal static int SetLedSpeed(string type, int index, int speed) => _setLedSpeedPointer(type, index, speed); internal static int SetLedSpeed(string type, int index, int speed) => (_setLedSpeedPointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(type, index, speed);
internal static string GetErrorMessage(int errorCode) internal static string GetErrorMessage(int errorCode)
{ {
_getErrorMessagePointer(errorCode, out string description); (_getErrorMessagePointer ?? throw new RGBDeviceException("The MSI-SDK is not initialized.")).Invoke(errorCode, out string description);
return description; return description;
} }

View File

@ -47,7 +47,7 @@ namespace RGB.NET.Devices.Novation
/// Sends the specified message to the device this queue is performing updates for. /// Sends the specified message to the device this queue is performing updates for.
/// </summary> /// </summary>
/// <param name="message">The message to send.</param> /// <param name="message">The message to send.</param>
protected virtual void SendMessage(ShortMessage message) protected virtual void SendMessage(ShortMessage? message)
{ {
if (message != null) if (message != null)
_outputDevice.SendShort(message.Message); _outputDevice.SendShort(message.Message);
@ -59,7 +59,7 @@ namespace RGB.NET.Devices.Novation
/// </summary> /// </summary>
/// <param name="data">The data set to create the message from.</param> /// <param name="data">The data set to create the message from.</param>
/// <returns>The message created out of the data set.</returns> /// <returns>The message created out of the data set.</returns>
protected abstract ShortMessage CreateMessage(KeyValuePair<object, Color> data); protected abstract ShortMessage? CreateMessage(KeyValuePair<object, Color> data);
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -25,7 +25,7 @@ namespace RGB.NET.Devices.Novation
/// The <see cref="MidiUpdateQueue"/> used to update this <see cref="NovationRGBDevice{TDeviceInfo}"/>. /// The <see cref="MidiUpdateQueue"/> used to update this <see cref="NovationRGBDevice{TDeviceInfo}"/>.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected MidiUpdateQueue UpdateQueue { get; set; } protected MidiUpdateQueue? UpdateQueue { get; set; }
#endregion #endregion
@ -53,7 +53,7 @@ namespace RGB.NET.Devices.Novation
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
@ -71,12 +71,12 @@ namespace RGB.NET.Devices.Novation
protected abstract void InitializeLayout(); protected abstract void InitializeLayout();
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <summary> /// <summary>
/// Resets the <see cref="NovationRGBDevice{TDeviceInfo}"/> back to default. /// Resets the <see cref="NovationRGBDevice{TDeviceInfo}"/> back to default.
/// </summary> /// </summary>
public virtual void Reset() => UpdateQueue.Reset(); public virtual void Reset() => UpdateQueue?.Reset();
/// <inheritdoc cref="IDisposable.Dispose" /> /// <inheritdoc cref="IDisposable.Dispose" />
/// <inheritdoc cref="AbstractRGBDevice{TDeviceInfo}.Dispose" /> /// <inheritdoc cref="AbstractRGBDevice{TDeviceInfo}.Dispose" />

View File

@ -152,7 +152,7 @@ namespace RGB.NET.Devices.Novation
#region Methods #region Methods
/// <inheritdoc /> /// <inheritdoc />
protected override ShortMessage CreateMessage(KeyValuePair<object, Color> data) protected override ShortMessage? CreateMessage(KeyValuePair<object, Color> data)
{ {
(byte mode, byte id) = ((byte, byte))data.Key; (byte mode, byte id) = ((byte, byte))data.Key;
if (mode == 0x00) return null; if (mode == 0x00) return null;

View File

@ -14,7 +14,7 @@ namespace RGB.NET.Devices.Novation
/// </summary> /// </summary>
/// <param name="source">The enum value to get the description from.</param> /// <param name="source">The enum value to get the description from.</param>
/// <returns>The value of the <see cref="DeviceIdAttribute"/> of the source.</returns> /// <returns>The value of the <see cref="DeviceIdAttribute"/> of the source.</returns>
internal static string GetDeviceId(this Enum source) => source.GetAttribute<DeviceIdAttribute>()?.Id; internal static string? GetDeviceId(this Enum source) => source.GetAttribute<DeviceIdAttribute>()?.Id;
/// <summary> /// <summary>
/// Gets the value of the <see cref="ColorCapabilityAttribute"/>. /// Gets the value of the <see cref="ColorCapabilityAttribute"/>.
@ -36,10 +36,11 @@ namespace RGB.NET.Devices.Novation
/// <param name="source">The enum value to get the attribute from</param> /// <param name="source">The enum value to get the attribute from</param>
/// <typeparam name="T">The generic attribute type</typeparam> /// <typeparam name="T">The generic attribute type</typeparam>
/// <returns>The <see cref="Attribute"/>.</returns> /// <returns>The <see cref="Attribute"/>.</returns>
private static T GetAttribute<T>(this Enum source) private static T? GetAttribute<T>(this Enum source)
where T : Attribute where T : Attribute
{ {
FieldInfo fi = source.GetType().GetField(source.ToString()); FieldInfo? fi = source.GetType().GetField(source.ToString());
if (fi == null) return null;
T[] attributes = (T[])fi.GetCustomAttributes(typeof(T), false); T[] attributes = (T[])fi.GetCustomAttributes(typeof(T), false);
return attributes.Length > 0 ? attributes[0] : null; return attributes.Length > 0 ? attributes[0] : null;
} }

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Novation
{ {
internal static class LaunchpadIdMapping internal static class LaunchpadIdMapping
{ {
internal static readonly Dictionary<LedId, (byte mode, byte id, int x, int y)> LEGACY = new Dictionary<LedId, (byte mode, byte id, int x, int y)> internal static readonly Dictionary<LedId, (byte mode, byte id, int x, int y)> LEGACY = new()
{ {
{ LedId.Invalid, (0x00, 0xFF, 8, 0) }, { LedId.Invalid, (0x00, 0xFF, 8, 0) },
{ LedId.LedMatrix1, (0x90, 0x00, 0, 1) }, { LedId.LedMatrix1, (0x90, 0x00, 0, 1) },
@ -93,8 +93,8 @@ namespace RGB.NET.Devices.Novation
{ LedId.Custom16, (0x90, 0x78, 8, 8) }, //Scene8 { LedId.Custom16, (0x90, 0x78, 8, 8) }, //Scene8
}; };
internal static readonly Dictionary<LedId, (byte mode, byte id, int x, int y)> CURRENT = new Dictionary<LedId, (byte mode, byte id, int x, int y)> internal static readonly Dictionary<LedId, (byte mode, byte id, int x, int y)> CURRENT = new()
{ {
{ LedId.Invalid, (0x00, 0xFF, 8, 0) }, { LedId.Invalid, (0x00, 0xFF, 8, 0) },
{ LedId.LedMatrix1, (0x90, 81, 0, 1) }, { LedId.LedMatrix1, (0x90, 81, 0, 1) },

View File

@ -18,7 +18,7 @@ namespace RGB.NET.Devices.Novation
{ {
#region Properties & Fields #region Properties & Fields
private static NovationDeviceProvider _instance; private static NovationDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="NovationDeviceProvider"/> instance. /// Gets the singleton <see cref="NovationDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -31,18 +31,12 @@ namespace RGB.NET.Devices.Novation
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
/// <summary> public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess => false;
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for novation devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for novation devices.
/// </summary> /// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; } public DeviceUpdateTrigger UpdateTrigger { get; }
#endregion #endregion
@ -71,7 +65,7 @@ namespace RGB.NET.Devices.Novation
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
IList<IRGBDevice> devices = new List<IRGBDevice>(); IList<IRGBDevice> devices = new List<IRGBDevice>();
@ -85,7 +79,7 @@ namespace RGB.NET.Devices.Novation
NovationDevices? deviceId = (NovationDevices?)Enum.GetValues(typeof(NovationDevices)) NovationDevices? deviceId = (NovationDevices?)Enum.GetValues(typeof(NovationDevices))
.Cast<Enum>() .Cast<Enum>()
.FirstOrDefault(x => x.GetDeviceId().ToUpperInvariant().Contains(outCaps.name.ToUpperInvariant())); .FirstOrDefault(x => x.GetDeviceId()?.ToUpperInvariant().Contains(outCaps.name.ToUpperInvariant()) ?? false);
if (deviceId == null) continue; if (deviceId == null) continue;
@ -99,7 +93,7 @@ namespace RGB.NET.Devices.Novation
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
} }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;
} }
@ -118,7 +112,7 @@ namespace RGB.NET.Devices.Novation
{ {
foreach (IRGBDevice device in Devices) foreach (IRGBDevice device in Devices)
{ {
NovationLaunchpadRGBDevice novationDevice = device as NovationLaunchpadRGBDevice; NovationLaunchpadRGBDevice? novationDevice = device as NovationLaunchpadRGBDevice;
novationDevice?.Reset(); novationDevice?.Reset();
} }
} }
@ -126,7 +120,7 @@ namespace RGB.NET.Devices.Novation
/// <inheritdoc /> /// <inheritdoc />
public void Dispose() public void Dispose()
{ {
try { UpdateTrigger?.Dispose(); } try { UpdateTrigger.Dispose(); }
catch { /* at least we tried */ } catch { /* at least we tried */ }
} }

View File

@ -34,7 +34,8 @@ namespace RGB.NET.Devices.Razer
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
colors[(int)data.Key] = new _Color(data.Value); colors[(int)data.Key] = new _Color(data.Value);
_ChromaLinkCustomEffect effectParams = new _ChromaLinkCustomEffect { Color = colors }; _ChromaLinkCustomEffect effectParams = new()
{ Color = colors };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams)); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams));
Marshal.StructureToPtr(effectParams, ptr, false); Marshal.StructureToPtr(effectParams, ptr, false);

View File

@ -1,15 +0,0 @@
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace RGB.NET.Devices.Razer
{
/// <summary>
/// Contains list of available logical layouts for razer keyboards.
/// </summary>
public enum RazerLogicalKeyboardLayout
{
TODO
};
}

View File

@ -1,15 +0,0 @@
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace RGB.NET.Devices.Razer
{
/// <summary>
/// Contains list of available physical layouts for razer keyboards.
/// </summary>
public enum RazerPhysicalKeyboardLayout
{
TODO
}
}

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Razer
{ {
internal class Devices internal class Devices
{ {
public static readonly List<(Guid guid, string model)> KEYBOARDS = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> KEYBOARDS = new()
{ {
(new Guid("2EA1BB63-CA28-428D-9F06-196B88330BBB"), "Blackwidow Chroma"), (new Guid("2EA1BB63-CA28-428D-9F06-196B88330BBB"), "Blackwidow Chroma"),
(new Guid("ED1C1B82-BFBE-418F-B49D-D03F05B149DF"), "Razer Blackwidow Chroma Tournament Edition"), (new Guid("ED1C1B82-BFBE-418F-B49D-D03F05B149DF"), "Razer Blackwidow Chroma Tournament Edition"),
(new Guid("18C5AD9B-4326-4828-92C4-2669A66D2283"), "Razer Deathstalker "), (new Guid("18C5AD9B-4326-4828-92C4-2669A66D2283"), "Razer Deathstalker "),
@ -22,8 +22,8 @@ namespace RGB.NET.Devices.Razer
(new Guid("16BB5ABD-C1CD-4CB3-BDF7-62438748BD98"), "Razer Blackwidow Elite") (new Guid("16BB5ABD-C1CD-4CB3-BDF7-62438748BD98"), "Razer Blackwidow Elite")
}; };
public static readonly List<(Guid guid, string model)> MICE = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> MICE = new()
{ {
(new Guid("7EC00450-E0EE-4289-89D5-0D879C19061A"), "Razer Mamba Chroma Tournament Edition"), (new Guid("7EC00450-E0EE-4289-89D5-0D879C19061A"), "Razer Mamba Chroma Tournament Edition"),
(new Guid("AEC50D91-B1F1-452F-8E16-7B73F376FDF3"), "Razer Deathadder Chroma "), (new Guid("AEC50D91-B1F1-452F-8E16-7B73F376FDF3"), "Razer Deathadder Chroma "),
(new Guid("FF8A5929-4512-4257-8D59-C647BF9935D0"), "Razer Diamondback"), (new Guid("FF8A5929-4512-4257-8D59-C647BF9935D0"), "Razer Diamondback"),
@ -35,35 +35,35 @@ namespace RGB.NET.Devices.Razer
(new Guid("77834867-3237-4A9F-AD77-4A46C4183003"), "Razer DeathAdder Elite Chroma") (new Guid("77834867-3237-4A9F-AD77-4A46C4183003"), "Razer DeathAdder Elite Chroma")
}; };
public static readonly List<(Guid guid, string model)> HEADSETS = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> HEADSETS = new()
{ {
(new Guid("DF3164D7-5408-4A0E-8A7F-A7412F26BEBF"), "Razer ManO'War"), (new Guid("DF3164D7-5408-4A0E-8A7F-A7412F26BEBF"), "Razer ManO'War"),
(new Guid("CD1E09A5-D5E6-4A6C-A93B-E6D9BF1D2092"), "Razer Kraken 7.1 Chroma"), (new Guid("CD1E09A5-D5E6-4A6C-A93B-E6D9BF1D2092"), "Razer Kraken 7.1 Chroma"),
(new Guid("7FB8A36E-9E74-4BB3-8C86-CAC7F7891EBD"), "Razer Kraken 7.1 Chroma Refresh"), (new Guid("7FB8A36E-9E74-4BB3-8C86-CAC7F7891EBD"), "Razer Kraken 7.1 Chroma Refresh"),
(new Guid("FB357780-4617-43A7-960F-D1190ED54806"), "Razer Kraken Kitty") (new Guid("FB357780-4617-43A7-960F-D1190ED54806"), "Razer Kraken Kitty")
}; };
public static readonly List<(Guid guid, string model)> MOUSEMATS = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> MOUSEMATS = new()
{ {
(new Guid("80F95A94-73D2-48CA-AE9A-0986789A9AF2"), "Razer Firefly") (new Guid("80F95A94-73D2-48CA-AE9A-0986789A9AF2"), "Razer Firefly")
}; };
public static readonly List<(Guid guid, string model)> KEYPADS = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> KEYPADS = new()
{ {
(new Guid("9D24B0AB-0162-466C-9640-7A924AA4D9FD"), "Razer Orbweaver"), (new Guid("9D24B0AB-0162-466C-9640-7A924AA4D9FD"), "Razer Orbweaver"),
(new Guid("00F0545C-E180-4AD1-8E8A-419061CE505E"), "Razer Tartarus") (new Guid("00F0545C-E180-4AD1-8E8A-419061CE505E"), "Razer Tartarus")
}; };
public static readonly List<(Guid guid, string model)> CHROMALINKS = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> CHROMALINKS = new()
{ {
(new Guid("0201203B-62F3-4C50-83DD-598BABD208E0"), "Core Chroma"), (new Guid("0201203B-62F3-4C50-83DD-598BABD208E0"), "Core Chroma"),
(new Guid("35F6F18D-1AE5-436C-A575-AB44A127903A"), "Lenovo Y900"), (new Guid("35F6F18D-1AE5-436C-A575-AB44A127903A"), "Lenovo Y900"),
(new Guid("47DB1FA7-6B9B-4EE6-B6F4-4071A3B2053B"), "Lenovo Y27"), (new Guid("47DB1FA7-6B9B-4EE6-B6F4-4071A3B2053B"), "Lenovo Y27"),
(new Guid("BB2E9C9B-B0D2-461A-BA52-230B5D6C3609"), "Chroma Box") (new Guid("BB2E9C9B-B0D2-461A-BA52-230B5D6C3609"), "Chroma Box")
}; };
public static readonly List<(Guid guid, string model)> SPEAKERS = new List<(Guid guid, string model)> public static readonly List<(Guid guid, string model)> SPEAKERS = new()
{ {
(new Guid("45B308F2-CD44-4594-8375-4D5945AD880E"), "Nommo Chroma"), (new Guid("45B308F2-CD44-4594-8375-4D5945AD880E"), "Nommo Chroma"),
(new Guid("3017280B-D7F9-4D7B-930E-7B47181B46B5"), "Nommo Chroma Pro") (new Guid("3017280B-D7F9-4D7B-930E-7B47181B46B5"), "Nommo Chroma Pro")
}; };

View File

@ -24,7 +24,7 @@ namespace RGB.NET.Devices.Razer
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected RazerUpdateQueue UpdateQueue { get; set; } protected RazerUpdateQueue? UpdateQueue { get; set; }
#endregion #endregion
@ -54,7 +54,7 @@ namespace RGB.NET.Devices.Razer
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
@ -74,12 +74,12 @@ namespace RGB.NET.Devices.Razer
protected abstract void InitializeLayout(); protected abstract void InitializeLayout();
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <summary> /// <summary>
/// Resets the device. /// Resets the device.
/// </summary> /// </summary>
public void Reset() => UpdateQueue.Reset(); public void Reset() => UpdateQueue?.Reset();
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -34,7 +34,8 @@ namespace RGB.NET.Devices.Razer
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
colors[(int)data.Key] = new _Color(data.Value); colors[(int)data.Key] = new _Color(data.Value);
_HeadsetCustomEffect effectParams = new _HeadsetCustomEffect { Color = colors }; _HeadsetCustomEffect effectParams = new()
{ Color = colors };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams)); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams));
Marshal.StructureToPtr(effectParams, ptr, false); Marshal.StructureToPtr(effectParams, ptr, false);

View File

@ -2,7 +2,6 @@
// ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Global
using System; using System;
using System.Globalization;
using RGB.NET.Core; using RGB.NET.Core;
namespace RGB.NET.Devices.Razer namespace RGB.NET.Devices.Razer
@ -13,20 +12,6 @@ namespace RGB.NET.Devices.Razer
/// </summary> /// </summary>
public class RazerKeyboardRGBDeviceInfo : RazerRGBDeviceInfo public class RazerKeyboardRGBDeviceInfo : RazerRGBDeviceInfo
{ {
#region Properties & Fields
/// <summary>
/// Gets the physical layout of the keyboard.
/// </summary>
public RazerPhysicalKeyboardLayout PhysicalLayout { get; private set; }
/// <summary>
/// Gets the logical layout of the keyboard as set in CUE settings.
/// </summary>
public RazerLogicalKeyboardLayout LogicalLayout { get; private set; }
#endregion
#region Constructors #region Constructors
/// <inheritdoc /> /// <inheritdoc />
@ -36,27 +21,9 @@ namespace RGB.NET.Devices.Razer
/// <param name="deviceId">The Id of the <see cref="IRGBDevice"/>.</param> /// <param name="deviceId">The Id of the <see cref="IRGBDevice"/>.</param>
/// <param name="model">The model of the <see cref="IRGBDevice"/>.</param> /// <param name="model">The model of the <see cref="IRGBDevice"/>.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> of the layout this keyboard is using.</param> /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> of the layout this keyboard is using.</param>
internal RazerKeyboardRGBDeviceInfo(Guid deviceId, string model, CultureInfo culture) internal RazerKeyboardRGBDeviceInfo(Guid deviceId, string model)
: base(deviceId, RGBDeviceType.Keyboard, model) : base(deviceId, RGBDeviceType.Keyboard, model)
{ { }
SetLayouts(culture.KeyboardLayoutId);
}
#endregion
#region Methods
private void SetLayouts(int keyboardLayoutId)
{
switch (keyboardLayoutId)
{
//TODO DarthAffe 07.10.2017: Implement
default:
PhysicalLayout = RazerPhysicalKeyboardLayout.TODO;
LogicalLayout = RazerLogicalKeyboardLayout.TODO;
break;
}
}
#endregion #endregion
} }

View File

@ -34,7 +34,8 @@ namespace RGB.NET.Devices.Razer
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
colors[(int)data.Key] = new _Color(data.Value); colors[(int)data.Key] = new _Color(data.Value);
_KeyboardCustomEffect effectParams = new _KeyboardCustomEffect { Color = colors }; _KeyboardCustomEffect effectParams = new()
{ Color = colors };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams)); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams));
Marshal.StructureToPtr(effectParams, ptr, false); Marshal.StructureToPtr(effectParams, ptr, false);

View File

@ -34,7 +34,8 @@ namespace RGB.NET.Devices.Razer
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
colors[(int)data.Key] = new _Color(data.Value); colors[(int)data.Key] = new _Color(data.Value);
_KeypadCustomEffect effectParams = new _KeypadCustomEffect { Color = colors }; _KeypadCustomEffect effectParams = new()
{ Color = colors };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams)); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams));
Marshal.StructureToPtr(effectParams, ptr, false); Marshal.StructureToPtr(effectParams, ptr, false);

View File

@ -34,7 +34,8 @@ namespace RGB.NET.Devices.Razer
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
colors[(int)data.Key] = new _Color(data.Value); colors[(int)data.Key] = new _Color(data.Value);
_MouseCustomEffect effectParams = new _MouseCustomEffect { Color = colors }; _MouseCustomEffect effectParams = new()
{ Color = colors };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams)); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams));
Marshal.StructureToPtr(effectParams, ptr, false); Marshal.StructureToPtr(effectParams, ptr, false);

View File

@ -34,7 +34,8 @@ namespace RGB.NET.Devices.Razer
foreach (KeyValuePair<object, Color> data in dataSet) foreach (KeyValuePair<object, Color> data in dataSet)
colors[(int)data.Key] = new _Color(data.Value); colors[(int)data.Key] = new _Color(data.Value);
_MousepadCustomEffect effectParams = new _MousepadCustomEffect { Color = colors }; _MousepadCustomEffect effectParams = new()
{ Color = colors };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams)); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(effectParams));
Marshal.StructureToPtr(effectParams, ptr, false); Marshal.StructureToPtr(effectParams, ptr, false);

View File

@ -17,11 +17,6 @@ namespace RGB.NET.Devices.Razer.Native
private static IntPtr _dllHandle = IntPtr.Zero; private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary> /// <summary>
/// Reloads the SDK. /// Reloads the SDK.
/// </summary> /// </summary>
@ -78,16 +73,16 @@ namespace RGB.NET.Devices.Razer.Native
#region Pointers #region Pointers
private static InitPointer _initPointer; private static InitPointer? _initPointer;
private static UnInitPointer _unInitPointer; private static UnInitPointer? _unInitPointer;
private static QueryDevicePointer _queryDevicePointer; private static QueryDevicePointer? _queryDevicePointer;
private static CreateEffectPointer _createEffectPointer; private static CreateEffectPointer? _createEffectPointer;
private static CreateHeadsetEffectPointer _createHeadsetEffectPointer; private static CreateHeadsetEffectPointer? _createHeadsetEffectPointer;
private static CreateChromaLinkEffectPointer _createChromaLinkEffectPointer; private static CreateChromaLinkEffectPointer? _createChromaLinkEffectPointer;
private static CreateKeyboardEffectPointer _createKeyboardEffectPointer; private static CreateKeyboardEffectPointer? _createKeyboardEffectPointer;
private static CreateMousepadEffectPointer _createMousepadEffectPointer; private static CreateMousepadEffectPointer? _createMousepadEffectPointer;
private static SetEffectPointer _setEffectPointer; private static SetEffectPointer? _setEffectPointer;
private static DeleteEffectPointer _deleteEffectPointer; private static DeleteEffectPointer? _deleteEffectPointer;
#endregion #endregion
@ -130,12 +125,12 @@ namespace RGB.NET.Devices.Razer.Native
/// <summary> /// <summary>
/// Razer-SDK: Initialize Chroma SDK. /// Razer-SDK: Initialize Chroma SDK.
/// </summary> /// </summary>
internal static RazerError Init() => _initPointer(); internal static RazerError Init() => (_initPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke();
/// <summary> /// <summary>
/// Razer-SDK: UnInitialize Chroma SDK. /// Razer-SDK: UnInitialize Chroma SDK.
/// </summary> /// </summary>
internal static RazerError UnInit() => _unInitPointer(); internal static RazerError UnInit() => (_unInitPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke();
/// <summary> /// <summary>
/// Razer-SDK: Query for device information. /// Razer-SDK: Query for device information.
@ -145,27 +140,27 @@ namespace RGB.NET.Devices.Razer.Native
int structSize = Marshal.SizeOf(typeof(_DeviceInfo)); int structSize = Marshal.SizeOf(typeof(_DeviceInfo));
IntPtr deviceInfoPtr = Marshal.AllocHGlobal(structSize); IntPtr deviceInfoPtr = Marshal.AllocHGlobal(structSize);
RazerError error = _queryDevicePointer(deviceId, deviceInfoPtr); RazerError error = (_queryDevicePointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(deviceId, deviceInfoPtr);
deviceInfo = (_DeviceInfo)Marshal.PtrToStructure(deviceInfoPtr, typeof(_DeviceInfo)); deviceInfo = (_DeviceInfo)Marshal.PtrToStructure(deviceInfoPtr, typeof(_DeviceInfo))!;
Marshal.FreeHGlobal(deviceInfoPtr); Marshal.FreeHGlobal(deviceInfoPtr);
return error; return error;
} }
internal static RazerError CreateEffect(Guid deviceId, int effectType, IntPtr param, ref Guid effectId) => _createEffectPointer(deviceId, effectType, param, ref effectId); internal static RazerError CreateEffect(Guid deviceId, int effectType, IntPtr param, ref Guid effectId) => (_createEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(deviceId, effectType, param, ref effectId);
internal static RazerError CreateHeadsetEffect(int effectType, IntPtr param, ref Guid effectId) => _createHeadsetEffectPointer(effectType, param, ref effectId); internal static RazerError CreateHeadsetEffect(int effectType, IntPtr param, ref Guid effectId) => (_createHeadsetEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(effectType, param, ref effectId);
internal static RazerError CreateChromaLinkEffect(int effectType, IntPtr param, ref Guid effectId) => _createChromaLinkEffectPointer(effectType, param, ref effectId); internal static RazerError CreateChromaLinkEffect(int effectType, IntPtr param, ref Guid effectId) => (_createChromaLinkEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(effectType, param, ref effectId);
internal static RazerError CreateKeyboardEffect(int effectType, IntPtr param, ref Guid effectId) => _createKeyboardEffectPointer(effectType, param, ref effectId); internal static RazerError CreateKeyboardEffect(int effectType, IntPtr param, ref Guid effectId) => (_createKeyboardEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(effectType, param, ref effectId);
internal static RazerError CreateMousepadEffect(int effectType, IntPtr param, ref Guid effectId) => _createMousepadEffectPointer(effectType, param, ref effectId); internal static RazerError CreateMousepadEffect(int effectType, IntPtr param, ref Guid effectId) => (_createMousepadEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(effectType, param, ref effectId);
internal static RazerError SetEffect(Guid effectId) => _setEffectPointer(effectId); internal static RazerError SetEffect(Guid effectId) => (_setEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(effectId);
internal static RazerError DeleteEffect(Guid effectId) => _deleteEffectPointer(effectId); internal static RazerError DeleteEffect(Guid effectId) => (_deleteEffectPointer ?? throw new RGBDeviceException("The Razer-SDK is not initialized.")).Invoke(effectId);
// ReSharper restore EventExceptionNotDocumented // ReSharper restore EventExceptionNotDocumented

View File

@ -20,7 +20,7 @@ namespace RGB.NET.Devices.Razer
{ {
#region Properties & Fields #region Properties & Fields
private static RazerDeviceProvider _instance; private static RazerDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="RazerDeviceProvider"/> instance. /// Gets the singleton <see cref="RazerDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -30,13 +30,13 @@ namespace RGB.NET.Devices.Razer
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { @"%systemroot%\SysWOW64\RzChromaSDK.dll" }; public static List<string> PossibleX86NativePaths { get; } = new() { @"%systemroot%\SysWOW64\RzChromaSDK.dll" };
/// <summary> /// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications. /// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used. /// The first match will be used.
/// </summary> /// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { @"%systemroot%\System32\RzChromaSDK.dll", @"%systemroot%\System32\RzChromaSDK64.dll" }; public static List<string> PossibleX64NativePaths { get; } = new() { @"%systemroot%\System32\RzChromaSDK.dll", @"%systemroot%\System32\RzChromaSDK64.dll" };
/// <inheritdoc /> /// <inheritdoc />
/// <summary> /// <summary>
@ -44,24 +44,8 @@ namespace RGB.NET.Devices.Razer
/// </summary> /// </summary>
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _RazerSDK.LoadedArchitecture;
/// <inheritdoc /> /// <inheritdoc />
/// <summary> public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess => false;
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
/// <summary> /// <summary>
/// Forces to load the devices represented by the emulator even if they aren't reported to exist. /// Forces to load the devices represented by the emulator even if they aren't reported to exist.
@ -71,7 +55,7 @@ namespace RGB.NET.Devices.Razer
/// <summary> /// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for razer devices. /// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for razer devices.
/// </summary> /// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; } public DeviceUpdateTrigger UpdateTrigger { get; }
#endregion #endregion
@ -103,7 +87,7 @@ namespace RGB.NET.Devices.Razer
try try
{ {
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
_RazerSDK.Reload(); _RazerSDK.Reload();
@ -121,7 +105,7 @@ namespace RGB.NET.Devices.Razer
if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1)) if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1))
&& (!LoadEmulatorDevices || (Razer.Devices.KEYBOARDS.FirstOrDefault().guid != guid))) continue; && (!LoadEmulatorDevices || (Razer.Devices.KEYBOARDS.FirstOrDefault().guid != guid))) continue;
RazerKeyboardRGBDevice device = new RazerKeyboardRGBDevice(new RazerKeyboardRGBDeviceInfo(guid, model, GetCulture())); RazerKeyboardRGBDevice device = new(new RazerKeyboardRGBDeviceInfo(guid, model));
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }
@ -134,7 +118,7 @@ namespace RGB.NET.Devices.Razer
if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1)) if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1))
&& (!LoadEmulatorDevices || (Razer.Devices.MICE.FirstOrDefault().guid != guid))) continue; && (!LoadEmulatorDevices || (Razer.Devices.MICE.FirstOrDefault().guid != guid))) continue;
RazerMouseRGBDevice device = new RazerMouseRGBDevice(new RazerMouseRGBDeviceInfo(guid, model)); RazerMouseRGBDevice device = new(new RazerMouseRGBDeviceInfo(guid, model));
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }
@ -147,7 +131,7 @@ namespace RGB.NET.Devices.Razer
if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1)) if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1))
&& (!LoadEmulatorDevices || (Razer.Devices.HEADSETS.FirstOrDefault().guid != guid))) continue; && (!LoadEmulatorDevices || (Razer.Devices.HEADSETS.FirstOrDefault().guid != guid))) continue;
RazerHeadsetRGBDevice device = new RazerHeadsetRGBDevice(new RazerHeadsetRGBDeviceInfo(guid, model)); RazerHeadsetRGBDevice device = new(new RazerHeadsetRGBDeviceInfo(guid, model));
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }
@ -160,7 +144,7 @@ namespace RGB.NET.Devices.Razer
if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1)) if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1))
&& (!LoadEmulatorDevices || (Razer.Devices.MOUSEMATS.FirstOrDefault().guid != guid))) continue; && (!LoadEmulatorDevices || (Razer.Devices.MOUSEMATS.FirstOrDefault().guid != guid))) continue;
RazerMousepadRGBDevice device = new RazerMousepadRGBDevice(new RazerMousepadRGBDeviceInfo(guid, model)); RazerMousepadRGBDevice device = new(new RazerMousepadRGBDeviceInfo(guid, model));
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }
@ -173,7 +157,7 @@ namespace RGB.NET.Devices.Razer
if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1)) if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1))
&& (!LoadEmulatorDevices || (Razer.Devices.KEYPADS.FirstOrDefault().guid != guid))) continue; && (!LoadEmulatorDevices || (Razer.Devices.KEYPADS.FirstOrDefault().guid != guid))) continue;
RazerKeypadRGBDevice device = new RazerKeypadRGBDevice(new RazerKeypadRGBDeviceInfo(guid, model)); RazerKeypadRGBDevice device = new(new RazerKeypadRGBDeviceInfo(guid, model));
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }
@ -186,13 +170,13 @@ namespace RGB.NET.Devices.Razer
if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1)) if (((_RazerSDK.QueryDevice(guid, out _DeviceInfo deviceInfo) != RazerError.Success) || (deviceInfo.Connected < 1))
&& (!LoadEmulatorDevices || (Razer.Devices.CHROMALINKS.FirstOrDefault().guid != guid))) continue; && (!LoadEmulatorDevices || (Razer.Devices.CHROMALINKS.FirstOrDefault().guid != guid))) continue;
RazerChromaLinkRGBDevice device = new RazerChromaLinkRGBDevice(new RazerChromaLinkRGBDeviceInfo(guid, model)); RazerChromaLinkRGBDevice device = new(new RazerChromaLinkRGBDeviceInfo(guid, model));
device.Initialize(UpdateTrigger); device.Initialize(UpdateTrigger);
devices.Add(device); devices.Add(device);
} }
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;
} }

View File

@ -5,6 +5,6 @@ namespace RGB.NET.Devices.SteelSeries.API.Model
internal class CoreProps internal class CoreProps
{ {
[JsonPropertyName("address")] [JsonPropertyName("address")]
public string Address { get; set; } public string? Address { get; set; }
} }
} }

View File

@ -8,13 +8,13 @@ namespace RGB.NET.Devices.SteelSeries.API.Model
#region Properties & Fields #region Properties & Fields
[JsonPropertyName("game")] [JsonPropertyName("game")]
public string Game { get; set; } public string? Game { get; set; }
[JsonPropertyName("event")] [JsonPropertyName("event")]
public string Name { get; set; } public string? Name { get; set; }
[JsonPropertyName("data")] [JsonPropertyName("data")]
public Dictionary<string, object> Data { get; } = new Dictionary<string, object>(); public Dictionary<string, object> Data { get; } = new();
#endregion #endregion

View File

@ -7,10 +7,10 @@ namespace RGB.NET.Devices.SteelSeries.API.Model
#region Properties & Fields #region Properties & Fields
[JsonPropertyName("game")] [JsonPropertyName("game")]
public string Name { get; set; } public string? Name { get; set; }
[JsonPropertyName("game_display_name")] [JsonPropertyName("game_display_name")]
public string DisplayName { get; set; } public string? DisplayName { get; set; }
#endregion #endregion

View File

@ -7,10 +7,10 @@ namespace RGB.NET.Devices.SteelSeries.API.Model
#region Properties & Fields #region Properties & Fields
[JsonPropertyName("game")] [JsonPropertyName("game")]
public string Game { get; set; } public string? Game { get; set; }
[JsonPropertyName("golisp")] [JsonPropertyName("golisp")]
public string Handler { get; set; } public string? Handler { get; set; }
#endregion #endregion

View File

@ -6,7 +6,6 @@ using System.Net.Http;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
using RGB.NET.Devices.SteelSeries.API.Model; using RGB.NET.Devices.SteelSeries.API.Model;
namespace RGB.NET.Devices.SteelSeries.API namespace RGB.NET.Devices.SteelSeries.API
@ -55,10 +54,10 @@ namespace RGB.NET.Devices.SteelSeries.API
#region Properties & Fields #region Properties & Fields
// ReSharper disable InconsistentNaming // ReSharper disable InconsistentNaming
private static readonly HttpClient _client = new HttpClient(); private static readonly HttpClient _client = new();
private static readonly Game _game = new Game(GAME_NAME, GAME_DISPLAYNAME); private static readonly Game _game = new(GAME_NAME, GAME_DISPLAYNAME);
private static readonly Event _event = new Event(_game, EVENT_NAME); private static readonly Event _event = new(_game, EVENT_NAME);
private static string _baseUrl; private static string? _baseUrl;
internal static bool IsInitialized => !string.IsNullOrWhiteSpace(_baseUrl); internal static bool IsInitialized => !string.IsNullOrWhiteSpace(_baseUrl);
@ -74,7 +73,7 @@ namespace RGB.NET.Devices.SteelSeries.API
string corePropsPath = GetCorePropsPath(); string corePropsPath = GetCorePropsPath();
if (!string.IsNullOrWhiteSpace(corePropsPath) && File.Exists(corePropsPath)) if (!string.IsNullOrWhiteSpace(corePropsPath) && File.Exists(corePropsPath))
{ {
CoreProps coreProps = JsonSerializer.Deserialize<CoreProps>(File.ReadAllText(corePropsPath)); CoreProps? coreProps = JsonSerializer.Deserialize<CoreProps>(File.ReadAllText(corePropsPath));
_baseUrl = coreProps?.Address; _baseUrl = coreProps?.Address;
if (_baseUrl != null) if (_baseUrl != null)
{ {
@ -93,12 +92,12 @@ namespace RGB.NET.Devices.SteelSeries.API
return IsInitialized; return IsInitialized;
} }
internal static void UpdateLeds(string device, Dictionary<string, int[]> data) internal static void UpdateLeds(string device, IList<(string zone, int[] color)> data)
{ {
_event.Data.Clear(); _event.Data.Clear();
_event.Data.Add("value", device); _event.Data.Add("value", device);
_event.Data.Add("colors", data.Values.ToList()); _event.Data.Add("colors", data.Select(x => x.color).ToList());
_event.Data.Add("zones", data.Keys.ToList()); _event.Data.Add("zones", data.Select(x => x.zone).ToList());
TriggerEvent(_event); TriggerEvent(_event);
} }

View File

@ -10,31 +10,31 @@ namespace RGB.NET.Devices.SteelSeries
#region Properties & Fields #region Properties & Fields
// ReSharper disable InconsistentNaming // ReSharper disable InconsistentNaming
private static readonly Dictionary<SteelSeriesDeviceType, string> _deviceTypeNames = new Dictionary<SteelSeriesDeviceType, string>(); private static readonly Dictionary<SteelSeriesDeviceType, string?> _deviceTypeNames = new();
private static readonly Dictionary<SteelSeriesLedId, string> _ledIdNames = new Dictionary<SteelSeriesLedId, string>(); private static readonly Dictionary<SteelSeriesLedId, string?> _ledIdNames = new();
// ReSharper restore InconsistentNaming // ReSharper restore InconsistentNaming
#endregion #endregion
#region Methods #region Methods
internal static string GetAPIName(this SteelSeriesDeviceType deviceType) internal static string? GetAPIName(this SteelSeriesDeviceType deviceType)
{ {
if (!_deviceTypeNames.TryGetValue(deviceType, out string apiName)) if (!_deviceTypeNames.TryGetValue(deviceType, out string? apiName))
_deviceTypeNames.Add(deviceType, apiName = GetAPIName(typeof(SteelSeriesDeviceType), deviceType)); _deviceTypeNames.Add(deviceType, apiName = GetAPIName(typeof(SteelSeriesDeviceType), deviceType));
return apiName; return apiName;
} }
internal static string GetAPIName(this SteelSeriesLedId ledId) internal static string? GetAPIName(this SteelSeriesLedId ledId)
{ {
if (!_ledIdNames.TryGetValue(ledId, out string apiName)) if (!_ledIdNames.TryGetValue(ledId, out string? apiName))
_ledIdNames.Add(ledId, apiName = GetAPIName(typeof(SteelSeriesLedId), ledId)); _ledIdNames.Add(ledId, apiName = GetAPIName(typeof(SteelSeriesLedId), ledId));
return apiName; return apiName;
} }
private static string GetAPIName(Type type, Enum value) private static string? GetAPIName(Type type, Enum value)
{ {
MemberInfo[] memInfo = type.GetMember(value.ToString()); MemberInfo[] memInfo = type.GetMember(value.ToString());
if (memInfo.Length == 0) return null; if (memInfo.Length == 0) return null;

View File

@ -35,9 +35,9 @@ namespace RGB.NET.Devices.SteelSeries
#region Methods #region Methods
protected override void OnUpdate(object sender, CustomUpdateData customData) protected override void OnUpdate(object? sender, CustomUpdateData customData)
{ {
if ((customData != null) && (customData["refresh"] as bool? ?? false)) if (customData["refresh"] as bool? ?? false)
SteelSeriesSDK.SendHeartbeat(); SteelSeriesSDK.SendHeartbeat();
else else
base.OnUpdate(sender, customData); base.OnUpdate(sender, customData);
@ -45,7 +45,7 @@ namespace RGB.NET.Devices.SteelSeries
/// <inheritdoc /> /// <inheritdoc />
protected override void Update(Dictionary<object, Color> dataSet) protected override void Update(Dictionary<object, Color> dataSet)
=> SteelSeriesSDK.UpdateLeds(_deviceType, dataSet.ToDictionary(x => ((SteelSeriesLedId)x.Key).GetAPIName(), x => x.Value.ToIntArray())); => SteelSeriesSDK.UpdateLeds(_deviceType, dataSet.Select(x => (((SteelSeriesLedId)x.Key).GetAPIName(), x.Value.ToIntArray())).Where(x => x.Item1 != null).ToList()!);
#endregion #endregion
} }

View File

@ -71,7 +71,7 @@ namespace RGB.NET.Devices.SteelSeries
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void OnUpdate(CustomUpdateData updateData = null) protected override void OnUpdate(CustomUpdateData? updateData = null)
{ {
base.OnUpdate(updateData); base.OnUpdate(updateData);
_lastUpdateTimestamp = Stopwatch.GetTimestamp(); _lastUpdateTimestamp = Stopwatch.GetTimestamp();

View File

@ -13,7 +13,7 @@ namespace RGB.NET.Devices.SteelSeries
{ {
#region Properties & Fields #region Properties & Fields
private Dictionary<LedId, SteelSeriesLedId> _ledMapping; private Dictionary<LedId, SteelSeriesLedId> _ledMapping = new();
/// <inheritdoc /> /// <inheritdoc />
/// <summary> /// <summary>
@ -25,7 +25,7 @@ namespace RGB.NET.Devices.SteelSeries
/// Gets or sets the update queue performing updates for this device. /// Gets or sets the update queue performing updates for this device.
/// </summary> /// </summary>
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global
protected UpdateQueue UpdateQueue { get; set; } protected UpdateQueue? UpdateQueue { get; set; }
#endregion #endregion
@ -68,7 +68,7 @@ namespace RGB.NET.Devices.SteelSeries
protected override object GetLedCustomData(LedId ledId) => _ledMapping[ledId]; protected override object GetLedCustomData(LedId ledId) => _ledMapping[ledId];
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()

View File

@ -1,5 +1,4 @@
using System; using RGB.NET.Core;
using RGB.NET.Core;
namespace RGB.NET.Devices.SteelSeries namespace RGB.NET.Devices.SteelSeries
{ {
@ -28,16 +27,6 @@ namespace RGB.NET.Devices.SteelSeries
public SteelSeriesDeviceType SteelSeriesDeviceType { get; } public SteelSeriesDeviceType SteelSeriesDeviceType { get; }
/// <summary>
/// Gets the layout used to decide which images to load.
/// </summary>
internal string ImageLayout { get; }
/// <summary>
/// Gets the path/name of the layout-file.
/// </summary>
internal string LayoutPath { get; }
#endregion #endregion
#region Constructors #region Constructors
@ -50,13 +39,11 @@ namespace RGB.NET.Devices.SteelSeries
/// <param name="deviceCaps">The lighting-capabilities of the device.</param> /// <param name="deviceCaps">The lighting-capabilities of the device.</param>
/// <param name="imageLayout">The layout used to decide which images to load.</param> /// <param name="imageLayout">The layout used to decide which images to load.</param>
/// <param name="layoutPath">The path/name of the layout-file.</param> /// <param name="layoutPath">The path/name of the layout-file.</param>
internal SteelSeriesRGBDeviceInfo(RGBDeviceType deviceType, string model, SteelSeriesDeviceType steelSeriesDeviceType, string imageLayout, string layoutPath) internal SteelSeriesRGBDeviceInfo(RGBDeviceType deviceType, string model, SteelSeriesDeviceType steelSeriesDeviceType)
{ {
this.DeviceType = deviceType; this.DeviceType = deviceType;
this.Model = model; this.Model = model;
this.SteelSeriesDeviceType = steelSeriesDeviceType; this.SteelSeriesDeviceType = steelSeriesDeviceType;
this.ImageLayout = imageLayout;
this.LayoutPath = layoutPath;
DeviceName = $"{Manufacturer} {Model}"; DeviceName = $"{Manufacturer} {Model}";
} }

View File

@ -2,7 +2,7 @@
using System.Linq; using System.Linq;
using HidSharp; using HidSharp;
using RGB.NET.Core; using RGB.NET.Core;
using DeviceDataList = System.Collections.Generic.List<(string model, RGB.NET.Core.RGBDeviceType deviceType, int id, RGB.NET.Devices.SteelSeries.SteelSeriesDeviceType steelSeriesDeviceType, string imageLayout, string layoutPath, System.Collections.Generic.Dictionary<RGB.NET.Core.LedId, RGB.NET.Devices.SteelSeries.SteelSeriesLedId> ledMapping)>; using DeviceDataList = System.Collections.Generic.List<(string model, RGB.NET.Core.RGBDeviceType deviceType, int id, RGB.NET.Devices.SteelSeries.SteelSeriesDeviceType steelSeriesDeviceType, System.Collections.Generic.Dictionary<RGB.NET.Core.LedId, RGB.NET.Devices.SteelSeries.SteelSeriesLedId> ledMapping)>;
using LedMapping = System.Collections.Generic.Dictionary<RGB.NET.Core.LedId, RGB.NET.Devices.SteelSeries.SteelSeriesLedId>; using LedMapping = System.Collections.Generic.Dictionary<RGB.NET.Core.LedId, RGB.NET.Devices.SteelSeries.SteelSeriesLedId>;
namespace RGB.NET.Devices.SteelSeries.HID namespace RGB.NET.Devices.SteelSeries.HID
@ -11,7 +11,7 @@ namespace RGB.NET.Devices.SteelSeries.HID
{ {
#region Constants #region Constants
private static readonly LedMapping KEYBOARD_MAPPING_UK = new LedMapping private static readonly LedMapping KEYBOARD_MAPPING_UK = new()
{ {
{ LedId.Logo, SteelSeriesLedId.Logo }, { LedId.Logo, SteelSeriesLedId.Logo },
{ LedId.Keyboard_Escape, SteelSeriesLedId.Escape }, { LedId.Keyboard_Escape, SteelSeriesLedId.Escape },
@ -121,7 +121,7 @@ namespace RGB.NET.Devices.SteelSeries.HID
{ LedId.Keyboard_NumPeriodAndDelete, SteelSeriesLedId.KeypadPeriod } { LedId.Keyboard_NumPeriodAndDelete, SteelSeriesLedId.KeypadPeriod }
}; };
private static readonly LedMapping KEYBOARD_TKL_MAPPING_UK = new LedMapping private static readonly LedMapping KEYBOARD_TKL_MAPPING_UK = new()
{ {
{ LedId.Logo, SteelSeriesLedId.Logo }, { LedId.Logo, SteelSeriesLedId.Logo },
{ LedId.Keyboard_Escape, SteelSeriesLedId.Escape }, { LedId.Keyboard_Escape, SteelSeriesLedId.Escape },
@ -214,87 +214,87 @@ namespace RGB.NET.Devices.SteelSeries.HID
{ LedId.Keyboard_ArrowRight, SteelSeriesLedId.RightArrow } { LedId.Keyboard_ArrowRight, SteelSeriesLedId.RightArrow }
}; };
private static readonly LedMapping MOUSE_ONE_ZONE = new LedMapping private static readonly LedMapping MOUSE_ONE_ZONE = new()
{ {
{LedId.Mouse1, SteelSeriesLedId.ZoneOne} { LedId.Mouse1, SteelSeriesLedId.ZoneOne }
}; };
private static readonly LedMapping MOUSE_TWO_ZONE = new LedMapping private static readonly LedMapping MOUSE_TWO_ZONE = new()
{
{LedId.Mouse1, SteelSeriesLedId.ZoneOne},
{LedId.Mouse2, SteelSeriesLedId.ZoneTwo}
};
private static readonly LedMapping MOUSE_THREE_ZONE = new LedMapping
{
{LedId.Mouse1, SteelSeriesLedId.ZoneOne},
{LedId.Mouse2, SteelSeriesLedId.ZoneTwo},
{LedId.Mouse3, SteelSeriesLedId.ZoneThree}
};
private static readonly LedMapping MOUSE_EIGHT_ZONE = new LedMapping
{
{ LedId.Mouse1, SteelSeriesLedId.ZoneOne},
{ LedId.Mouse2, SteelSeriesLedId.ZoneTwo},
{ LedId.Mouse3, SteelSeriesLedId.ZoneThree},
{ LedId.Mouse4, SteelSeriesLedId.ZoneFour},
{ LedId.Mouse5, SteelSeriesLedId.ZoneFive},
{ LedId.Mouse6, SteelSeriesLedId.ZoneSix},
{ LedId.Mouse7, SteelSeriesLedId.ZoneSeven},
{ LedId.Mouse8, SteelSeriesLedId.ZoneEight}
};
private static readonly LedMapping HEADSET_TWO_ZONE = new LedMapping
{ {
{LedId.Headset1, SteelSeriesLedId.ZoneOne}, { LedId.Mouse1, SteelSeriesLedId.ZoneOne },
{LedId.Headset2, SteelSeriesLedId.ZoneTwo} { LedId.Mouse2, SteelSeriesLedId.ZoneTwo }
};
private static readonly LedMapping MOUSE_THREE_ZONE = new()
{
{ LedId.Mouse1, SteelSeriesLedId.ZoneOne },
{ LedId.Mouse2, SteelSeriesLedId.ZoneTwo },
{ LedId.Mouse3, SteelSeriesLedId.ZoneThree }
};
private static readonly LedMapping MOUSE_EIGHT_ZONE = new()
{
{ LedId.Mouse1, SteelSeriesLedId.ZoneOne },
{ LedId.Mouse2, SteelSeriesLedId.ZoneTwo },
{ LedId.Mouse3, SteelSeriesLedId.ZoneThree },
{ LedId.Mouse4, SteelSeriesLedId.ZoneFour },
{ LedId.Mouse5, SteelSeriesLedId.ZoneFive },
{ LedId.Mouse6, SteelSeriesLedId.ZoneSix },
{ LedId.Mouse7, SteelSeriesLedId.ZoneSeven },
{ LedId.Mouse8, SteelSeriesLedId.ZoneEight }
};
private static readonly LedMapping HEADSET_TWO_ZONE = new()
{
{ LedId.Headset1, SteelSeriesLedId.ZoneOne },
{ LedId.Headset2, SteelSeriesLedId.ZoneTwo }
}; };
private const int VENDOR_ID = 0x1038; private const int VENDOR_ID = 0x1038;
//TODO DarthAffe 16.02.2019: Add devices //TODO DarthAffe 16.02.2019: Add devices
private static readonly DeviceDataList DEVICES = new DeviceDataList private static readonly DeviceDataList DEVICES = new()
{ {
//Mice //Mice
("Aerox 3", RGBDeviceType.Mouse, 0x1836, SteelSeriesDeviceType.ThreeZone, "default", @"Mice\Aerox3", MOUSE_THREE_ZONE), ("Aerox 3", RGBDeviceType.Mouse, 0x1836, SteelSeriesDeviceType.ThreeZone, MOUSE_THREE_ZONE),
("Aerox 3 Wireless", RGBDeviceType.Mouse, 0x183A, SteelSeriesDeviceType.ThreeZone, "default", @"Mice\Aerox3Wireless", MOUSE_THREE_ZONE), ("Aerox 3 Wireless", RGBDeviceType.Mouse, 0x183A, SteelSeriesDeviceType.ThreeZone, MOUSE_THREE_ZONE),
("Rival 100", RGBDeviceType.Mouse, 0x1702, SteelSeriesDeviceType.OneZone, "default", @"Mice\Rival100", MOUSE_ONE_ZONE), ("Rival 100", RGBDeviceType.Mouse, 0x1702, SteelSeriesDeviceType.OneZone, MOUSE_ONE_ZONE),
("Rival 105", RGBDeviceType.Mouse, 0x1814, SteelSeriesDeviceType.OneZone, "default", @"Mice\Rival105", MOUSE_ONE_ZONE), ("Rival 105", RGBDeviceType.Mouse, 0x1814, SteelSeriesDeviceType.OneZone, MOUSE_ONE_ZONE),
("Rival 106", RGBDeviceType.Mouse, 0x1816, SteelSeriesDeviceType.OneZone, "default", @"Mice\Rival106", MOUSE_ONE_ZONE), ("Rival 106", RGBDeviceType.Mouse, 0x1816, SteelSeriesDeviceType.OneZone, MOUSE_ONE_ZONE),
("Rival 110", RGBDeviceType.Mouse, 0x1729, SteelSeriesDeviceType.OneZone, "default", @"Mice\Rival110", MOUSE_ONE_ZONE), ("Rival 110", RGBDeviceType.Mouse, 0x1729, SteelSeriesDeviceType.OneZone, MOUSE_ONE_ZONE),
("Rival 150", RGBDeviceType.Mouse, 0x0472, SteelSeriesDeviceType.OneZone, "default", @"Mice\Rival150", MOUSE_ONE_ZONE), ("Rival 150", RGBDeviceType.Mouse, 0x0472, SteelSeriesDeviceType.OneZone, MOUSE_ONE_ZONE),
("Rival 300", RGBDeviceType.Mouse, 0x1710, SteelSeriesDeviceType.TwoZone, "default", @"Mice\Rival300", MOUSE_TWO_ZONE), ("Rival 300", RGBDeviceType.Mouse, 0x1710, SteelSeriesDeviceType.TwoZone, MOUSE_TWO_ZONE),
("Rival 310", RGBDeviceType.Mouse, 0x1720, SteelSeriesDeviceType.TwoZone, "default", @"Mice\Rival310", MOUSE_TWO_ZONE), ("Rival 310", RGBDeviceType.Mouse, 0x1720, SteelSeriesDeviceType.TwoZone, MOUSE_TWO_ZONE),
("Rival 500", RGBDeviceType.Mouse, 0x170E, SteelSeriesDeviceType.TwoZone, "default", @"Mice\Rival500", MOUSE_TWO_ZONE), ("Rival 500", RGBDeviceType.Mouse, 0x170E, SteelSeriesDeviceType.TwoZone, MOUSE_TWO_ZONE),
("Rival 600", RGBDeviceType.Mouse, 0x1724, SteelSeriesDeviceType.EightZone, "default", @"Mice\Rival600", MOUSE_EIGHT_ZONE), ("Rival 600", RGBDeviceType.Mouse, 0x1724, SteelSeriesDeviceType.EightZone, MOUSE_EIGHT_ZONE),
("Rival 700", RGBDeviceType.Mouse, 0x1700, SteelSeriesDeviceType.TwoZone, "default", @"Mice\Rival700", MOUSE_TWO_ZONE), ("Rival 700", RGBDeviceType.Mouse, 0x1700, SteelSeriesDeviceType.TwoZone, MOUSE_TWO_ZONE),
("Rival 3 (Old Firmware)", RGBDeviceType.Mouse, 0x1824, SteelSeriesDeviceType.ThreeZone, "default", @"Mice\Rival3", MOUSE_THREE_ZONE), ("Rival 3 (Old Firmware)", RGBDeviceType.Mouse, 0x1824, SteelSeriesDeviceType.ThreeZone, MOUSE_THREE_ZONE),
("Rival 3", RGBDeviceType.Mouse, 0x184C, SteelSeriesDeviceType.ThreeZone, "default", @"Mice\Rival3", MOUSE_THREE_ZONE), ("Rival 3", RGBDeviceType.Mouse, 0x184C, SteelSeriesDeviceType.ThreeZone, MOUSE_THREE_ZONE),
("Rival 3 Wireless", RGBDeviceType.Mouse, 0x1830, SteelSeriesDeviceType.ThreeZone, "default", @"Mice\Rival3Wireless", MOUSE_THREE_ZONE), ("Rival 3 Wireless", RGBDeviceType.Mouse, 0x1830, SteelSeriesDeviceType.ThreeZone, MOUSE_THREE_ZONE),
("Sensei Ten", RGBDeviceType.Mouse, 0x1832, SteelSeriesDeviceType.TwoZone, "default", @"Mice\SenseiTen", MOUSE_TWO_ZONE), ("Sensei Ten", RGBDeviceType.Mouse, 0x1832, SteelSeriesDeviceType.TwoZone, MOUSE_TWO_ZONE),
//Keyboards //Keyboards
("Apex 5", RGBDeviceType.Keyboard, 0x161C, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\5\UK", KEYBOARD_MAPPING_UK), ("Apex 5", RGBDeviceType.Keyboard, 0x161C, SteelSeriesDeviceType.PerKey, KEYBOARD_MAPPING_UK),
("Apex 7", RGBDeviceType.Keyboard, 0x1612, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\7\UK", KEYBOARD_MAPPING_UK), ("Apex 7", RGBDeviceType.Keyboard, 0x1612, SteelSeriesDeviceType.PerKey, KEYBOARD_MAPPING_UK),
("Apex 7 TKL", RGBDeviceType.Keyboard, 0x1618, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\7TKL\UK", KEYBOARD_TKL_MAPPING_UK), ("Apex 7 TKL", RGBDeviceType.Keyboard, 0x1618, SteelSeriesDeviceType.PerKey, KEYBOARD_TKL_MAPPING_UK),
("Apex M750", RGBDeviceType.Keyboard, 0x0616, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\M750\UK", KEYBOARD_MAPPING_UK), ("Apex M750", RGBDeviceType.Keyboard, 0x0616, SteelSeriesDeviceType.PerKey, KEYBOARD_MAPPING_UK),
("Apex M800", RGBDeviceType.Keyboard, 0x1600, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\M800\UK", KEYBOARD_MAPPING_UK), ("Apex M800", RGBDeviceType.Keyboard, 0x1600, SteelSeriesDeviceType.PerKey, KEYBOARD_MAPPING_UK),
("Apex Pro", RGBDeviceType.Keyboard, 0x1610, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\Pro\UK", KEYBOARD_MAPPING_UK), ("Apex Pro", RGBDeviceType.Keyboard, 0x1610, SteelSeriesDeviceType.PerKey, KEYBOARD_MAPPING_UK),
("Apex Pro TKL", RGBDeviceType.Keyboard, 0x1614, SteelSeriesDeviceType.PerKey, "UK", @"Keyboards\ProTKL\UK", KEYBOARD_TKL_MAPPING_UK), ("Apex Pro TKL", RGBDeviceType.Keyboard, 0x1614, SteelSeriesDeviceType.PerKey, KEYBOARD_TKL_MAPPING_UK),
//Headsets //Headsets
("Arctis 5", RGBDeviceType.Headset, 0x12AA, SteelSeriesDeviceType.TwoZone, "default", @"Headsets\Artis5", HEADSET_TWO_ZONE), ("Arctis 5", RGBDeviceType.Headset, 0x12AA, SteelSeriesDeviceType.TwoZone, HEADSET_TWO_ZONE),
("Arctis 5 Game", RGBDeviceType.Headset, 0x1250, SteelSeriesDeviceType.TwoZone, "default", @"Headsets\Artis5", HEADSET_TWO_ZONE), ("Arctis 5 Game", RGBDeviceType.Headset, 0x1250, SteelSeriesDeviceType.TwoZone, HEADSET_TWO_ZONE),
("Arctis 5 Game - Dota 2 edition", RGBDeviceType.Headset, 0x1251, SteelSeriesDeviceType.TwoZone, "default", @"Headsets\Artis5", HEADSET_TWO_ZONE), ("Arctis 5 Game - Dota 2 edition", RGBDeviceType.Headset, 0x1251, SteelSeriesDeviceType.TwoZone, HEADSET_TWO_ZONE),
("Arctis 5 Game - PUBG edition", RGBDeviceType.Headset, 0x12A8, SteelSeriesDeviceType.TwoZone, "default", @"Headsets\Artis5", HEADSET_TWO_ZONE), ("Arctis 5 Game - PUBG edition", RGBDeviceType.Headset, 0x12A8, SteelSeriesDeviceType.TwoZone, HEADSET_TWO_ZONE),
("Arctis Pro Game", RGBDeviceType.Headset, 0x1252, SteelSeriesDeviceType.TwoZone, "default", @"Headsets\Artis5", HEADSET_TWO_ZONE), ("Arctis Pro Game", RGBDeviceType.Headset, 0x1252, SteelSeriesDeviceType.TwoZone, HEADSET_TWO_ZONE),
}; };
#endregion #endregion
#region Properties & Fields #region Properties & Fields
public static DeviceDataList ConnectedDevices { get; } = new DeviceDataList(); public static DeviceDataList ConnectedDevices { get; } = new();
#endregion #endregion
@ -304,7 +304,7 @@ namespace RGB.NET.Devices.SteelSeries.HID
{ {
ConnectedDevices.Clear(); ConnectedDevices.Clear();
HashSet<int> ids = new HashSet<int>(DeviceList.Local.GetHidDevices(VENDOR_ID).Select(x => x.ProductID).Distinct()); HashSet<int> ids = new(DeviceList.Local.GetHidDevices(VENDOR_ID).Select(x => x.ProductID).Distinct());
DeviceDataList connectedDevices = DEVICES.Where(d => ids.Contains(d.id) && loadFilter.HasFlag(d.deviceType)).ToList(); DeviceDataList connectedDevices = DEVICES.Where(d => ids.Contains(d.id) && loadFilter.HasFlag(d.deviceType)).ToList();
List<SteelSeriesDeviceType> connectedDeviceTypes = connectedDevices.Select(d => d.steelSeriesDeviceType).ToList(); List<SteelSeriesDeviceType> connectedDeviceTypes = connectedDevices.Select(d => d.steelSeriesDeviceType).ToList();

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq;
using RGB.NET.Core; using RGB.NET.Core;
using RGB.NET.Devices.SteelSeries.API; using RGB.NET.Devices.SteelSeries.API;
using RGB.NET.Devices.SteelSeries.HID; using RGB.NET.Devices.SteelSeries.HID;
@ -15,7 +16,7 @@ namespace RGB.NET.Devices.SteelSeries
{ {
#region Properties & Fields #region Properties & Fields
private static SteelSeriesDeviceProvider _instance; private static SteelSeriesDeviceProvider? _instance;
/// <summary> /// <summary>
/// Gets the singleton <see cref="SteelSeriesDeviceProvider"/> instance. /// Gets the singleton <see cref="SteelSeriesDeviceProvider"/> instance.
/// </summary> /// </summary>
@ -28,13 +29,7 @@ namespace RGB.NET.Devices.SteelSeries
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
/// <summary> public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess => false;
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary> /// <summary>
/// The <see cref="SteelSeriesDeviceUpdateTrigger"/> used to trigger the updates for SteelSeries devices. /// The <see cref="SteelSeriesDeviceUpdateTrigger"/> used to trigger the updates for SteelSeries devices.
@ -68,7 +63,7 @@ namespace RGB.NET.Devices.SteelSeries
{ {
IsInitialized = false; IsInitialized = false;
UpdateTrigger?.Stop(); UpdateTrigger.Stop();
if (!SteelSeriesSDK.IsInitialized) if (!SteelSeriesSDK.IsInitialized)
SteelSeriesSDK.Initialize(); SteelSeriesSDK.Initialize();
@ -78,17 +73,18 @@ namespace RGB.NET.Devices.SteelSeries
try try
{ {
foreach ((string model, RGBDeviceType deviceType, int _, SteelSeriesDeviceType steelSeriesDeviceType, string imageLayout, string layoutPath, Dictionary<LedId, SteelSeriesLedId> ledMapping) in DeviceChecker.ConnectedDevices) foreach ((string model, RGBDeviceType deviceType, int _, SteelSeriesDeviceType steelSeriesDeviceType, Dictionary<LedId, SteelSeriesLedId> ledMapping) in DeviceChecker.ConnectedDevices)
{ {
ISteelSeriesRGBDevice device = new SteelSeriesRGBDevice(new SteelSeriesRGBDeviceInfo(deviceType, model, steelSeriesDeviceType, imageLayout, layoutPath)); ISteelSeriesRGBDevice device = new SteelSeriesRGBDevice(new SteelSeriesRGBDeviceInfo(deviceType, model, steelSeriesDeviceType));
SteelSeriesDeviceUpdateQueue updateQueue = new SteelSeriesDeviceUpdateQueue(UpdateTrigger, steelSeriesDeviceType.GetAPIName()); string apiName = steelSeriesDeviceType.GetAPIName() ?? throw new RGBDeviceException($"Missing API-name for device {model}");
SteelSeriesDeviceUpdateQueue updateQueue = new(UpdateTrigger, apiName);
device.Initialize(updateQueue, ledMapping); device.Initialize(updateQueue, ledMapping);
devices.Add(device); devices.Add(device);
} }
} }
catch { if (throwExceptions) throw; } catch { if (throwExceptions) throw; }
UpdateTrigger?.Start(); UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices); Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true; IsInitialized = true;

View File

@ -66,7 +66,7 @@ namespace RGB.NET.Devices.WS281X.Arduino
protected override object GetLedCustomData(LedId ledId) => (Channel, (int)ledId - (int)LedId.LedStripe1); protected override object GetLedCustomData(LedId ledId) => (Channel, (int)ledId - (int)LedId.LedStripe1);
/// <inheritdoc /> /// <inheritdoc />
protected override IEnumerable<Led> GetLedsToUpdate(bool flushLeds) => (flushLeds || LedMapping.Values.Any(x => x.IsDirty)) ? LedMapping.Values : null; protected override IEnumerable<Led> GetLedsToUpdate(bool flushLeds) => (flushLeds || LedMapping.Values.Any(x => x.IsDirty)) ? LedMapping.Values : Enumerable.Empty<Led>();
/// <inheritdoc /> /// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0)); protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0));

View File

@ -21,7 +21,7 @@ namespace RGB.NET.Devices.WS281X.Arduino
#region Properties & Fields #region Properties & Fields
private readonly Dictionary<int, byte[]> _dataBuffer = new Dictionary<int, byte[]>(); private readonly Dictionary<int, byte[]> _dataBuffer = new();
#endregion #endregion
@ -42,7 +42,7 @@ namespace RGB.NET.Devices.WS281X.Arduino
#region Methods #region Methods
/// <inheritdoc /> /// <inheritdoc />
protected override void OnStartup(object sender, CustomUpdateData customData) protected override void OnStartup(object? sender, CustomUpdateData customData)
{ {
base.OnStartup(sender, customData); base.OnStartup(sender, customData);
@ -56,7 +56,7 @@ namespace RGB.NET.Devices.WS281X.Arduino
.GroupBy(x => x.Item1.channel)) .GroupBy(x => x.Item1.channel))
{ {
int channel = channelData.Key; int channel = channelData.Key;
if (!_dataBuffer.TryGetValue(channel, out byte[] dataBuffer) || (dataBuffer.Length != ((dataSet.Count * 3) + 1))) if (!_dataBuffer.TryGetValue(channel, out byte[]? dataBuffer) || (dataBuffer.Length != ((dataSet.Count * 3) + 1)))
_dataBuffer[channel] = dataBuffer = new byte[(dataSet.Count * 3) + 1]; _dataBuffer[channel] = dataBuffer = new byte[(dataSet.Count * 3) + 1];
dataBuffer[0] = (byte)((channel << 4) | UPDATE_COMMAND[0]); dataBuffer[0] = (byte)((channel << 4) | UPDATE_COMMAND[0]);

View File

@ -24,7 +24,7 @@ namespace RGB.NET.Devices.WS281X.Arduino
/// <summary> /// <summary>
/// Gets the name of the serial-port to connect to. /// Gets the name of the serial-port to connect to.
/// </summary> /// </summary>
public string Port => SerialConnection?.Port; public string Port => SerialConnection.Port;
/// <summary> /// <summary>
/// Gets the baud-rate used by the serial-connection. /// Gets the baud-rate used by the serial-connection.
@ -35,7 +35,7 @@ namespace RGB.NET.Devices.WS281X.Arduino
/// Gets or sets the name used by this device. /// Gets or sets the name used by this device.
/// This allows to use {0} as a placeholder for a incrementing number if multiple devices are created. /// This allows to use {0} as a placeholder for a incrementing number if multiple devices are created.
/// </summary> /// </summary>
public string Name { get; set; } public string? Name { get; set; }
#endregion #endregion
@ -67,13 +67,13 @@ namespace RGB.NET.Devices.WS281X.Arduino
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<IRGBDevice> CreateDevices(IDeviceUpdateTrigger updateTrigger) public IEnumerable<IRGBDevice> CreateDevices(IDeviceUpdateTrigger updateTrigger)
{ {
ArduinoWS2812USBUpdateQueue queue = new ArduinoWS2812USBUpdateQueue(updateTrigger, SerialConnection); ArduinoWS2812USBUpdateQueue queue = new(updateTrigger, SerialConnection);
IEnumerable<(int channel, int ledCount)> channels = queue.GetChannels(); IEnumerable<(int channel, int ledCount)> channels = queue.GetChannels();
int counter = 0; int counter = 0;
foreach ((int channel, int ledCount) in channels) foreach ((int channel, int ledCount) in channels)
{ {
string name = string.Format(Name ?? $"Arduino WS2812 USB ({Port}) [{{0}}]", ++counter); string name = string.Format(Name ?? $"Arduino WS2812 USB ({Port}) [{{0}}]", ++counter);
ArduinoWS2812USBDevice device = new ArduinoWS2812USBDevice(new ArduinoWS2812USBDeviceInfo(name), queue, channel); ArduinoWS2812USBDevice device = new(new ArduinoWS2812USBDeviceInfo(name), queue, channel);
device.Initialize(ledCount); device.Initialize(ledCount);
yield return device; yield return device;
} }

View File

@ -54,7 +54,7 @@ namespace RGB.NET.Devices.WS281X.Bitwizard
if (Size == Size.Invalid) if (Size == Size.Invalid)
{ {
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle)); Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y); Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
} }
} }

View File

@ -28,7 +28,7 @@ namespace RGB.NET.Devices.WS281X.Bitwizard
#region Methods #region Methods
/// <inheritdoc /> /// <inheritdoc />
protected override void OnStartup(object sender, CustomUpdateData customData) protected override void OnStartup(object? sender, CustomUpdateData customData)
{ {
base.OnStartup(sender, customData); base.OnStartup(sender, customData);
@ -38,8 +38,8 @@ namespace RGB.NET.Devices.WS281X.Bitwizard
/// <inheritdoc /> /// <inheritdoc />
protected override IEnumerable<string> GetCommands(Dictionary<object, Color> dataSet) protected override IEnumerable<string> GetCommands(Dictionary<object, Color> dataSet)
{ {
foreach (KeyValuePair<object, Color> data in dataSet) foreach ((object key, Color value) in dataSet)
yield return $"pix {(int)data.Key} {data.Value.AsRGBHexString(false)}"; yield return $"pix {(int)key} {value.AsRGBHexString(false)}";
} }
#endregion #endregion

View File

@ -24,17 +24,17 @@ namespace RGB.NET.Devices.WS281X.Bitwizard
/// <summary> /// <summary>
/// Gets the name of the serial-port to connect to. /// Gets the name of the serial-port to connect to.
/// </summary> /// </summary>
public string Port => SerialConnection?.Port; public string Port => SerialConnection.Port;
/// <summary> /// <summary>
/// Gets the baud-rate used by the serial-connection. /// Gets the baud-rate used by the serial-connection.
/// </summary> /// </summary>
public int BaudRate => SerialConnection?.BaudRate ?? 0; public int BaudRate => SerialConnection.BaudRate;
/// <summary> /// <summary>
/// Gets or sets the name used by this device. /// Gets or sets the name used by this device.
/// </summary> /// </summary>
public string Name { get; set; } public string? Name { get; set; }
/// <summary> /// <summary>
/// Gets or sets the pin sed to control the leds. /// Gets or sets the pin sed to control the leds.
@ -82,10 +82,10 @@ namespace RGB.NET.Devices.WS281X.Bitwizard
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<IRGBDevice> CreateDevices(IDeviceUpdateTrigger updateTrigger) public IEnumerable<IRGBDevice> CreateDevices(IDeviceUpdateTrigger updateTrigger)
{ {
BitwizardWS2812USBUpdateQueue queue = new BitwizardWS2812USBUpdateQueue(updateTrigger, SerialConnection); BitwizardWS2812USBUpdateQueue queue = new(updateTrigger, SerialConnection);
string name = Name ?? $"Bitwizard WS2812 USB ({Port})"; string name = Name ?? $"Bitwizard WS2812 USB ({Port})";
int ledOffset = Pin * MaxStripLength; int ledOffset = Pin * MaxStripLength;
BitwizardWS2812USBDevice device = new BitwizardWS2812USBDevice(new BitwizardWS2812USBDeviceInfo(name), queue, ledOffset); BitwizardWS2812USBDevice device = new(new BitwizardWS2812USBDeviceInfo(name), queue, ledOffset);
device.Initialize(StripLength); device.Initialize(StripLength);
yield return device; yield return device;
} }

Some files were not shown because too many files have changed in this diff Show More