Files
Spectrum/Spectrum/Input/InputLibraries/MakcuBinary/MakcuBinaryMain.cs
T
whoswhip e08e971bf9 old changes
all of these changes were done MONTHS ago, but i'll try to list them out:
- simplified input library switching & implementation
- implemented makcu binary, which is their new communication, have NOT tested
- renamed existing makcu implementation to makcuLegacy since they've changed their communication format
- overall simplification of code
- formatted code via csharpier
- minimal optimizations
2026-08-30 10:32:56 -04:00

356 lines
12 KiB
C#

using Spectrum.Utilities;
using System.Diagnostics;
using System.IO.Ports;
using LogLevel = Spectrum.Utilities.LogManager.LogLevel;
namespace Spectrum.Input.InputLibraries.MakcuBinary
{
internal class MakcuBinaryMain : IInputLibrary, IDisposable
{
#region Frame Constants
private const byte FrameStart = 0x50;
private const byte CmdMove = 0x0D;
private const byte CmdButtonsStream = 0x02;
private const byte CmdLeft = 0x08;
private const byte CmdRight = 0x11;
private const byte CmdMiddle = 0x0A;
private const byte CmdSide1 = 0x12;
private const byte CmdSide2 = 0x13;
private const byte CmdVersion = 0xBF;
#endregion
#region Serial Constants
private const int BaudRate = 115200;
private const int ReadTimeoutMs = 150;
private const int WriteTimeoutMs = 250;
private const int HandshakeTimeoutMs = 1200;
private const int OpenResetDelayMs = 200;
private const byte StreamModeRaw = 0x01;
private const byte StreamPeriodMs = 10;
#endregion
private SerialPort? serial;
private readonly object sync = new();
private CancellationTokenSource? readerCts;
private Thread? readerThread;
public event Action<ushort>? ButtonsChanged;
public bool RequiresInitialization => true;
public bool IsConnected => serial != null && serial.IsOpen;
public static MakcuBinaryMain Instance { get; } = new MakcuBinaryMain();
private MakcuBinaryMain() { }
public bool Initialize()
{
lock (sync)
{
if (serial != null && serial.IsOpen)
return true;
serial = FindDevice();
if (serial == null)
{
LogManager.Log("MakcuBinary: Failed to connect to device.", LogLevel.Warning);
return false;
}
StartButtonStreaming();
LogManager.Log($"MakcuBinary: Connected on {serial.PortName}.", LogLevel.Info);
return true;
}
}
public void Dispose()
{
lock (sync)
{
StopButtonStreaming();
if (serial != null)
{
try
{
serial.Close();
serial.Dispose();
}
catch (Exception ex)
{
LogManager.Log($"MakcuBinary: Error closing port: {ex.Message}", LogLevel.Debug);
}
finally
{
serial = null;
}
}
}
}
public void Move(int x, int y)
{
var payload = BuildMovePayload(x, y);
SendCommand(CmdMove, payload);
}
public void Press(int button)
{
SendButtonState(button, 0x01);
}
public void Release(int button)
{
SendButtonState(button, 0x00);
}
private static byte[] BuildMovePayload(int x, int y)
{
short dx = (short)Math.Clamp(x, short.MinValue, short.MaxValue);
short dy = (short)Math.Clamp(y, short.MinValue, short.MaxValue);
var payload = new byte[7];
BitConverter.GetBytes(dx).CopyTo(payload, 0);
BitConverter.GetBytes(dy).CopyTo(payload, 2);
payload[4] = 0x01;
payload[5] = 0x00;
payload[6] = 0x00;
return payload;
}
private void SendButtonState(int button, byte state)
{
byte cmd = MapButtonCommand(button);
if (cmd == 0) return;
SendCommand(cmd, new[] { state });
}
private static byte MapButtonCommand(int button)
{
return button switch
{
0x01 => CmdLeft,
0x02 => CmdRight,
0x03 => CmdMiddle,
0x04 => CmdSide1,
0x05 => CmdSide2,
_ => 0
};
}
private bool SendCommand(byte cmd, ReadOnlySpan<byte> payload)
{
SerialPort? sp;
lock (sync) sp = serial;
if (sp == null || !sp.IsOpen) return false;
byte[] frame = new byte[4 + payload.Length];
frame[0] = FrameStart;
frame[1] = cmd;
frame[2] = (byte)(payload.Length & 0xFF);
frame[3] = (byte)((payload.Length >> 8) & 0xFF);
payload.CopyTo(frame.AsSpan(4));
try
{
sp.Write(frame, 0, frame.Length);
return true;
}
catch (Exception ex)
{
LogManager.Log($"MakcuBinary: Write failed: {ex.Message}", LogLevel.Debug);
return false;
}
}
private SerialPort? FindDevice()
{
string[] candidates = SerialPort.GetPortNames();
if (candidates.Length == 0)
LogManager.Log("MakcuBinary: No serial ports detected.", LogLevel.Debug);
foreach (string portName in candidates)
{
try
{
LogManager.Log($"MakcuBinary: Probing {portName}...", LogLevel.Debug);
var sp = new SerialPort(portName, BaudRate)
{
ReadTimeout = ReadTimeoutMs,
WriteTimeout = WriteTimeoutMs,
DtrEnable = true,
RtsEnable = true
};
sp.Open();
Thread.Sleep(OpenResetDelayMs);
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
if (ProbeDevice(sp))
return sp;
sp.Close();
sp.Dispose();
}
catch (Exception ex)
{
LogManager.Log($"MakcuBinary: Probe failed on {portName}: {ex.Message}", LogLevel.Debug);
}
}
return null;
}
private bool ProbeDevice(SerialPort sp)
{
LogManager.Log("MakcuBinary: Sending version probe...", LogLevel.Debug);
if (!SendCommandOn(sp, CmdVersion, ReadOnlySpan<byte>.Empty))
return false;
if (TryReadFrame(sp, HandshakeTimeoutMs, out byte cmd, out _))
{
LogManager.Log($"MakcuBinary: Probe response cmd=0x{cmd:X2}.", LogLevel.Debug);
return cmd == CmdVersion;
}
return false;
}
private static bool SendCommandOn(SerialPort sp, byte cmd, ReadOnlySpan<byte> payload)
{
byte[] frame = new byte[4 + payload.Length];
frame[0] = FrameStart;
frame[1] = cmd;
frame[2] = (byte)(payload.Length & 0xFF);
frame[3] = (byte)((payload.Length >> 8) & 0xFF);
payload.CopyTo(frame.AsSpan(4));
try
{
sp.Write(frame, 0, frame.Length);
return true;
}
catch
{
return false;
}
}
private static bool TryReadFrame(SerialPort sp, int timeoutMs, out byte cmd, out byte[] payload)
{
cmd = 0;
payload = Array.Empty<byte>();
var sw = Stopwatch.StartNew();
int b = -1;
while (sw.ElapsedMilliseconds < timeoutMs)
{
if (!TryReadByte(sp, ReadTimeoutMs, out b))
continue;
if (b == FrameStart)
break;
}
if (b != FrameStart) return false;
if (!TryReadByte(sp, ReadTimeoutMs, out int cmdVal)) return false;
if (!TryReadByte(sp, ReadTimeoutMs, out int lenLo)) return false;
if (!TryReadByte(sp, ReadTimeoutMs, out int lenHi)) return false;
int len = lenLo | (lenHi << 8);
if (len < 0) return false;
payload = new byte[len];
if (!TryReadExact(sp, payload, ReadTimeoutMs)) return false;
cmd = (byte)cmdVal;
return true;
}
private static bool TryReadExact(SerialPort sp, byte[] buffer, int timeoutMs)
{
int offset = 0;
var sw = Stopwatch.StartNew();
while (offset < buffer.Length && sw.ElapsedMilliseconds < timeoutMs)
{
try
{
int read = sp.Read(buffer, offset, buffer.Length - offset);
if (read > 0)
offset += read;
}
catch (TimeoutException) { }
}
return offset == buffer.Length;
}
private static bool TryReadByte(SerialPort sp, int timeoutMs, out int value)
{
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeoutMs)
{
try
{
value = sp.ReadByte();
if (value >= 0) return true;
}
catch (TimeoutException) { }
}
value = -1;
return false;
}
private void StartButtonStreaming()
{
SendCommand(CmdButtonsStream, new[] { StreamModeRaw, StreamPeriodMs });
if (readerThread != null) return;
LogManager.Log("MakcuBinary: Starting button stream.", LogLevel.Debug);
readerCts = new CancellationTokenSource();
readerThread = new Thread(() => ReadLoop(readerCts.Token)) { IsBackground = true };
readerThread.Start();
}
private void StopButtonStreaming()
{
if (readerCts == null) return;
LogManager.Log("MakcuBinary: Stopping button stream.", LogLevel.Debug);
readerCts.Cancel();
readerThread?.Join(200);
readerThread = null;
readerCts.Dispose();
readerCts = null;
}
private void ReadLoop(CancellationToken token)
{
SerialPort? sp;
lock (sync) sp = serial;
if (sp == null) return;
while (!token.IsCancellationRequested)
{
if (!TryReadByte(sp, ReadTimeoutMs, out int b))
continue;
if (b == FrameStart)
{
if (!TryReadByte(sp, ReadTimeoutMs, out int cmdVal)) continue;
if (!TryReadByte(sp, ReadTimeoutMs, out int lenLo)) continue;
if (!TryReadByte(sp, ReadTimeoutMs, out int lenHi)) continue;
int len = lenLo | (lenHi << 8);
if (len < 0) continue;
var payload = new byte[len];
if (!TryReadExact(sp, payload, ReadTimeoutMs)) continue;
if (cmdVal == CmdButtonsStream && len >= 2)
{
ushort mask = (ushort)(payload[0] | (payload[1] << 8));
LogManager.Log($"MakcuBinary: Buttons mask 0x{mask:X4}.", LogLevel.Debug);
ButtonsChanged?.Invoke(mask);
}
continue;
}
if (b == CmdButtonsStream)
{
if (!TryReadByte(sp, ReadTimeoutMs, out int lo)) continue;
if (!TryReadByte(sp, ReadTimeoutMs, out int hi)) continue;
ushort mask = (ushort)(lo | (hi << 8));
LogManager.Log($"MakcuBinary: Buttons mask 0x{mask:X4}.", LogLevel.Debug);
ButtonsChanged?.Invoke(mask);
}
}
}
}
}