Skip to content

Commit

Permalink
Fix first write after connect/open failed
Browse files Browse the repository at this point in the history
Windows (or my HID device) needs an ~200ms delay for the first write to succeed.
  • Loading branch information
popy2k14 authored Jun 25, 2024
1 parent 5f18fac commit da6cfcb
Showing 1 changed file with 33 additions and 7 deletions.
40 changes: 33 additions & 7 deletions USB/Classes/DeviceCommunication.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using UsbHid.USB.Classes.DllWrappers;
Expand All @@ -21,12 +22,37 @@ public static bool WriteRawReportToDevice(byte[] outputReportBuffer, ref DeviceI
try
{
// Set an output report via interrupt to the device
var success = Kernel32.WriteFile(
deviceInformation.WriteHandle,
outputReportBuffer,
outputReportBuffer.Length,
ref numberOfBytesWritten,
IntPtr.Zero);
bool success = false;

//do retries because first write to an USB hid device (ex.: Hopt869T) fails
//after waiting and retries it works!? What the heck Microsoft?
for (int i = 0; i < 5; i++)
{
success = Kernel32.WriteFile(
deviceInformation.WriteHandle,
outputReportBuffer,
outputReportBuffer.Length,
ref numberOfBytesWritten,
IntPtr.Zero);

//did we succeed?
if (success)
{
//write succeeded -> break retry loop
break;
}
else
{
// We did not succeed, GetLastError may give more information about why not.
int dwError = Marshal.GetLastWin32Error();
//Check for 0x000003e3 = 995 dec windows error, which means: ERROR_OPERATION_ABORTED
// The I/ O operation has been aborted because of either a thread exit or an application request.
if (dwError == 0x000003e3)
{
Thread.Sleep(100);
}
}
}

return success;
}
Expand Down

0 comments on commit da6cfcb

Please sign in to comment.