refactor: implement InputLibrary Interface; make libraries support interface

This commit is contained in:
2026-01-17 00:32:58 -05:00
parent 92bea63815
commit 4225aeda33
8 changed files with 188 additions and 153 deletions
-1
View File
@@ -50,7 +50,6 @@ namespace Spectrum.Detection
var t0 = Stopwatch.GetTimestamp(); var t0 = Stopwatch.GetTimestamp();
renderer?.ClearDetectionDrawCommands(); renderer?.ClearDetectionDrawCommands();
AddTiming("Clear Draw Commands", Stopwatch.GetTimestamp() - t0);
if (!config.ClosestToMouse) if (!config.ClosestToMouse)
{ {
@@ -5,17 +5,19 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum.Input.InputLibraries.Arduino namespace Spectrum.Input.InputLibraries.Arduino
{ {
class ArduinoMain internal class ArduinoMain : IInputLibrary, IDisposable
{ {
private static readonly byte PingCommand = 0x02; private static readonly byte PingCommand = 0x02;
private static readonly byte PingResponse = 0xAA; private static readonly byte PingResponse = 0xAA;
private const int BaudRate = 115200; private const int BaudRate = 115200;
private const int HandshakeTimeoutMs = 1500; private const int HandshakeTimeoutMs = 1500;
private const int OpenResetDelayMs = 1200; private const int OpenResetDelayMs = 1200;
private static SerialPort? serial; private SerialPort? serial;
private static readonly object sync = new(); private readonly object sync = new();
public static bool Load() public bool RequiresInitialization => true;
public bool IsConnected => serial != null && serial.IsOpen;
public bool Initialize()
{ {
lock (sync) lock (sync)
{ {
@@ -106,7 +108,7 @@ namespace Spectrum.Input.InputLibraries.Arduino
return false; return false;
} }
public static void Close() public void Dispose()
{ {
lock (sync) lock (sync)
{ {
@@ -130,7 +132,7 @@ namespace Spectrum.Input.InputLibraries.Arduino
} }
} }
public static void Move(int x, int y) public void Move(int x, int y)
{ {
SerialPort? sp; SerialPort? sp;
lock (sync) sp = serial; lock (sync) sp = serial;
@@ -158,17 +160,17 @@ namespace Spectrum.Input.InputLibraries.Arduino
y -= stepY; y -= stepY;
} }
} }
public static void ClickDown(int button = 0x03) public void Press(int button)
{ {
SendClick(button, true); SendMappedClick(button, true);
} }
public static void ClickUp(int button = 0x03) public void Release(int button)
{ {
SendClick(button, false); SendMappedClick(button, false);
} }
private static void SendClick(int buttonBase, bool expectDown) private void SendClick(int buttonBase, bool expectDown)
{ {
SerialPort? sp; SerialPort? sp;
lock (sync) sp = serial; lock (sync) sp = serial;
@@ -188,5 +190,18 @@ namespace Spectrum.Input.InputLibraries.Arduino
LogManager.Log($"ArduinoMain: Click {(expectDown ? "down" : "up")} failed: {ex.Message}", LogLevel.Debug); LogManager.Log($"ArduinoMain: Click {(expectDown ? "down" : "up")} failed: {ex.Message}", LogLevel.Debug);
} }
} }
private void SendMappedClick(int button, bool isDown)
{
int mapped = button switch
{
0x01 => 0x03,
0x02 => 0x05,
_ => 0
};
if (mapped == 0) return;
SendClick(mapped, isDown);
}
} }
} }
+92 -98
View File
@@ -4,7 +4,7 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum.Input.InputLibraries.HID namespace Spectrum.Input.InputLibraries.HID
{ {
internal class HIDMain(int? vid = null, int? pid = null) internal class HIDMain(int? vid = null, int? pid = null) : IInputLibrary, IDisposable
{ {
readonly int[] ExpectedVIDs = readonly int[] ExpectedVIDs =
[ [
@@ -40,6 +40,89 @@ namespace Spectrum.Input.InputLibraries.HID
HidStream? stream; HidStream? stream;
private readonly object _syncLock = new(); private readonly object _syncLock = new();
public bool RequiresInitialization => true;
public bool IsConnected => stream != null && device != null;
public bool Initialize()
{
lock (_syncLock)
{
if (stream != null && device != null)
{
LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug);
return true;
}
LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug);
var candidates = FindDevice().ToList();
if (candidates.Count == 0)
{
LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning);
return false;
}
foreach (var dev in candidates)
{
try
{
LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug);
if (dev.TryOpen(out stream))
{
if (TestDeviceWithPing(dev, stream))
{
device = dev;
vid = dev.VendorID;
pid = dev.ProductID;
LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info);
return true;
}
LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug);
stream.Close();
stream.Dispose();
stream = null;
}
else
{
LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug);
}
}
catch (Exception ex)
{
LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug);
stream?.Close();
stream?.Dispose();
stream = null;
}
}
LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning);
return false;
}
}
public void Dispose()
{
lock (_syncLock)
{
try
{
stream?.Close();
stream?.Dispose();
LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug);
}
catch (Exception ex)
{
LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug);
}
finally
{
stream = null;
device = null;
}
}
}
IEnumerable<HidDevice> FindDevice() IEnumerable<HidDevice> FindDevice()
{ {
var devices = DeviceList.Local.GetHidDevices(); var devices = DeviceList.Local.GetHidDevices();
@@ -153,67 +236,6 @@ namespace Spectrum.Input.InputLibraries.HID
return false; return false;
} }
public bool Init()
{
lock (_syncLock)
{
if (stream != null && device != null)
{
LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug);
return true;
}
LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug);
var candidates = FindDevice().ToList();
if (candidates.Count == 0)
{
LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning);
return false;
}
foreach (var dev in candidates)
{
try
{
LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug);
if (dev.TryOpen(out stream))
{
if (TestDeviceWithPing(dev, stream))
{
device = dev;
vid = dev.VendorID;
pid = dev.ProductID;
LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info);
return true;
}
else
{
LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug);
stream.Close();
stream.Dispose();
stream = null;
}
}
else
{
LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug);
}
}
catch (Exception ex)
{
LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug);
stream?.Close();
stream?.Dispose();
stream = null;
}
}
LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning);
return false;
}
}
private bool SendFeatureReport(byte[] data) private bool SendFeatureReport(byte[] data)
{ {
@@ -245,7 +267,7 @@ namespace Spectrum.Input.InputLibraries.HID
} }
} }
public bool Move(int x, int y) public void Move(int x, int y)
{ {
x = Math.Clamp(x, -127, 127); x = Math.Clamp(x, -127, 127);
y = Math.Clamp(y, -127, 127); y = Math.Clamp(y, -127, 127);
@@ -254,9 +276,7 @@ namespace Spectrum.Input.InputLibraries.HID
byte yByte = unchecked((byte)y); byte yByte = unchecked((byte)y);
byte[] data = [CMD_MOVE, xByte, yByte]; byte[] data = [CMD_MOVE, xByte, yByte];
bool success = SendFeatureReport(data); SendFeatureReport(data);
return success;
} }
public bool Click(byte button) public bool Click(byte button)
@@ -267,20 +287,16 @@ namespace Spectrum.Input.InputLibraries.HID
return success; return success;
} }
public bool Press(byte button) public void Press(int button)
{ {
byte[] data = [CMD_PRESS, button]; byte[] data = [CMD_PRESS, (byte)button];
bool success = SendFeatureReport(data); SendFeatureReport(data);
return success;
} }
public bool Release(byte button) public void Release(int button)
{ {
byte[] data = [CMD_RELEASE, button]; byte[] data = [CMD_RELEASE, (byte)button];
bool success = SendFeatureReport(data); SendFeatureReport(data);
return success;
} }
public bool Scroll(int amount) public bool Scroll(int amount)
@@ -294,28 +310,6 @@ namespace Spectrum.Input.InputLibraries.HID
return success; return success;
} }
public void Close()
{
lock (_syncLock)
{
try
{
stream?.Close();
stream?.Dispose();
LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug);
}
catch (Exception ex)
{
LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug);
}
finally
{
stream = null;
device = null;
}
}
}
public bool IsConnected => stream != null && device != null;
} }
} }
@@ -0,0 +1,13 @@
namespace Spectrum.Input.InputLibraries
{
public interface IInputLibrary
{
bool RequiresInitialization { get; }
bool IsConnected { get; }
bool Initialize();
void Dispose();
void Move(int x, int y);
void Press(int button);
void Release(int button);
}
}
@@ -2,23 +2,44 @@
namespace Spectrum.Input.InputLibraries.MouseEvent namespace Spectrum.Input.InputLibraries.MouseEvent
{ {
public class MouseMain public class MouseMain : IInputLibrary
{ {
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo); private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
public bool RequiresInitialization => false;
public bool IsConnected => true;
public bool Initialize() { return true; }
public void Dispose() { }
public static void Move(int x, int y) public void Move(int x, int y)
{ {
mouse_event(0x0001, (uint)x, (uint)y, 0, 0); mouse_event(0x0001, (uint)x, (uint)y, 0, 0);
} }
public static void ClickDown() public void Press(int button)
{ {
mouse_event(0x0002, 0, 0, 0, 0); uint downFlag = button switch
}
public static void ClickUp()
{ {
mouse_event(0x0004, 0, 0, 0, 0); 0x01 => 0x0002, // left: down
0x02 => 0x0008, // right: down
0x03 => 0x0020, // middle: down
_ => 0
};
if (downFlag != 0)
mouse_event(downFlag, 0, 0, 0, 0);
}
public void Release(int button)
{
uint upFlag = button switch
{
0x01 => 0x0004, // left: up
0x02 => 0x0010, // right: up
0x03 => 0x0040, // middle: up
_ => 0
};
if (upFlag != 0)
mouse_event(upFlag, 0, 0, 0, 0);
} }
} }
} }
+14 -24
View File
@@ -1,9 +1,7 @@
using Spectrum.Input.InputLibraries.Arduino; using Spectrum.Input.InputLibraries.HID;
using Spectrum.Input.InputLibraries.HID;
using Spectrum.Utilities; using Spectrum.Utilities;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
namespace Spectrum.Input namespace Spectrum.Input
{ {
@@ -107,10 +105,10 @@ namespace Spectrum.Input
switch (config.MovementMethod) switch (config.MovementMethod)
{ {
case MovementMethod.MouseEvent: case MovementMethod.MouseEvent:
MouseEvent.Move(deltaX, deltaY); Program.MouseMain.Move(deltaX, deltaY);
break; break;
case MovementMethod.Arduino: case MovementMethod.Arduino:
ArduinoMain.Move(deltaX, deltaY); Program.ArduinoMain.Move(deltaX, deltaY);
break; break;
case MovementMethod.HID: case MovementMethod.HID:
if (hid != null && hid.IsConnected) if (hid != null && hid.IsConnected)
@@ -119,7 +117,7 @@ namespace Spectrum.Input
LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}"); LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}");
break; break;
default: default:
MouseEvent.Move(deltaX, deltaY); Program.MouseMain.Move(deltaX, deltaY);
break; break;
} }
} }
@@ -132,23 +130,15 @@ namespace Spectrum.Input
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity), MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity),
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity), MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity),
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity), MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity),
MovementType.WindMouse => TrackWindMouse(start, end, sensitivity, insideBoundingBox), MovementType.WindMouse => MovementPaths.WindMouse(start, end,
_ => MovementPaths.LinearInterpolation(start, end, sensitivity),
};
}
private static Point TrackWindMouse(Point start, Point end, double sensitivity, bool insideBoundingBox)
{
var t0 = Stopwatch.GetTimestamp();
var result = MovementPaths.WindMouse(start, end,
mainConfig.Data.WindMouseGravity, mainConfig.Data.WindMouseGravity,
mainConfig.Data.WindMouseWind, mainConfig.Data.WindMouseWind,
mainConfig.Data.WindMouseMaxStep, mainConfig.Data.WindMouseMaxStep,
sensitivity, sensitivity,
mainConfig.Data.WindMouseOvershoot, mainConfig.Data.WindMouseOvershoot,
insideBoundingBox); insideBoundingBox),
Program.Timings.Add("WindMouse", Stopwatch.GetTimestamp() - t0); _ => MovementPaths.LinearInterpolation(start, end, sensitivity),
return result; };
} }
public static async Task ClickMouse() public static async Task ClickMouse()
@@ -219,17 +209,17 @@ namespace Spectrum.Input
switch (movementMethod) switch (movementMethod)
{ {
case MovementMethod.MouseEvent: case MovementMethod.MouseEvent:
MouseEvent.ClickDown(); Program.MouseMain.Press(0x01);
break; break;
case MovementMethod.Arduino: case MovementMethod.Arduino:
ArduinoMain.ClickDown(); Program.ArduinoMain.Press(0x01);
break; break;
case MovementMethod.HID: case MovementMethod.HID:
if (hid != null && hid.IsConnected) if (hid != null && hid.IsConnected)
hid.Press(HIDMain.BUTTON_LEFT); hid.Press(HIDMain.BUTTON_LEFT);
break; break;
default: default:
MouseEvent.ClickDown(); Program.MouseMain.Press(0x01);
break; break;
} }
} }
@@ -238,17 +228,17 @@ namespace Spectrum.Input
switch (movementMethod) switch (movementMethod)
{ {
case MovementMethod.MouseEvent: case MovementMethod.MouseEvent:
MouseEvent.ClickUp(); Program.MouseMain.Release(0x01);
break; break;
case MovementMethod.Arduino: case MovementMethod.Arduino:
ArduinoMain.ClickUp(); Program.ArduinoMain.Release(0x01);
break; break;
case MovementMethod.HID: case MovementMethod.HID:
if (hid != null && hid.IsConnected) if (hid != null && hid.IsConnected)
hid.Release(HIDMain.BUTTON_LEFT); hid.Release(HIDMain.BUTTON_LEFT);
break; break;
default: default:
MouseEvent.ClickUp(); Program.MouseMain.Release(0x01);
break; break;
} }
} }
+4
View File
@@ -1,6 +1,8 @@
using OpenCvSharp; using OpenCvSharp;
using Spectrum.Detection; using Spectrum.Detection;
using Spectrum.Input.InputLibraries.Arduino;
using Spectrum.Input.InputLibraries.HID; using Spectrum.Input.InputLibraries.HID;
using Spectrum.Input.InputLibraries.MouseEvent;
using Spectrum.Utilities; using Spectrum.Utilities;
using System.CommandLine; using System.CommandLine;
@@ -11,6 +13,8 @@ namespace Spectrum
static Renderer? renderer = null; static Renderer? renderer = null;
public static ConfigManager<ConfigData> mainConfig = new("bin\\configs\\default.json", "bin\\configs"); public static ConfigManager<ConfigData> mainConfig = new("bin\\configs\\default.json", "bin\\configs");
public static ColorConfigManager colorConfig = new("bin\\configs\\colors"); public static ColorConfigManager colorConfig = new("bin\\configs\\colors");
public static MouseMain MouseMain = new();
public static ArduinoMain ArduinoMain = new();
public static HIDMain HIDMain = new(); public static HIDMain HIDMain = new();
private static DetectionManager? detectionManager; private static DetectionManager? detectionManager;
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager(); public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
+9 -10
View File
@@ -1,12 +1,11 @@
using ClickableTransparentOverlay; using ClickableTransparentOverlay;
using ImGuiNET; using ImGuiNET;
using OpenCvSharp; using OpenCvSharp;
using Spectrum.Detection;
using Spectrum.Input;
using Spectrum.Input.InputLibraries.Arduino;
using Spectrum.Utilities;
using SixLabors.ImageSharp; using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.PixelFormats;
using Spectrum.Detection;
using Spectrum.Input;
using Spectrum.Utilities;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
using System.Numerics; using System.Numerics;
@@ -691,13 +690,13 @@ namespace Spectrum
case MovementMethod.Arduino: case MovementMethod.Arduino:
{ {
if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) if (Program.HIDMain != null && Program.HIDMain.IsConnected == true)
Program.HIDMain.Close(); Program.HIDMain.Dispose();
var ok = ArduinoMain.Load(); var ok = Program.ArduinoMain.Initialize();
if (!ok) if (!ok)
{ {
LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
config.MovementMethod = MovementMethod.MouseEvent; config.MovementMethod = MovementMethod.MouseEvent;
ArduinoMain.Close(); Program.ArduinoMain.Dispose();
} }
break; break;
} }
@@ -706,7 +705,7 @@ namespace Spectrum
try try
{ {
if (Program.HIDMain?.IsConnected == false) if (Program.HIDMain?.IsConnected == false)
Program.HIDMain.Init(); Program.HIDMain.Initialize();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -716,9 +715,9 @@ namespace Spectrum
break; break;
} }
default: default:
ArduinoMain.Close(); Program.ArduinoMain.Dispose();
if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) if (Program.HIDMain != null && Program.HIDMain.IsConnected == true)
Program.HIDMain.Close(); Program.HIDMain.Dispose();
break; break;
} }
} }