Skip to content

Instantly share code, notes, and snippets.

@sverrirs
Created October 13, 2015 19:54
Show Gist options
  • Save sverrirs/dc0f27873cf5f0853040 to your computer and use it in GitHub Desktop.
Save sverrirs/dc0f27873cf5f0853040 to your computer and use it in GitHub Desktop.
class Program
{
static BackgroundWorker _bgWorker = new BackgroundWorker();
static ManualResetEvent _terminateSignal = new ManualResetEvent(false);
static void Main(string[] args)
{
_bgWorker.DoWork += BgWorkerOnDoWork;
USBDevice device = null;
try
{
device = USBDevice.GetSingleDevice("{EF5B294C-E3E3-4914-B5BB-037866450C41}");
// Start listening to the input channel
_bgWorker.RunWorkerAsync(device);
Console.WriteLine("Waiting on main thread");
_terminateSignal.WaitOne(Timeout.Infinite);
Console.WriteLine("Resuming main thread and exiting");
}
finally
{
device?.Dispose();
}
Console.ReadLine();
}
private static void BgWorkerOnDoWork(object sender, DoWorkEventArgs e)
{
var device = e.Argument as USBDevice;
var dInterface = device?.Interfaces[0];
if (dInterface?.InPipe != null)
{
byte[] inbuffer = new byte[6];
byte[] prevbuffer = new byte[6];
while (true)
{
Task<int> t = Task<int>.Factory.FromAsync(dInterface.InPipe.BeginRead, dInterface.InPipe.EndRead, inbuffer, 0, inbuffer.Length, null);
t.ContinueWith(result =>
{
// Only print if different
if (inbuffer.SequenceEqual(prevbuffer))
return;
inbuffer.CopyTo(prevbuffer, 0);
Console.WriteLine(BitConverter.ToString(inbuffer));
});
// Sleep for 250msec to allow for processing
Thread.Sleep(250);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment