Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions SDK/Nefarius.DsHidMini.IPC/DsHidMiniInterop.Commands.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System.ComponentModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;

using Nefarius.DsHidMini.IPC.Exceptions;
using Nefarius.DsHidMini.IPC.Models;
Expand All @@ -21,26 +22,22 @@ public partial class DsHidMiniInterop
/// only return when the driver signaled that new data is available, otherwise you will just burn through CPU for no
/// good reason. A new input report is typically available each average 5 milliseconds, depending on the connection
/// (wired or wireless) so a timeout of 20 milliseconds should be a good recommendation.
/// When <paramref name="timeout" /> is set, the implementation waits on the driver's per-slot named auto-reset event
/// (same DACL as other IPC objects); it does not require administrator elevation.
/// </remarks>
/// <param name="deviceIndex">The one-based device index.</param>
/// <param name="report">The <see cref="DS3_RAW_INPUT_REPORT" /> to populate.</param>
/// <param name="timeout">Optional timeout to wait for a report update to arrive. Default invocation returns immediately.</param>
/// <exception cref="DsHidMiniInteropAccessDeniedException">
/// Driver process interaction failed due to missing permissions;
/// this operation requires elevated privileges.
/// </exception>
/// <exception cref="DsHidMiniInteropUnexpectedReplyException">The driver returned unexpected or malformed data.</exception>
/// <exception cref="Win32Exception">Handle duplication failed.</exception>
/// <exception cref="DsHidMiniInteropReplyTimeoutException">The driver didn't respond within an expected period.</exception>
/// <exception cref="DsHidMiniInteropConcurrencyException">A different thread is currently performing a data exchange.</exception>
/// <exception cref="DsHidMiniInteropUnavailableException">
/// No driver instance is available. Make sure that at least one
/// device is connected and that the driver is installed and working properly. Call <see cref="IsAvailable" /> prior to
/// avoid this exception.
/// </exception>
/// <returns>
/// TRUE if <paramref name="report" /> got filled in or FALSE if the given <paramref name="deviceIndex" /> is not
/// occupied.
/// occupied, or if <paramref name="timeout" /> is used and the named wait event for that slot does not exist (no device
/// in that slot).
/// </returns>
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public unsafe bool GetRawInputReport(int deviceIndex, ref DS3_RAW_INPUT_REPORT report, TimeSpan? timeout = null)
Expand All @@ -52,13 +49,20 @@ public unsafe bool GetRawInputReport(int deviceIndex, ref DS3_RAW_INPUT_REPORT r

ValidateDeviceIndex(deviceIndex);

ref IPC_HID_INPUT_REPORT_MESSAGE message = ref Unsafe.AsRef<IPC_HID_INPUT_REPORT_MESSAGE>(_hidView);
nuint byteOffset = (nuint)((deviceIndex - 1) * Marshal.SizeOf<IPC_HID_INPUT_REPORT_MESSAGE>());
void* pMessage = (byte*)_hidView.Value + byteOffset;
ref IPC_HID_INPUT_REPORT_MESSAGE message = ref Unsafe.AsRef<IPC_HID_INPUT_REPORT_MESSAGE>(pMessage);

if (timeout.HasValue)
{
_inputReportEvent ??= GetHidReportWaitHandle(deviceIndex);

_inputReportEvent.WaitOne(timeout.Value);
try
{
GetOrOpenHidReportWaitEvent(deviceIndex).WaitOne(timeout.Value);
}
catch (WaitHandleCannotBeOpenedException)
{
return false;
}
}

//
Expand Down
151 changes: 47 additions & 104 deletions SDK/Nefarius.DsHidMini.IPC/DsHidMiniInterop.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using System.ComponentModel;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Memory;
using Windows.Win32.System.SystemInformation;
using Windows.Win32.System.Threading;

using Microsoft.Win32.SafeHandles;

Expand All @@ -29,6 +29,11 @@ public sealed partial class DsHidMiniInterop : IDisposable
private const string WriteEventName = "Global\\DsHidMiniWriteEvent";
private const string MutexName = "Global\\DsHidMiniCommandMutex";

/// <summary>
/// Must match <c>DSHM_IPC_HID_REPORT_EVENT_PREFIX</c> in driver <c>IPC.h</c> (suffix is the one-based device index).
/// </summary>
private const string HidReportWaitEventNamePrefix = "Global\\DsHidMiniHidReportEvent";

private readonly Dictionary<int, PnPDevice> _connectedDevices = new();
private readonly DeviceNotificationListener _deviceListener = new();
private MEMORY_MAPPED_VIEW_ADDRESS? _cmdView;
Expand All @@ -38,7 +43,7 @@ public sealed partial class DsHidMiniInterop : IDisposable
private SafeFileHandle? _fileMapping;
private MEMORY_MAPPED_VIEW_ADDRESS? _hidView;

private EventWaitHandle? _inputReportEvent;
private readonly ConcurrentDictionary<int, EventWaitHandle> _inputReportWaitEvents = new();

private EventWaitHandle? _readEvent;
private EventWaitHandle? _writeEvent;
Expand Down Expand Up @@ -99,7 +104,7 @@ public void Dispose()

_readEvent?.Dispose();
_writeEvent?.Dispose();
_inputReportEvent?.Dispose();
DisposeInputReportWaitEvents();

_commandMutex?.Dispose();
}
Expand All @@ -114,6 +119,8 @@ public void Dispose()
/// </exception>
public void Reconnect()
{
DisposeInputReportWaitEvents();

PInvoke.GetSystemInfo(out SYSTEM_INFO systemInfo);

try
Expand Down Expand Up @@ -173,6 +180,8 @@ public void Reconnect()

private void RefreshDevices()
{
DisposeInputReportWaitEvents();

_connectedDevices.Clear();

int instanceIndex = 0;
Expand Down Expand Up @@ -212,116 +221,50 @@ private void DsHidMiniDeviceArrived(DeviceEventArgs obj)
RefreshDevices();
}

private void DisposeInputReportWaitEvents()
{
foreach (int key in _inputReportWaitEvents.Keys.ToArray())
{
if (_inputReportWaitEvents.TryRemove(key, out EventWaitHandle? handle))
{
handle.Dispose();
}
}
}

/// <summary>
/// Gets the input report wait handle from the driver and duplicates it into the current process.
/// Returns a cached handle to the driver's named auto-reset event for the given one-based device slot (created with
/// DACL allowing authenticated users).
/// </summary>
/// <exception cref="DsHidMiniInteropAccessDeniedException">
/// Driver process interaction failed due to missing permissions;
/// this operation requires elevated privileges.
/// <remarks>
/// <para>
/// <see cref="EventWaitHandle.OpenExisting(string)" /> is used to obtain the handle. It throws
/// <see cref="WaitHandleCannotBeOpenedException" /> when the named event does not exist (for example, the device
/// slot is empty). <see cref="GetRawInputReport" /> catches that exception and returns <see langword="false" />.
/// </para>
/// </remarks>
/// <exception cref="WaitHandleCannotBeOpenedException">
/// No kernel object exists for the per-slot name (prefix <see cref="HidReportWaitEventNamePrefix" /> plus
/// <paramref name="deviceIndex" />).
/// </exception>
/// <exception cref="DsHidMiniInteropUnexpectedReplyException">The driver returned unexpected or malformed data.</exception>
/// <exception cref="Win32Exception">Handle duplication failed.</exception>
/// <exception cref="DsHidMiniInteropReplyTimeoutException">The driver didn't respond within an expected period.</exception>
/// <exception cref="DsHidMiniInteropConcurrencyException">A different thread is currently performing a data exchange.</exception>
/// <exception cref="DsHidMiniInteropUnavailableException">
/// No driver instance is available. Make sure that at least one
/// device is connected and that the driver is installed and working properly. Call <see cref="IsAvailable" /> prior to
/// avoid this exception.
/// </exception>
private unsafe EventWaitHandle GetHidReportWaitHandle(int deviceIndex)
private EventWaitHandle GetOrOpenHidReportWaitEvent(int deviceIndex)
{
if (_commandMutex is null || _cmdView is null)
if (_inputReportWaitEvents.TryGetValue(deviceIndex, out EventWaitHandle? existing))
{
throw new DsHidMiniInteropUnavailableException();
return existing;
}

ValidateDeviceIndex(deviceIndex);

AcquireCommandLock();
string name = $"{HidReportWaitEventNamePrefix}{deviceIndex}";
EventWaitHandle opened = EventWaitHandle.OpenExisting(name);

try
if (_inputReportWaitEvents.TryAdd(deviceIndex, opened))
{
ref DSHM_IPC_MSG_HEADER request = ref Unsafe.AsRef<DSHM_IPC_MSG_HEADER>(_cmdView);

request.Type = DSHM_IPC_MSG_TYPE.DSHM_IPC_MSG_TYPE_RESPONSE_ONLY;
request.Target = DSHM_IPC_MSG_TARGET.DSHM_IPC_MSG_TARGET_DEVICE;
request.Command.Device = DSHM_IPC_MSG_CMD_DEVICE.DSHM_IPC_MSG_CMD_DEVICE_GET_HID_WAIT_HANDLE;
request.TargetIndex = (uint)deviceIndex;
request.Size = (uint)Marshal.SizeOf<DSHM_IPC_MSG_HEADER>();

if (!SendAndWait())
{
throw new DsHidMiniInteropReplyTimeoutException();
}
return opened;
}

ref DSHM_IPC_MSG_GET_HID_WAIT_HANDLE_RESPONSE reply =
ref Unsafe.AsRef<DSHM_IPC_MSG_GET_HID_WAIT_HANDLE_RESPONSE>(_cmdView);

//
// Plausibility check
//
if (reply.Header is
{
Type: DSHM_IPC_MSG_TYPE.DSHM_IPC_MSG_TYPE_RESPONSE_ONLY,
Target: DSHM_IPC_MSG_TARGET.DSHM_IPC_MSG_TARGET_CLIENT,
Command.Device: DSHM_IPC_MSG_CMD_DEVICE.DSHM_IPC_MSG_CMD_DEVICE_GET_HID_WAIT_HANDLE
}
&& reply.Header.TargetIndex == deviceIndex
&& reply.Header.Size == Marshal.SizeOf<DSHM_IPC_MSG_GET_HID_WAIT_HANDLE_RESPONSE>())
{
HANDLE driverProcess = PInvoke.OpenProcess(
PROCESS_ACCESS_RIGHTS.PROCESS_DUP_HANDLE,
new BOOL(false),
reply.ProcessId
);

try
{
if (driverProcess.IsNull)
{
if (Marshal.GetLastWin32Error() == (int)WIN32_ERROR.ERROR_ACCESS_DENIED)
{
throw new DsHidMiniInteropAccessDeniedException();
}

throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenProcess call failed.");
}

HANDLE dupHandle;

if (!PInvoke.DuplicateHandle(
driverProcess,
new HANDLE(reply.WaitHandle),
PInvoke.GetCurrentProcess(),
&dupHandle,
0,
new BOOL(false),
DUPLICATE_HANDLE_OPTIONS.DUPLICATE_SAME_ACCESS
))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "DuplicateHandle call failed.");
}

return new EventWaitHandle(false, EventResetMode.AutoReset)
{
SafeWaitHandle = new SafeWaitHandle(dupHandle, true)
};
}
finally
{
if (!driverProcess.IsNull)
{
PInvoke.CloseHandle(driverProcess);
}
}
}
opened.Dispose();

throw new DsHidMiniInteropUnexpectedReplyException(ref reply.Header);
}
finally
{
_commandMutex.ReleaseMutex();
}
return _inputReportWaitEvents[deviceIndex];
}

private void AcquireCommandLock()
Expand Down
7 changes: 4 additions & 3 deletions SDK/Nefarius.DsHidMini.IPC/Exceptions/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Nefarius.DsHidMini.IPC.Models;
using Nefarius.DsHidMini.IPC.Models;

namespace Nefarius.DsHidMini.IPC.Exceptions;

Expand Down Expand Up @@ -67,12 +67,13 @@ internal DsHidMiniInteropInvalidDeviceIndexException(int deviceIndex) : base(
}

/// <summary>
/// Driver process interaction failed due to missing permissions; this operation requires elevated privileges.
/// Reserved for compatibility; the current SDK does not throw this type. HID report waiting uses named events with
/// standard IPC DACLs (no handle duplication).
/// </summary>
public sealed class DsHidMiniInteropAccessDeniedException : Exception
{
internal DsHidMiniInteropAccessDeniedException() : base(
"Driver process interaction failed due to missing permissions; this operation requires elevated privileges.")
"Reserved; not used by the current SDK.")
{
}
}
24 changes: 1 addition & 23 deletions SDK/Nefarius.DsHidMini.IPC/Models/CmdStructs.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;

