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

Prepared Msi SDK-integration

This commit is contained in:
Darth Affe 2017-11-11 21:49:51 +01:00
parent 61c4a06241
commit 22617845b0
17 changed files with 1021 additions and 1 deletions

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>RGB.NET.Devices.Msi</id>
<title>RGB.NET.Devices.Msi</title>
<version>1.0.0.0</version>
<authors>Darth Affe</authors>
<owners>Darth Affe</owners>
<projectUrl>https://github.com/DarthAffe/RGB.NET</projectUrl>
<licenseUrl>https://raw.githubusercontent.com/DarthAffe/RGB.NET/master/LICENSE</licenseUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<description>Msi-Device-Implementations of RGB.NET</description>
<releaseNotes></releaseNotes>
<summary>Msi-Device-Implementations of RGB.NET, a C# (.NET) library for accessing various RGB-peripherals</summary>
<copyright>Copyright © Wyrez 2017</copyright>
<language>en-US</language>
<dependencies>
<dependency id="RGB.NET.Core" version="1.0" />
<dependency id="System.ValueTuple" version="4.3.1" />
</dependencies>
</metadata>
<files>
<file src="..\bin\RGB.NET.Devices.Msi.dll" target="lib\net45\RGB.NET.Devices.Msi.dll" />
<file src="..\bin\RGB.NET.Devices.Msi.pdb" target="lib\net45\RGB.NET.Devices.Msi.pdb" />
<file src="..\bin\RGB.NET.Devices.Msi.xml" target="lib\net45\RGB.NET.Devices.Msi.xml" />
<file src="..\RGB.NET.Devices.Msi\**\*.cs" target="src" exclude="..\RGB.NET.Devices.Msi\obj\**\*.*" />
<file src="..\RGB.NET.Devices.Msi\Images\**\*.*" target="build\net45\resources\Images\" />
<file src="..\RGB.NET.Devices.Msi\Layouts\**\*.*" target="build\net45\resources\Layouts\" />
<file src="..\RGB.NET.Devices.Msi\libs\**\*.*" target="build\net45\libs\" />
<file src="..\RGB.NET.Devices.Msi\targets\*.targets" target="build\net45\" />
</files>
</package>

View File

@ -0,0 +1,16 @@
// ReSharper disable InconsistentNaming
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace RGB.NET.Devices.Msi
{
/// <summary>
/// Contains list of all LEDs available for all Msi devices.
/// </summary>
public enum MsiLedIds
{
Invalid = -1,
//TODO DarthAffe 11.11.2017: Create useful Ids for all devices
}
}

View File

@ -0,0 +1,44 @@
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
using System;
namespace RGB.NET.Devices.Msi.Exceptions
{
/// <inheritdoc />
/// <summary>
/// Represents an exception thrown by the MysticLight-SDK.
/// </summary>
public class MysticLightException : ApplicationException
{
#region Properties & Fields
/// <summary>
/// Gets the raw error code provided by the SDK.
/// </summary>
public int ErrorCode { get; }
/// <summary>
/// Gets the text-description the <see cref="ErrorCode"/> resolves too.
/// </summary>
public string Description { get; }
#endregion
#region Constructors
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:RGB.NET.Devices.Msi.MysticLightException" /> class.
/// </summary>
/// <param name="errorCode">The raw error code provided by the SDK.</param>
/// <param name="description">The text-description of the error.</param>
public MysticLightException(int errorCode, string description)
{
this.ErrorCode = errorCode;
this.Description = description;
}
#endregion
}
}

View File

