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();
renderer?.ClearDetectionDrawCommands();
AddTiming("Clear Draw Commands", Stopwatch.GetTimestamp() - t0);
if (!config.ClosestToMouse)
{
@@ -5,17 +5,19 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum.Input.InputLibraries.Arduino
{
class ArduinoMain
internal class ArduinoMain : IInputLibrary, IDisposable
{
private static readonly byte PingCommand = 0x02;
private static readonly byte PingResponse = 0xAA;
private const int BaudRate = 115200;
private const int HandshakeTimeoutMs = 1500;
private const int OpenResetDelayMs = 1200;
private static SerialPort? serial;
private static readonly object sync = new();
private SerialPort? serial;
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)
{
@@ -106,7 +108,7 @@ namespace Spectrum.Input.InputLibraries.Arduino
return false;
}
public static void Close()
public void Dispose()
{
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;
lock (sync) sp = serial;
@@ -158,17 +160,17 @@ namespace Spectrum.Input.InputLibraries.Arduino
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;
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);
}
}
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
{
internal class HIDMain(int? vid = null, int? pid = null)
internal class HIDMain(int? vid = null, int? pid = null) : IInputLibrary, IDisposable
{
readonly int[] ExpectedVIDs =
[
@@ -40,6 +40,89 @@ namespace Spectrum.Input.InputLibraries.HID
HidStream? stream;
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()
{
var devices = DeviceList.Local.GetHidDevices();
@@ -153,67 +236,6 @@ namespace Spectrum.Input.InputLibraries.HID
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)
{
@@ -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);
y = Math.Clamp(y, -127, 127);
@@ -254,9 +276,7 @@ namespace Spectrum.Input.InputLibraries.HID
byte yByte = unchecked((byte)y);
byte[] data = [CMD_MOVE, xByte, yByte];
bool success = SendFeatureReport(data);
return success;
SendFeatureReport(data);
}
public bool Click(byte button)
@@ -267,20 +287,16 @@ namespace Spectrum.Input.InputLibraries.HID
return success;
}
public bool Press(byte button)
public void Press(int button)
{
byte[] data = [CMD_PRESS, button];
bool success = SendFeatureReport(data);
return success;
byte[] data = [CMD_PRESS, (byte)button];
SendFeatureReport(data);
}
public bool Release(byte button)
public void Release(int button)
{
byte[] data = [CMD_RELEASE, button];
bool success = SendFeatureReport(data);
return success;
byte[] data = [CMD_RELEASE, (byte)button];
SendFeatureReport(data);
}
public bool Scroll(int amount)
@@ -294,28 +310,6 @@ namespace Spectrum.Input.InputLibraries.HID
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
{
public class MouseMain
public class MouseMain : IInputLibrary
{
[DllImport("user32.dll")]
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);
}
public static void ClickDown()
public void Press(int button)
{
mouse_event(0x0002, 0, 0, 0, 0);
}
public static void ClickUp()
uint downFlag = button switch
{
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 System.Diagnostics;
using System.Runtime.InteropServices;
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
namespace Spectrum.Input
{
@@ -107,10 +105,10 @@ namespace Spectrum.Input
switch (config.MovementMethod)
{
case MovementMethod.MouseEvent:
MouseEvent.Move(deltaX, deltaY);
Program.MouseMain.Move(deltaX, deltaY);
break;
case MovementMethod.Arduino:
ArduinoMain.Move(deltaX, deltaY);
Program.ArduinoMain.Move(deltaX, deltaY);
break;
case MovementMethod.HID:
if (hid != null && hid.IsConnected)
@@ -119,7 +117,7 @@ namespace Spectrum.Input
LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}");
break;
default:
MouseEvent.Move(deltaX, deltaY);
Program.MouseMain.Move(deltaX, deltaY);
break;
}
}
@@ -132,23 +130,15 @@ namespace Spectrum.Input
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity),
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity),
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity),
MovementType.WindMouse => TrackWindMouse(start, end, sensitivity, insideBoundingBox),
_ => 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,
MovementType.WindMouse => MovementPaths.WindMouse(start, end,
mainConfig.Data.WindMouseGravity,
mainConfig.Data.WindMouseWind,
mainConfig.Data.WindMouseMaxStep,
sensitivity,
mainConfig.Data.WindMouseOvershoot,
insideBoundingBox);
Program.Timings.Add("WindMouse", Stopwatch.GetTimestamp() - t0);
return result;
insideBoundingBox),
_ => MovementPaths.LinearInterpolation(start, end, sensitivity),
};
}
public static async Task ClickMouse()
@@ -219,17 +209,17 @@ namespace Spectrum.Input
switch (movementMethod)
{
case MovementMethod.MouseEvent:
MouseEvent.ClickDown();
Program.MouseMain.Press(0x01);
break;
case MovementMethod.Arduino:
ArduinoMain.ClickDown();
Program.ArduinoMain.Press(0x01);
break;
case MovementMethod.HID:
if (hid != null && hid.IsConnected)
hid.Press(HIDMain.BUTTON_LEFT);
break;
default:
MouseEvent.ClickDown();
Program.MouseMain.Press(0x01);
break;
}
}
@@ -238,17 +228,17 @@ namespace Spectrum.Input
switch (movementMethod)
{
case MovementMethod.MouseEvent:
MouseEvent.ClickUp();
Program.MouseMain.Release(0x01);
break;
case MovementMethod.Arduino:
ArduinoMain.ClickUp();
Program.ArduinoMain.Release(0x01);
break;
case MovementMethod.HID:
if (hid != null && hid.IsConnected)
hid.Release(HIDMain.BUTTON_LEFT);
break;
default:
MouseEvent.ClickUp();
Program.MouseMain.Release(0x01);
break;
}
}
+4
View File
@@ -1,6 +1,8 @@
using OpenCvSharp;
using Spectrum.Detection;
using Spectrum.Input.InputLibraries.Arduino;
using Spectrum.Input.InputLibraries.HID;
using Spectrum.Input.InputLibraries.MouseEvent;
using Spectrum.Utilities;
using System.CommandLine;
@@ -11,6 +13,8 @@ namespace Spectrum
static Renderer? renderer = null;
public static ConfigManager<ConfigData> mainConfig = new("bin\\configs\\default.json", "bin\\configs");
public static ColorConfigManager colorConfig = new("bin\\configs\\colors");
public static MouseMain MouseMain = new();
public static ArduinoMain ArduinoMain = new();
public static HIDMain HIDMain = new();
private static DetectionManager? detectionManager;
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
+9 -10
View File
@@ -1,12 +1,11 @@
using ClickableTransparentOverlay;
using ImGuiNET;
using OpenCvSharp;
using Spectrum.Detection;
using Spectrum.Input;
using Spectrum.Input.InputLibraries.Arduino;
using Spectrum.Utilities;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Spectrum.Detection;
using Spectrum.Input;
using Spectrum.Utilities;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Numerics;
@@ -691,13 +690,13 @@ namespace Spectrum
case MovementMethod.Arduino:
{
if (Program.HIDMain != null && Program.HIDMain.IsConnected == true)
Program.HIDMain.Close();
var ok = ArduinoMain.Load();
Program.HIDMain.Dispose();
var ok = Program.ArduinoMain.Initialize();
if (!ok)
{
LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
config.MovementMethod = MovementMethod.MouseEvent;
ArduinoMain.Close();
Program.ArduinoMain.Dispose();
}
break;
}
@@ -706,7 +705,7 @@ namespace Spectrum
try
{
if (Program.HIDMain?.IsConnected == false)
Program.HIDMain.Init();
Program.HIDMain.Initialize();
}
catch (Exception ex)
{
@@ -716,9 +715,9 @@ namespace Spectrum
break;
}
default:
ArduinoMain.Close();
Program.ArduinoMain.Dispose();
if (Program.HIDMain != null && Program.HIDMain.IsConnected == true)
Program.HIDMain.Close();
Program.HIDMain.Dispose();
break;
}
}