Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Windows] Update HidDeviceReportEvent() #447

Merged
merged 1 commit into from
Feb 16, 2024
Merged
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
22 changes: 14 additions & 8 deletions windows/QMK Toolbox/HidConsole/HidConsoleDevice.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using HidLibrary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Expand Down Expand Up @@ -54,29 +55,34 @@ private async Task<HidReport> ReadReportAsync()
return await Task.Run(() => HidDevice.ReadReport());
}

private string currentLine = "";
private List<byte> currentLine = new();

private void HidDeviceReportEvent(HidReport report)
{
if (HidDevice.IsConnected)
{
// Check if we have a completed line queued
int lineEnd = currentLine.IndexOf('\n');
int lineEnd = currentLine.IndexOf((byte)'\n');
if (lineEnd == -1)
{
// Partial line or nothing - append incoming report to current line
string reportString = Encoding.UTF8.GetString(report.Data).Trim('\0');
currentLine += reportString;
foreach (byte b in report.Data)
{
// Trim trailing null bytes
if (b == 0) break;
currentLine.Add(b);
}
}

// Check again for a completed line
lineEnd = currentLine.IndexOf('\n');
lineEnd = currentLine.IndexOf((byte)'\n');
while (lineEnd >= 0)
{
// Fire delegate with completed lines until we have none left
string completedLine = currentLine[..lineEnd];
currentLine = currentLine[(lineEnd + 1)..];
lineEnd = currentLine.IndexOf('\n');
// Only convert to string at the last possible moment in case there is a UTF-8 sequence split across reports
string completedLine = Encoding.UTF8.GetString(currentLine.GetRange(0, lineEnd).ToArray());
currentLine = currentLine.Skip(lineEnd + 1).ToList();
lineEnd = currentLine.IndexOf((byte)'\n');
consoleReportReceived?.Invoke(this, completedLine);
}

Expand Down