@ -0,0 +1,111 @@
using System.Diagnostics;
using RGB.NET.Core;
namespace RGB.NET.Devices.Msi
{
/// <inheritdoc />
/// <summary>
/// Represents a Id of a <see cref="T:RGB.NET.Core.Led" /> on a <see cref="T:RGB.NET.Devices.Msi.MsiRGBDevice" />.
/// </summary>
[DebuggerDisplay("{" + nameof(LedId) + "}")]
public class MsiLedId : ILedId
{
#region Properties & Fields
internal readonly MsiLedIds LedId;
internal readonly int Index;
/// <inheritdoc />
public IRGBDevice Device { get; }
/// <inheritdoc />
public bool IsValid => LedId != MsiLedIds.Invalid;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MsiLedId"/> class.
/// </summary>
/// <param name="device">The <see cref="IRGBDevice"/> the <see cref="ILedId"/> belongs to.</param>
/// <param name="ledId">The <see cref="MsiLedId"/> of the represented <see cref="Led"/>.</param>
public MsiLedId(IRGBDevice device, MsiLedIds ledId)
{
this.Device = device;
this.LedId = ledId;
}
/// <summary>
/// Initializes a new instance of the <see cref="MsiLedId"/> class.
/// </summary>
/// <param name="device">The <see cref="IRGBDevice"/> the <see cref="ILedId"/> belongs to.</param>
/// <param name="ledId">The <see cref="MsiLedId"/> of the represented <see cref="Led"/>.</param>
/// <param name="index">The index in the mapping array of the device.</param>
public MsiLedId(IRGBDevice device, MsiLedIds ledId, int index)
{
this.Device = device;
this.LedId = ledId;
this.Index = index;
}
#endregion
#region Methods
/// <summary>
/// Converts the Id of this <see cref="MsiLedId"/> to a human-readable string.
/// </summary>
/// <returns>A string that contains the Id of this <see cref="MsiLedId"/>. For example "Enter".</returns>
public override string ToString() => LedId.ToString();
/// <summary>
/// Tests whether the specified object is a <see cref="MsiLedId" /> and is equivalent to this <see cref="MsiLedId" />.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="MsiLedId" /> equivalent to this <see cref="MsiLedId" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
MsiLedId compareLedId = obj as MsiLedId;
if (ReferenceEquals(compareLedId, null))
return false;
if (ReferenceEquals(this, compareLedId))
return true;
if (GetType() != compareLedId.GetType())
return false;
return compareLedId.LedId == LedId;
}
/// <summary>
/// Returns a hash code for this <see cref="MsiLedId" />.
/// </summary>
/// <returns>An integer value that specifies the hash code for this <see cref="MsiLedId" />.</returns>
public override int GetHashCode() => LedId.GetHashCode();
#endregion
#region Operators
/// <summary>
/// Returns a value that indicates whether two specified <see cref="MsiLedId" /> are equal.
/// </summary>
/// <param name="ledId1">The first <see cref="MsiLedId" /> to compare.</param>
/// <param name="ledId2">The second <see cref="MsiLedId" /> to compare.</param>
/// <returns><c>true</c> if <paramref name="ledId1" /> and <paramref name="ledId2" /> are equal; otherwise, <c>false</c>.</returns>
public static bool operator ==(MsiLedId ledId1, MsiLedId ledId2) => ReferenceEquals(ledId1, null) ? ReferenceEquals(ledId2, null) : ledId1.Equals(ledId2);
/// <summary>
/// Returns a value that indicates whether two specified <see cref="MsiLedId" /> are equal.
/// </summary>
/// <param name="ledId1">The first <see cref="MsiLedId" /> to compare.</param>
/// <param name="ledId2">The second <see cref="MsiLedId" /> to compare.</param>
/// <returns><c>true</c> if <paramref name="ledId1" /> and <paramref name="ledId2" /> are not equal; otherwise, <c>false</c>.</returns>
public static bool operator !=(MsiLedId ledId1, MsiLedId ledId2) => !(ledId1 == ledId2);
#endregion
}
}

View File