using Nefarius.DsHidMini.IPC.Models.Public;
Expand Down Expand Up @@ -124,25 +124,3 @@ internal struct DSHM_IPC_MSG_SET_PLAYER_INDEX_REPLY

public UInt32 NtStatus;
}

/// <summary>
/// Requests the driver host process PID and a wait handle for new input reports
/// </summary>
/// <remarks>Post-processing this command requires elevated privileges.</remarks>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[StructLayout(LayoutKind.Sequential)]
internal struct DSHM_IPC_MSG_GET_HID_WAIT_HANDLE_RESPONSE
{
public DSHM_IPC_MSG_HEADER Header;

/// <summary>
/// The driver hosting process PID
/// </summary>
public UInt32 ProcessId;

/// <summary>
/// A handle to an auto-reset event
/// </summary>
/// <remarks>The requester of this handle must duplicate it into the current process before it becomes usable.</remarks>
public IntPtr WaitHandle;
}
9 changes: 2 additions & 7 deletions SDK/Nefarius.DsHidMini.IPC/Models/Enums.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;

namespace Nefarius.DsHidMini.IPC.Models;

Expand Down Expand Up @@ -99,10 +99,5 @@ internal enum DSHM_IPC_MSG_CMD_DEVICE : UInt32
/// <summary>
/// Requests a player index update (switch player LED etc.)
/// </summary>
DSHM_IPC_MSG_CMD_DEVICE_SET_PLAYER_INDEX,

