This is how I typically do it.
Regards,
John.
//This is a BackgroundWorker Thread
private void bwkUSB_DoWork(object sender, DoWorkEventArgs e)
{
byte[] testarray = new byte[2];
bool weareconnected = false;
do //Until StopUSBRead
{
do //Until weareconnected
{
if (!hid1.MyDeviceDetected)
hid1.FindTheHid();
if (hid1.MyDeviceDetected)
{
//if we can write then we are connected
//the device knows to ignore this data
testarray[0] = Convert.ToByte(hid_interface.COMMANDenum.areWeConnectedenum); //no responce from this
testarray[1] = 0; //data bytes to follow
if (hid1.OutputToDevice(testarray)) //true for successfull write
{
weareconnected = true;
}
else
{
weareconnected = false;
hid1.MyDeviceDetected = false;
mfref.AccessFormMarshal("rtbMonitor", "We are not connected, will try again:", Color.Black);
//Thread.Sleep(2000);
}
}
else
{
mfref.AccessFormMarshal("rtbMonitor", "Failled to connect, will try again:", Color.Black);
Thread.Sleep(2000); //before we try again
}
if (hid1.StopUSBRead)
{
break;
}
} while (!weareconnected && !hid1.StopUSBRead);
if (hid1.StopUSBRead)
break;
for (int times = 0; times < 10; times++) //only check connection every so many loops
{
byte[] receivearray = new byte[hid1.Capabilities.InputReportByteLength];
//a small read timeout so that we can check for sends more often
if (hid1.InputFromDevice(ref receivearray, 200)) //values less than 10 dont mean much
{
times = 0; //reset it as we are obviously connected
//Do something with the data
AccessFormMarshal("rtbMonitor", "Some Data was Received.", Color.Black);
}
//else
//{
// AccessFormMarshal("rtbMonitor", "No Data was Received.", Color.Black);
//}
if (hid1.StopUSBRead) //so that other code can inform this tread to stop
{
Debug.WriteLine("bwkUSB Stopped");
break;
}
}
} while (!hid1.StopUSBRead);
hid1.StopUSBRead = false;
mfref.AccessFormMarshal("rtbMonitor", "BackgroundWorker bwkUSB is closing.", Color.Black);
}