@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using RGB.NET.Core;
using RGB.NET.Core.Layout;
using RGB.NET.Devices.Msi.Native;
namespace RGB.NET.Devices.Msi
{
/// <inheritdoc />
/// <summary>
/// Represents a generic Msi-device. (keyboard, mouse, headset, mousepad).
/// </summary>
public abstract class MsiRGBDevice : AbstractRGBDevice
{
#region Properties & Fields
/// <inheritdoc />
/// <summary>
/// Gets information about the <see cref="T:RGB.NET.Devices.Msi.MsiRGBDevice" />.
/// </summary>
public override IRGBDeviceInfo DeviceInfo { get; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MsiRGBDevice"/> class.
/// </summary>
/// <param name="info">The generic information provided by Msi for the device.</param>
protected MsiRGBDevice(IRGBDeviceInfo info)
{
this.DeviceInfo = info;
}
#endregion
#region Methods
/// <summary>
/// Initializes the device.
/// </summary>
internal void Initialize()
{
InitializeLayout();
if (InternalSize == null)
{
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
InternalSize = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
}
}
/// <summary>
/// Initializes the <see cref="Led"/> and <see cref="Size"/> of the device.
/// </summary>
protected abstract void InitializeLayout();
/// <summary>
/// Applies the given layout.
/// </summary>
/// <param name="layoutPath">The file containing the layout.</param>
/// <param name="imageLayout">The name of the layout used to get the images of the leds.</param>
/// <param name="imageBasePath">The path images for this device are collected in.</param>
protected void ApplyLayoutFromFile(string layoutPath, string imageLayout, string imageBasePath)
{
DeviceLayout layout = DeviceLayout.Load(layoutPath);
if (layout != null)
{
LedImageLayout ledImageLayout = layout.LedImageLayouts.FirstOrDefault(x => string.Equals(x.Layout, imageLayout, StringComparison.OrdinalIgnoreCase));
InternalSize = new Size(layout.Width, layout.Height);
if (layout.Leds != null)
foreach (LedLayout layoutLed in layout.Leds)
{
if (Enum.TryParse(layoutLed.Id, true, out MsiLedIds ledId))
{
if (LedMapping.TryGetValue(new MsiLedId(this, ledId), out Led led))
{
led.LedRectangle.Location.X = layoutLed.X;
led.LedRectangle.Location.Y = layoutLed.Y;
led.LedRectangle.Size.Width = layoutLed.Width;
led.LedRectangle.Size.Height = layoutLed.Height;
led.Shape = layoutLed.Shape;
led.ShapeData = layoutLed.ShapeData;
LedImage image = ledImageLayout?.LedImages.FirstOrDefault(x => x.Id == layoutLed.Id);
led.Image = (!string.IsNullOrEmpty(image?.Image))
? new Uri(Path.Combine(imageBasePath, image.Image), UriKind.Absolute)
: new Uri(Path.Combine(imageBasePath, "Missing.png"), UriKind.Absolute);
}
}
}
}
}
/// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate)
{
List<Led> leds = ledsToUpdate.Where(x => x.Color.A > 0).ToList();
if (leds.Count > 0)
{
string deviceType = ((MsiRGBDeviceInfo)DeviceInfo).MsiDeviceType;
foreach (Led led in leds)
_MsiSDK.SetLedColor(deviceType, ((MsiLedId)led.Id).Index, led.Color.R, led.Color.G, led.Color.B);
}
}
#endregion
}
}

View File

@ -0,0 +1,52 @@
using System;
using RGB.NET.Core;
namespace RGB.NET.Devices.Msi
{
/// <inheritdoc />
/// <summary>
/// Represents a generic information for a Corsair-<see cref="T:RGB.NET.Core.IRGBDevice" />.
/// </summary>
public class MsiRGBDeviceInfo : IRGBDeviceInfo
{
#region Properties & Fields
/// <inheritdoc />
public RGBDeviceType DeviceType { get; }
public string MsiDeviceType { get; }
/// <inheritdoc />
public string Manufacturer { get; }
/// <inheritdoc />
public string Model { get; }
/// <inheritdoc />
public Uri Image { get; protected set; }
/// <inheritdoc />
public RGBDeviceLighting Lighting => RGBDeviceLighting.Key;
#endregion
#region Constructors
/// <summary>
/// Internal constructor of managed <see cref="MsiRGBDeviceInfo"/>.
/// </summary>
/// <param name="deviceType">The type of the <see cref="IRGBDevice"/>.</param>
/// <param name="msiDeviceType">The internal type 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>
internal MsiRGBDeviceInfo(RGBDeviceType deviceType, string msiDeviceType, string manufacturer = "Msi", string model = "Generic Msi-Device")
{
this.DeviceType = deviceType;
this.MsiDeviceType = msiDeviceType;
this.Manufacturer = manufacturer;
this.Model = model;
}
#endregion
}
}

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
<xsd:element name="Device">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Name" type="xsd:string" />
<xsd:element name="Description" type="xsd:string" />
<xsd:element name="Type" type="xsd:string" />
<xsd:element name="Lighting" type="xsd:string" />
<xsd:element name="Vendor" type="xsd:string" />
<xsd:element name="Model" type="xsd:string" />
<xsd:element name="Shape" type="xsd:string" />
<xsd:element name="Width" type="xsd:double" />
<xsd:element name="Height" type="xsd:double" />
<xsd:element name="LedUnitWidth" type="xsd:double" />
<xsd:element name="LedUnitHeight" type="xsd:double" />
<xsd:element name="Leds">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="Led">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Shape" type="xsd:string" />
<xsd:element name="X" type="xsd:string" />
<xsd:element name="Y" type="xsd:string" />
<xsd:element name="Width" type="xsd:string" />
<xsd:element name="Height" type="xsd:string" />
</xsd:sequence>
<xsd:attribute name="Id" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="LedImageLayouts">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="LedImageLayout">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="LedImages">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="LedImage">
<xsd:complexType>
<xsd:attribute name="Id" type="xsd:string" use="required" />
<xsd:attribute name="Image" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="Layout" type="xsd:string" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xs:schema>

View File

@ -0,0 +1,131 @@
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedMember.Global
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using RGB.NET.Core;
using RGB.NET.Devices.Msi.Exceptions;
using RGB.NET.Devices.Msi.Native;
namespace RGB.NET.Devices.Msi
{
/// <inheritdoc />
/// <summary>
/// Represents a device provider responsible for Cooler Master devices.
/// </summary>
public class MsiDeviceProvider : IRGBDeviceProvider
{
#region Properties & Fields
private static MsiDeviceProvider _instance;
/// <summary>
/// Gets the singleton <see cref="MsiDeviceProvider"/> instance.
/// </summary>
public static MsiDeviceProvider Instance => _instance ?? new MsiDeviceProvider();
/// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used.
/// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/MysticLight_SDK.dll" };
/// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used.
/// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/MysticLight_SDK.dll" };
/// <inheritdoc />
/// <summary>
/// Indicates if the SDK is initialized and ready to use.
/// </summary>
public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _MsiSDK.LoadedArchitecture;
/// <inheritdoc />
/// <summary>
/// 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;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MsiDeviceProvider"/> class.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if this constructor is called even if there is already an instance of this class.</exception>
public MsiDeviceProvider()
{
if (_instance != null) throw new InvalidOperationException($"There can be only one instanc of type {nameof(MsiDeviceProvider)}");
_instance = this;
}
#endregion
#region Methods
/// <inheritdoc />
public bool Initialize(bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
{
IsInitialized = false;
try
{
_MsiSDK.Reload();
IList<IRGBDevice> devices = new List<IRGBDevice>();
int errorCode;
if ((errorCode = _MsiSDK.Initialize()) != 0)
ThrowMsiError(errorCode);
if ((errorCode = _MsiSDK.GetDeviceInfo(out string[] deviceTypes, out int[] ledCounts)) != 0)
ThrowMsiError(errorCode);
for (int i = 0; i < deviceTypes.Length; i++)
{
//TODO DarthAffe 11.11.2017: What is this deviceType? Find someone to try that out
}
Devices = new ReadOnlyCollection<IRGBDevice>(devices);
}
catch
{
if (throwExceptions)
throw;
else
return false;
}
IsInitialized = true;
return true;
}
private void ThrowMsiError(int errorCode) => throw new MysticLightException(errorCode, _MsiSDK.GetErrorMessage(errorCode));
/// <inheritdoc />
public void ResetDevices()
{
//TODO DarthAffe 11.11.2017: Implement
}
#endregion
}
}

View File

@ -0,0 +1,175 @@
// ReSharper disable UnusedMethodReturnValue.Global
// ReSharper disable UnusedMember.Global
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using RGB.NET.Core.Exceptions;
namespace RGB.NET.Devices.Msi.Native
{
// ReSharper disable once InconsistentNaming
internal static class _MsiSDK
{
#region Libary Management
private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary>
/// Reloads the SDK.
/// </summary>
internal static void Reload()
{
UnloadMsiSDK();
LoadMsiSDK();
}
private static void LoadMsiSDK()
{
if (_dllHandle != IntPtr.Zero) return;
// HACK: Load library at runtime to support both, x86 and x64 with one managed dll
List<string> possiblePathList = Environment.Is64BitProcess ? MsiDeviceProvider.PossibleX64NativePaths : MsiDeviceProvider.PossibleX86NativePaths;
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))}'");
SetDllDirectory(Path.GetDirectoryName(Path.GetFullPath(dllPath)));
_dllHandle = LoadLibrary(dllPath);
_initializePointer = (InitializePointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_Initialize"), typeof(InitializePointer));
_getDeviceInfoPointer = (GetDeviceInfoPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetDeviceInfo"), typeof(GetDeviceInfoPointer));
_getLedInfoPointer = (GetLedInfoPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedInfo"), typeof(GetLedInfoPointer));
_getLedColorPointer = (GetLedColorPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedColor"), typeof(GetLedColorPointer));
_getLedStylePointer = (GetLedStylePointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedStyle"), typeof(GetLedStylePointer));
_getLedMaxBrightPointer = (GetLedMaxBrightPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedMaxBright"), typeof(GetLedMaxBrightPointer));
_getLedBrightPointer = (GetLedBrightPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedBright"), typeof(GetLedBrightPointer));
_getLedMaxSpeedPointer = (GetLedMaxSpeedPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedMaxSpeed"), typeof(GetLedMaxSpeedPointer));
_getLedSpeedPointer = (GetLedSpeedPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetLedSpeed"), typeof(GetLedSpeedPointer));
_setLedColorPointer = (SetLedColorPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_SetLedColor"), typeof(SetLedColorPointer));
_setLedStylePointer = (SetLedStylePointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_SetLedStyle"), typeof(SetLedStylePointer));
_setLedBrightPointer = (SetLedBrightPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_SetLedBright"), typeof(SetLedBrightPointer));
_setLedSpeedPointer = (SetLedSpeedPointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_SetLedSpeed"), typeof(SetLedSpeedPointer));
_getErrorMessagePointer = (GetErrorMessagePointer)Marshal.GetDelegateForFunctionPointer(GetProcAddress(_dllHandle, "MLAPI_GetErrorMessage"), typeof(GetErrorMessagePointer));
}
private static void UnloadMsiSDK()
{
if (_dllHandle == IntPtr.Zero) return;
// ReSharper disable once EmptyEmbeddedStatement - DarthAffe 07.10.2017: We might need to reduce the internal reference counter more than once to set the library free
while (FreeLibrary(_dllHandle)) ;
_dllHandle = IntPtr.Zero;
}
[DllImport("kernel32.dll")]
private static extern bool SetDllDirectory(string lpPathName);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr dllHandle);
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr dllHandle, string name);
#endregion
#region SDK-METHODS
#region Pointers
private static InitializePointer _initializePointer;
private static GetDeviceInfoPointer _getDeviceInfoPointer;
private static GetLedInfoPointer _getLedInfoPointer;
private static GetLedColorPointer _getLedColorPointer;
private static GetLedStylePointer _getLedStylePointer;
private static GetLedMaxBrightPointer _getLedMaxBrightPointer;
private static GetLedBrightPointer _getLedBrightPointer;
private static GetLedMaxSpeedPointer _getLedMaxSpeedPointer;
private static GetLedSpeedPointer _getLedSpeedPointer;
private static SetLedColorPointer _setLedColorPointer;
private static SetLedStylePointer _setLedStylePointer;
private static SetLedBrightPointer _setLedBrightPointer;
private static SetLedSpeedPointer _setLedSpeedPointer;
private static GetErrorMessagePointer _getErrorMessagePointer;
#endregion
#region Delegates
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int InitializePointer();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetDeviceInfoPointer(out string[] pDevType, out int[] pLedCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedInfoPointer(string type, int index, out string pName, out string[] pLedStyles);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedColorPointer(string type, int index, out int r, out int g, out int b);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedStylePointer(string type, int index, out int style);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedMaxBrightPointer(string type, int index, out int maxLevel);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedBrightPointer(string type, int index, out int currentLevel);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedMaxSpeedPointer(string type, int index, out int maxSpeed);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetLedSpeedPointer(string type, int index, out int currentSpeed);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int SetLedColorPointer(string type, int index, int r, int g, int b);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int SetLedStylePointer(string type, int index, string style);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int SetLedBrightPointer(string type, int index, int level);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int SetLedSpeedPointer(string type, int index, int speed);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int GetErrorMessagePointer(int errorCode, out string pDesc);
#endregion
internal static int Initialize() => _initializePointer();
internal static int GetDeviceInfo(out string[] pDevType, out int[] pLedCount) => _getDeviceInfoPointer(out pDevType, out pLedCount);
internal static int GetLedInfo(string type, int index, out string pName, out string[] pLedStyles) => _getLedInfoPointer(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 GetLedStyle(string type, int index, out int style) => _getLedStylePointer(type, index, out style);
internal static int GetLedMaxBright(string type, int index, out int maxLevel) => _getLedMaxBrightPointer(type, index, out maxLevel);
internal static int GetLedBright(string type, int index, out int currentLevel) => _getLedBrightPointer(type, index, out currentLevel);
internal static int GetLedMaxSpeed(string type, int index, out int maxSpeed) => _getLedMaxSpeedPointer(type, index, out maxSpeed);
internal static int GetLedSpeed(string type, int index, out int currentSpeed) => _getLedSpeedPointer(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 SetLedStyle(string type, int index, string style) => _setLedStylePointer(type, index, style);
internal static int SetLedBright(string type, int index, int level) => _setLedBrightPointer(type, index, level);
internal static int SetLedSpeed(string type, int index, int speed) => _setLedSpeedPointer(type, index, speed);
internal static string GetErrorMessage(int errorCode)
{
_getErrorMessagePointer(errorCode, out string description);
return description;
}
#endregion
}
}

View File

@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RGB.NET.Devices.Msi")]
[assembly: AssemblyDescription("Msi-Device-Implementations of RGB.NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Wyrez")]
[assembly: AssemblyProduct("RGB.NET.Devices.Msi")]
[assembly: AssemblyCopyright("Copyright © Wyrez 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dda8c4c2-8abf-4fa0-9af9-c47ad0bfe47d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RGB.NET.Devices.Msi</RootNamespace>
<AssemblyName>RGB.NET.Devices.Msi</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>..\bin\RGB.NET.Devices.Msi.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>..\bin\RGB.NET.Devices.Msi.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.ValueTuple, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Enum\MsiLedIds.cs" />
<Compile Include="Exceptions\MysticLightException.cs" />
<Compile Include="Generic\MsiLedId.cs" />
<Compile Include="Generic\MsiRGBDevice.cs" />
<Compile Include="Generic\MsiRGBDeviceInfo.cs" />
<Compile Include="MsiDeviceProvider.cs" />
<Compile Include="Native\_MsiSDK.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Layouts\DeviceLayout.xsd">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
<None Include="targets\RGB.NET.Devices.Msi.targets" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RGB.NET.Core\RGB.NET.Core.csproj">
<Project>{5a4f9a75-75fe-47cd-90e5-914d5b20d232}</Project>
<Name>RGB.NET.Core</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="Images\Msi\" />
<Folder Include="Layouts\Msi\" />
</ItemGroup>
<ItemGroup>
<Content Include="libs\x64\MysticLight_SDK.dll" />
<Content Include="libs\x86\MysticLight_SDK.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enum/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=generic/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.ValueTuple" version="4.4.0" targetFramework="net45" />
</packages>

View File

@ -0,0 +1,150 @@
<!--
* Build targets hacked from SQLite (thanks!)
* System.Data.SQLite.Core.targets -
-->
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!--
******************************************************************************
** Build Items **
******************************************************************************
-->
<ItemGroup>
<MsiSDKFiles Condition="'$(MSBuildThisFileDirectory)' != '' And
HasTrailingSlash('$(MSBuildThisFileDirectory)')"
Include="$(MSBuildThisFileDirectory)libs\**\*.dll;$(MSBuildThisFileDirectory)resources\**\*.*" />
<AdditionalPublishFilex86 Include="$(MSBuildThisFileDirectory)libs\x86\*.dll">
<Visible>False</Visible>
</AdditionalPublishFilex86>
<AdditionalPublishFilex64 Include="$(MSBuildThisFileDirectory)libs\x64\*.dll">
<Visible>False</Visible>
</AdditionalPublishFilex64>
</ItemGroup>
<!--
******************************************************************************
** Content Items **
******************************************************************************
-->
<ItemGroup Condition="'$(ContentMsiSDKFiles)' != '' And
'$(ContentMsiSDKFiles)' != 'false' And
'@(MsiSDKFiles)' != ''">
<Content Include="@(MsiSDKFiles)">
<Link>%(RecursiveDir)%(FileName)%(Extension)</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<!--
******************************************************************************
** Build Targets* **
******************************************************************************
-->
<Target Name="CopyMsiSDKFiles"
Condition="'$(CopyMsiSDKFiles)' != 'false' And
'$(OutDir)' != '' And
HasTrailingSlash('$(OutDir)') And
Exists('$(OutDir)')"
Inputs="@(MsiSDKFiles)"
Outputs="@(MsiSDKFiles -> '$(OutDir)%(RecursiveDir)%(Filename)%(Extension)')">
<!--
NOTE: Copy "MythicLight_SDK.dll" and all related files, for every
architecture that we support, to the build output directory.
-->
<Message Text="Copying SDK files..." Importance="high" />
<Copy SourceFiles="@(MsiSDKFiles)"
DestinationFiles="@(MsiSDKFiles -> '$(OutDir)%(RecursiveDir)%(Filename)%(Extension)')" />
</Target>
<!--
******************************************************************************
-->
<Target Name="CleanMsiSDKFiles"
Condition="'$(CleanMsiSDKFiles)' != 'false' And
'$(OutDir)' != '' And
HasTrailingSlash('$(OutDir)') And
Exists('$(OutDir)')">
<!--
NOTE: Delete "MsiSDK*.dll" and all related files, for every
architecture that we support, from the build output directory.
-->
<Message Text="this file $(MSBuildThisFileDirectory)" Importance="high"/>
<Message Text="Cleaning SDK files..." Importance="high" />
<Delete Files="@(MsiSDKFiles -> '$(OutDir)%(RecursiveDir)%(Filename)%(Extension)')" />
</Target>
<!--
******************************************************************************
-->
<Target Name="CollectMsiSDKFiles"
Condition="'$(CollectMsiSDKFiles)' != 'false'">
<Message Text="Collecting SDK files..." Importance="high" />
<ItemGroup>
<FilesForPackagingFromProject Include="@(MsiSDKFiles)">
<DestinationRelativePath>bin\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
</FilesForPackagingFromProject>
</ItemGroup>
</Target>
<!--
******************************************************************************
-->
<Target Name="BeforePublish">
<Touch Files="@(IntermediateAssembly)" />
</Target>
<Target Name="BeforeBuild">
<CreateItem Include="@(AdditionalPublishFilex86)" AdditionalMetadata="TargetPath=x86\%(FileName)%(Extension);IsDataFile=false">
<Output TaskParameter="Include" ItemName="_DeploymentManifestFiles" />
</CreateItem>
<CreateItem Include="@(AdditionalPublishFilex64)" AdditionalMetadata="TargetPath=x64\%(FileName)%(Extension);IsDataFile=false">
<Output TaskParameter="Include" ItemName="_DeploymentManifestFiles" />
</CreateItem>
</Target>
<!--
******************************************************************************
** Build Properties **
******************************************************************************
-->
<PropertyGroup>
<PostBuildEventDependsOn>
$(PostBuildEventDependsOn);
CopyMsiSDKFiles;
</PostBuildEventDependsOn>
<BuildDependsOn>
$(BuildDependsOn);
CopyMsiSDKFiles;
</BuildDependsOn>
<CleanDependsOn>
$(CleanDependsOn);
CleanMsiSDKFiles;
</CleanDependsOn>
</PropertyGroup>
<!--
******************************************************************************
** Publish Properties for Visual Studio 201x **
******************************************************************************
-->
<PropertyGroup Condition="'$(VisualStudioVersion)' == '' Or
'$(VisualStudioVersion)' == '10.0' Or
'$(VisualStudioVersion)' == '11.0' Or
'$(VisualStudioVersion)' == '12.0'">
<PipelineCollectFilesPhaseDependsOn>
CollectMsiSDKFiles;
$(PipelineCollectFilesPhaseDependsOn);
</PipelineCollectFilesPhaseDependsOn>
</PropertyGroup>
</Project>

View File

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.16
VisualStudioVersion = 15.0.27004.2008
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RGB.NET.Core", "RGB.NET.Core\RGB.NET.Core.csproj", "{5A4F9A75-75FE-47CD-90E5-914D5B20D232}"
EndProject
@ -32,6 +32,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{06416566
NuGet\RGB.NET.Devices.CoolerMaster.nuspec = NuGet\RGB.NET.Devices.CoolerMaster.nuspec
NuGet\RGB.NET.Devices.Corsair.nuspec = NuGet\RGB.NET.Devices.Corsair.nuspec
NuGet\RGB.NET.Devices.Logitech.nuspec = NuGet\RGB.NET.Devices.Logitech.nuspec
NuGet\RGB.NET.Devices.Msi.nuspec = NuGet\RGB.NET.Devices.Msi.nuspec
NuGet\RGB.NET.Devices.Novation.nuspec = NuGet\RGB.NET.Devices.Novation.nuspec
NuGet\RGB.NET.Groups.nuspec = NuGet\RGB.NET.Groups.nuspec
NuGet\RGB.NET.Input.Corsair.nuspec = NuGet\RGB.NET.Input.Corsair.nuspec
@ -57,6 +58,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RGB.NET.Decorators", "RGB.N
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RGB.NET.Devices.Aura", "RGB.NET.Devices.Aura\RGB.NET.Devices.Aura.csproj", "{4F2F3FBD-A1E4-4968-A2AD-0514959E5E59}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RGB.NET.Devices.Msi", "RGB.NET.Devices.Msi\RGB.NET.Devices.Msi.csproj", "{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -111,6 +114,10 @@ Global
{4F2F3FBD-A1E4-4968-A2AD-0514959E5E59}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4F2F3FBD-A1E4-4968-A2AD-0514959E5E59}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4F2F3FBD-A1E4-4968-A2AD-0514959E5E59}.Release|Any CPU.Build.0 = Release|Any CPU
{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -127,6 +134,7 @@ Global
{DB2911F6-404C-4BC8-B35F-232A7450755F} = {33D5E279-1C4E-4AB6-9D1E-6D18109A6C25}
{7012C431-244A-453F-B7FD-59E030CDBC44} = {FFBCAF88-6646-43EC-9F24-2D719D3779C8}
{4F2F3FBD-A1E4-4968-A2AD-0514959E5E59} = {33D5E279-1C4E-4AB6-9D1E-6D18109A6C25}
{4EFD77C7-FDB4-4C6B-970C-0EF66D24BE09} = {33D5E279-1C4E-4AB6-9D1E-6D18109A6C25}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CDECA6C7-8D18-4AF3-94F7-C70A69B8571B}