|
1 | 1 | using HidLibrary; |
| 2 | +using System.Collections.Generic; |
2 | 3 | using System.Linq; |
3 | 4 | using System.Text; |
4 | 5 | using System.Threading.Tasks; |
@@ -54,29 +55,34 @@ private async Task<HidReport> ReadReportAsync() |
54 | 55 | return await Task.Run(() => HidDevice.ReadReport()); |
55 | 56 | } |
56 | 57 |
|
57 | | - private string currentLine = ""; |
| 58 | + private List<byte> currentLine = new(); |
58 | 59 |
|
59 | 60 | private void HidDeviceReportEvent(HidReport report) |
60 | 61 | { |
61 | 62 | if (HidDevice.IsConnected) |
62 | 63 | { |
63 | 64 | // Check if we have a completed line queued |
64 | | - int lineEnd = currentLine.IndexOf('\n'); |
| 65 | + int lineEnd = currentLine.IndexOf((byte)'\n'); |
65 | 66 | if (lineEnd == -1) |
66 | 67 | { |
67 | 68 | // Partial line or nothing - append incoming report to current line |
68 | | - string reportString = Encoding.UTF8.GetString(report.Data).Trim('\0'); |
69 | | - currentLine += reportString; |
| 69 | + foreach (byte b in report.Data) |
| 70 | + { |
| 71 | + // Trim trailing null bytes |
| 72 | + if (b == 0) break; |
| 73 | + currentLine.Add(b); |
| 74 | + } |
70 | 75 | } |
71 | 76 |
|
72 | 77 | // Check again for a completed line |
73 | | - lineEnd = currentLine.IndexOf('\n'); |
| 78 | + lineEnd = currentLine.IndexOf((byte)'\n'); |
74 | 79 | while (lineEnd >= 0) |
75 | 80 | { |
76 | 81 | // Fire delegate with completed lines until we have none left |
77 | | - string completedLine = currentLine[..lineEnd]; |
78 | | - currentLine = currentLine[(lineEnd + 1)..]; |
79 | | - lineEnd = currentLine.IndexOf('\n'); |
| 82 | + // Only convert to string at the last possible moment in case there is a UTF-8 sequence split across reports |
| 83 | + string completedLine = Encoding.UTF8.GetString(currentLine.GetRange(0, lineEnd).ToArray()); |
| 84 | + currentLine = currentLine.Skip(lineEnd + 1).ToList(); |
| 85 | + lineEnd = currentLine.IndexOf((byte)'\n'); |
80 | 86 | consoleReportReceived?.Invoke(this, completedLine); |
81 | 87 | } |
82 | 88 |
|
|
0 commit comments