-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy path_CUESDK.cs
381 lines (305 loc) · 16.3 KB
/
_CUESDK.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#pragma warning disable IDE1006 // Naming Styles
// 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;
namespace RGB.NET.Devices.Corsair.Native;
internal delegate void CorsairSessionStateChangedHandler(nint context, _CorsairSessionStateChanged eventData);
internal delegate void CorsairEventHandler(nint context, _CorsairEvent corsairEvent);
// ReSharper disable once InconsistentNaming
internal static unsafe class _CUESDK
{
#region Constants
/// <summary>
/// iCUE-SDK: small string length
/// </summary>
internal const int CORSAIR_STRING_SIZE_S = 64;
/// <summary>
/// iCUE-SDK: medium string length
/// </summary>
internal const int CORSAIR_STRING_SIZE_M = 128;
/// <summary>
/// iCUE-SDK: maximum level of layer’s priority that can be used in CorsairSetLayerPriority
/// </summary>
internal const int CORSAIR_LAYER_PRIORITY_MAX = 255;
/// <summary>
/// iCUE-SDK: maximum number of devices to be discovered
/// </summary>
internal const int CORSAIR_DEVICE_COUNT_MAX = 64;
/// <summary>
/// iCUE-SDK: maximum number of LEDs controlled by device
/// </summary>
internal const int CORSAIR_DEVICE_LEDCOUNT_MAX = 512;
#endregion
#region Properties & Fields
internal static bool IsConnected => SessionState == CorsairSessionState.Connected;
internal static CorsairSessionState SessionState { get; private set; }
#endregion
#region Events
internal static event EventHandler<CorsairSessionState>? SessionStateChanged;
internal static event EventHandler<_CorsairDeviceConnectionStatusChangedEvent>? DeviceConnectionEvent;
#endregion
#region Methods
private static void CorsairSessionStateChangedCallback(nint context, _CorsairSessionStateChanged eventData)
{
SessionState = eventData.state;
try
{
SessionStateChanged?.Invoke(null, eventData.state);
}
catch { /* dont let exception go to sdk */ }
switch (eventData.state)
{
case CorsairSessionState.Connected:
_corsairSubscribeForEvents(CorsairEventCallback, 0);
break;
case CorsairSessionState.Closed:
_corsairUnsubscribeForEvents();
break;
}
}
private static void CorsairEventCallback(nint context, _CorsairEvent eventData)
{
if (eventData.id != CorsairEventId.DeviceConnectionStatusChangedEvent)
{
return;
}
try
{
if (eventData.eventPointer == 0)
{
return;
}
_CorsairDeviceConnectionStatusChangedEvent connectionStatusChangedEvent =
Marshal.PtrToStructure<_CorsairDeviceConnectionStatusChangedEvent>(eventData.eventPointer)!;
DeviceConnectionEvent?.Invoke(null, connectionStatusChangedEvent);
}catch { /* dont let exception go to sdk */ }
}
#endregion
#region Libary Management
private static nint _handle = 0;
/// <summary>
/// Reloads the SDK.
/// </summary>
internal static void Reload()
{
UnloadCUESDK();
LoadCUESDK();
}
private static void LoadCUESDK()
{
if (_handle != 0) return;
List<string> possiblePathList = GetPossibleLibraryPaths().ToList();
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 (!NativeLibrary.TryLoad(dllPath, out _handle))
throw new RGBDeviceException($"Corsair LoadLibrary failed with error code {Marshal.GetLastPInvokeError()}");
_corsairConnectPtr = (delegate* unmanaged[Cdecl]<CorsairSessionStateChangedHandler, nint, CorsairError>)LoadFunction("CorsairConnect");
_corsairGetSessionDetails = (delegate* unmanaged[Cdecl]<nint, CorsairError>)LoadFunction("CorsairGetSessionDetails");
_corsairDisconnect = (delegate* unmanaged[Cdecl]<CorsairError>)LoadFunction("CorsairDisconnect");
_corsairGetDevices = (delegate* unmanaged[Cdecl]<_CorsairDeviceFilter, int, nint, out int, CorsairError>)LoadFunction("CorsairGetDevices");
_corsairGetDeviceInfo = (delegate* unmanaged[Cdecl]<string, ref _CorsairDeviceInfo, CorsairError>)LoadFunction("CorsairGetDeviceInfo");
_corsairGetLedPositions = (delegate* unmanaged[Cdecl]<string, int, nint, out int, CorsairError>)LoadFunction("CorsairGetLedPositions");
_corsairSetLedColors = (delegate* unmanaged[Cdecl]<string, int, nint, CorsairError>)LoadFunction("CorsairSetLedColors");
_corsairSetLayerPriority = (delegate* unmanaged[Cdecl]<uint, CorsairError>)LoadFunction("CorsairSetLayerPriority");
_corsairGetLedLuidForKeyName = (delegate* unmanaged[Cdecl]<string, char, out uint, CorsairError>)LoadFunction("CorsairGetLedLuidForKeyName");
_corsairRequestControl = (delegate* unmanaged[Cdecl]<string, CorsairAccessLevel, CorsairError>)LoadFunction("CorsairRequestControl");
_corsairReleaseControl = (delegate* unmanaged[Cdecl]<string, CorsairError>)LoadFunction("CorsairReleaseControl");
_getDevicePropertyInfo = (delegate* unmanaged[Cdecl]<string, CorsairDevicePropertyId, uint, out CorsairDataType, out CorsairPropertyFlag, CorsairError>)LoadFunction("CorsairGetDevicePropertyInfo");
_readDeviceProperty = (delegate* unmanaged[Cdecl]<string, CorsairDevicePropertyId, uint, nint, CorsairError>)LoadFunction("CorsairReadDeviceProperty");
_corsairSubscribeForEvents = (delegate* unmanaged[Cdecl]<CorsairEventHandler, nint, CorsairError>)LoadFunction("CorsairSubscribeForEvents");
_corsairUnsubscribeForEvents = (delegate* unmanaged[Cdecl]<CorsairError>)LoadFunction("CorsairSubscribeForEvents");
}
private static nint LoadFunction(string function)
{
if (!NativeLibrary.TryGetExport(_handle, function, out nint ptr)) throw new RGBDeviceException($"Failed to load Corsair function '{function}'");
return ptr;
}
private static IEnumerable<string> GetPossibleLibraryPaths()
{
IEnumerable<string> possibleLibraryPaths;
if (OperatingSystem.IsWindows())
possibleLibraryPaths = Environment.Is64BitProcess ? CorsairDeviceProvider.PossibleX64NativePaths : CorsairDeviceProvider.PossibleX86NativePaths;
else
possibleLibraryPaths = Enumerable.Empty<string>();
return possibleLibraryPaths.Select(Environment.ExpandEnvironmentVariables);
}
internal static void UnloadCUESDK()
{
if (_handle == 0) return;
_corsairConnectPtr = null;
_corsairGetSessionDetails = null;
_corsairDisconnect = null;
_corsairGetDevices = null;
_corsairGetDeviceInfo = null;
_corsairGetLedPositions = null;
_corsairSetLedColors = null;
_corsairSetLayerPriority = null;
_corsairGetLedLuidForKeyName = null;
_corsairRequestControl = null;
_corsairReleaseControl = null;
_getDevicePropertyInfo = null;
_readDeviceProperty = null;
NativeLibrary.Free(_handle);
_handle = 0;
}
#endregion
#region SDK-METHODS
#region Pointers
private static delegate* unmanaged[Cdecl]<CorsairSessionStateChangedHandler, nint, CorsairError> _corsairConnectPtr;
private static delegate* unmanaged[Cdecl]<nint, CorsairError> _corsairGetSessionDetails;
private static delegate* unmanaged[Cdecl]<CorsairError> _corsairDisconnect;
private static delegate* unmanaged[Cdecl]<_CorsairDeviceFilter, int, nint, out int, CorsairError> _corsairGetDevices;
private static delegate* unmanaged[Cdecl]<string, ref _CorsairDeviceInfo, CorsairError> _corsairGetDeviceInfo;
private static delegate* unmanaged[Cdecl]<string, int, nint, out int, CorsairError> _corsairGetLedPositions;
private static delegate* unmanaged[Cdecl]<string, int, nint, CorsairError> _corsairSetLedColors;
private static delegate* unmanaged[Cdecl]<uint, CorsairError> _corsairSetLayerPriority;
private static delegate* unmanaged[Cdecl]<string, char, out uint, CorsairError> _corsairGetLedLuidForKeyName;
private static delegate* unmanaged[Cdecl]<string, CorsairAccessLevel, CorsairError> _corsairRequestControl;
private static delegate* unmanaged[Cdecl]<string, CorsairError> _corsairReleaseControl;
private static delegate* unmanaged[Cdecl]<string, CorsairDevicePropertyId, uint, out CorsairDataType, out CorsairPropertyFlag, CorsairError> _getDevicePropertyInfo;
private static delegate* unmanaged[Cdecl]<string, CorsairDevicePropertyId, uint, nint, CorsairError> _readDeviceProperty;
private static delegate* unmanaged[Cdecl]<CorsairEventHandler, nint, CorsairError> _corsairSubscribeForEvents;
private static delegate* unmanaged[Cdecl]<CorsairError> _corsairUnsubscribeForEvents;
#endregion
internal static CorsairError CorsairConnect()
{
if (_corsairConnectPtr == null) throw new RGBDeviceException("The Corsair-SDK is not initialized.");
if (SessionState is CorsairSessionState.Connecting or CorsairSessionState.Timeout)
{
return CorsairError.Success;
}
return _corsairConnectPtr(CorsairSessionStateChangedCallback, 0);
}
internal static CorsairError CorsairGetSessionDetails(out _CorsairSessionDetails? details)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
nint sessionDetailPtr = Marshal.AllocHGlobal(Marshal.SizeOf<_CorsairSessionDetails>());
try
{
CorsairError error = _corsairGetSessionDetails(sessionDetailPtr);
details = Marshal.PtrToStructure<_CorsairSessionDetails>(sessionDetailPtr);
return error;
}
finally
{
Marshal.FreeHGlobal(sessionDetailPtr);
}
}
internal static CorsairError CorsairDisconnect()
{
return _corsairDisconnect();
}
internal static CorsairError CorsairGetDevices(_CorsairDeviceFilter filter, out _CorsairDeviceInfo[] devices)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
int structSize = Marshal.SizeOf<_CorsairDeviceInfo>();
nint devicePtr = Marshal.AllocHGlobal(structSize * CORSAIR_DEVICE_COUNT_MAX);
try
{
CorsairError error = _corsairGetDevices(filter, CORSAIR_DEVICE_COUNT_MAX, devicePtr, out int size);
devices = devicePtr.ToArray<_CorsairDeviceInfo>(size);
return error;
}
finally
{
Marshal.FreeHGlobal(devicePtr);
}
}
internal static CorsairError CorsairGetDeviceInfo(string deviceId, out _CorsairDeviceInfo deviceInfo)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
deviceInfo = new _CorsairDeviceInfo();
return _corsairGetDeviceInfo(deviceId, ref deviceInfo);
}
internal static CorsairError CorsairGetLedPositions(string deviceId, out _CorsairLedPosition[] ledPositions)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
int structSize = Marshal.SizeOf<_CorsairLedPosition>();
nint ledPositionsPtr = Marshal.AllocHGlobal(structSize * CORSAIR_DEVICE_LEDCOUNT_MAX);
try
{
CorsairError error = _corsairGetLedPositions(deviceId, CORSAIR_DEVICE_LEDCOUNT_MAX, ledPositionsPtr, out int size);
ledPositions = ledPositionsPtr.ToArray<_CorsairLedPosition>(size);
return error;
}
finally
{
Marshal.FreeHGlobal(ledPositionsPtr);
}
}
internal static CorsairError CorsairSetLedColors(string deviceId, int ledCount, nint ledColorsPtr)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
return _corsairSetLedColors(deviceId, ledCount, ledColorsPtr);
}
internal static CorsairError CorsairSetLayerPriority(uint priority)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
return _corsairSetLayerPriority(priority);
}
internal static CorsairError CorsairGetLedLuidForKeyName(string deviceId, char keyName, out uint ledId)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
return _corsairGetLedLuidForKeyName(deviceId, keyName, out ledId);
}
internal static CorsairError CorsairRequestControl(string deviceId, CorsairAccessLevel accessLevel)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
return _corsairRequestControl(deviceId, accessLevel);
}
internal static CorsairError CorsairReleaseControl(string deviceId)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
return _corsairReleaseControl(deviceId);
}
internal static CorsairError GetDevicePropertyInfo(string deviceId, CorsairDevicePropertyId propertyId, uint index, out CorsairDataType dataType, out CorsairPropertyFlag flags)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
return _getDevicePropertyInfo(deviceId, propertyId, index, out dataType, out flags);
}
internal static CorsairError ReadDeviceProperty(string deviceId, CorsairDevicePropertyId propertyId, uint index, out _CorsairProperty? property)
{
if (!IsConnected) throw new RGBDeviceException("The Corsair-SDK is not connected.");
nint propertyPtr = Marshal.AllocHGlobal(Marshal.SizeOf<_CorsairProperty>());
try
{
CorsairError error = _readDeviceProperty(deviceId, propertyId, index, propertyPtr);
property = Marshal.PtrToStructure<_CorsairProperty>(propertyPtr);
return error;
}
finally
{
Marshal.FreeHGlobal(propertyPtr);
}
}
internal static int ReadDevicePropertySimpleInt32(string deviceId, CorsairDevicePropertyId propertyId, uint index = 0) => ReadDevicePropertySimple(deviceId, propertyId, CorsairDataType.Int32, index).int32;
internal static int[] ReadDevicePropertySimpleInt32Array(string deviceId, CorsairDevicePropertyId propertyId, uint index = 0)
{
_CorsairDataValue dataValue = ReadDevicePropertySimple(deviceId, propertyId, CorsairDataType.Int32Array, index);
return dataValue.int32Array.items.ToArray<int>((int)dataValue.int32Array.count);
}
internal static _CorsairDataValue ReadDevicePropertySimple(string deviceId, CorsairDevicePropertyId propertyId, CorsairDataType expectedDataType, uint index = 0)
{
CorsairError errorCode = GetDevicePropertyInfo(deviceId, propertyId, index, out CorsairDataType dataType, out CorsairPropertyFlag flags);
if (errorCode != CorsairError.Success)
throw new RGBDeviceException($"Failed to read device-property-info '{propertyId}' for corsair device '{deviceId}'. (ErrorCode: {errorCode})");
if (dataType != expectedDataType)
throw new RGBDeviceException($"Failed to read device-property-info '{propertyId}' for corsair device '{deviceId}'. (Wrong data-type '{dataType}', expected: '{expectedDataType}')");
if (!flags.HasFlag(CorsairPropertyFlag.CanRead))
throw new RGBDeviceException($"Failed to read device-property-info '{propertyId}' for corsair device '{deviceId}'. (Not readable)");
errorCode = ReadDeviceProperty(deviceId, propertyId, index, out _CorsairProperty? property);
if (errorCode != CorsairError.Success)
throw new RGBDeviceException($"Failed to read device-property '{propertyId}' for corsair device '{deviceId}'. (ErrorCode: {errorCode})");
if (property == null)
throw new RGBDeviceException($"Failed to read device-property '{propertyId}' for corsair device '{deviceId}'. (Invalid return value)");
if (property.Value.type != expectedDataType)
throw new RGBDeviceException($"Failed to read device-property '{propertyId}' for corsair device '{deviceId}'. (Wrong data-type '{dataType}', expected: '{expectedDataType}')");
return property.Value.value;
}
#endregion
}