/// <summary>
/// Requests a wait handle for input report state changes
/// </summary>
DSHM_IPC_MSG_CMD_DEVICE_GET_HID_WAIT_HANDLE
DSHM_IPC_MSG_CMD_DEVICE_SET_PLAYER_INDEX
}
5 changes: 0 additions & 5 deletions SDK/Nefarius.DsHidMini.IPC/NativeMethods.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
OpenProcess
DuplicateHandle
GetCurrentProcess
DUPLICATE_HANDLE_OPTIONS
OpenFileMapping
MapViewOfFile
UnmapViewOfFile
FILE_MAP
GetSystemInfo
WIN32_ERROR
8 changes: 4 additions & 4 deletions SDK/Nefarius.DsHidMini.IPC/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ The SDK handles reconnection when the last device disconnects and the next one a
| **.NET** | .NET 8.0 (Windows-specific: `net8.0-windows`) |
| **OS** | Windows (named kernel objects and shared memory are Windows-only) |
| **Driver** | DsHidMini driver installed; at least one compatible controller connected and bound to the driver |
| **Elevation** | Required only for operations that duplicate the driver’s HID report wait handle (e.g. when using a timeout in `GetRawInputReport`). Other operations do not require admin. |
| **Elevation** | Not required for normal use. IPC uses named objects (mutex, events, shared memory, and per-device HID wait events) with DACLs that allow authenticated users, including event-based `GetRawInputReport`. |

Before creating a `DsHidMiniInterop` instance, check **`DsHidMiniInterop.IsAvailable`** to avoid throwing when no device is present.

Expand Down Expand Up @@ -117,7 +117,7 @@ if (gotReport)
| **`DsHidMiniInterop()`** | Connects to the driver IPC. Throws if not available. Subscribes to device arrival/removal for reconnection. |
| **`void Dispose()`** | Releases mapped views, file mapping, and events. Implement `IDisposable` and dispose when done. |
| **`void Reconnect()`** | Re-opens mutex, events, and shared memory (e.g. after all devices were removed). Throws if still no device. |
| **`bool GetRawInputReport(int deviceIndex, ref DS3_RAW_INPUT_REPORT report, TimeSpan? timeout)`** | Fills `report` with the last or next raw HID report. Use `timeout: null` for immediate read; use e.g. `TimeSpan.FromMilliseconds(20)` for event-based waiting. Returns `false` if the slot is empty. |
| **`bool GetRawInputReport(int deviceIndex, ref DS3_RAW_INPUT_REPORT report, TimeSpan? timeout)`** | Fills `report` with the last or next raw HID report. Use `timeout: null` for immediate read; use e.g. `TimeSpan.FromMilliseconds(20)` for event-based waiting on the driver’s named per-slot event (`Global\DsHidMiniHidReportEvent` + index). Returns `false` if the slot is empty, or if a timeout was requested and no wait object exists for that slot (nothing connected there). |
| **`void SendPing()`** | Sends a ping to the driver and waits for a reply (liveness check). |
| **`SetHostResult SetHostAddress(int deviceIndex, PhysicalAddress hostAddress)`** | Writes the new Bluetooth host address (pairing). Returns write/read NTSTATUS in `SetHostResult`. |
| **`uint SetPlayerIndex(int deviceIndex, byte playerIndex)`** | Sets the player LED index (1–7). Returns NTSTATUS. |
Expand Down Expand Up @@ -168,10 +168,10 @@ The SDK uses dedicated exception types so you can handle driver and usage errors
| **`DsHidMiniInteropInvalidDeviceIndexException`** | `deviceIndex` not in 1…255. |
| **`DsHidMiniInteropReplyTimeoutException`** | Driver did not respond within the expected time (e.g. ping or command). |
| **`DsHidMiniInteropConcurrencyException`** | Another thread is already performing an IPC call; only one at a time is allowed. |
| **`DsHidMiniInteropAccessDeniedException`** | Handle duplication failed (e.g. when using `GetRawInputReport` with a timeout without sufficient privileges). Run elevated if you need event-based reading. |
| **`DsHidMiniInteropAccessDeniedException`** | Reserved; not thrown by the current SDK. |
| **`DsHidMiniInteropUnexpectedReplyException`** | Driver replied with an unexpected or malformed message. |

Other failures (e.g. Win32 errors during handle duplication) may surface as `Win32Exception`.
Other failures may surface as `Win32Exception` where low-level Win32 calls apply.

---

Expand Down
Loading