In re-thinking this, I realize that I don't need to wait for bytes. I didn't notice the fact that the wclsyncClient has it's own timeout that I should be able to rely on.
My application needs to periodically read a sensor and provide a live display. The sensor returns a variable length string terminated with a carriage return.
Along with the live display, there are several other user interface items in my application that cause interaction with the Bluetooth device. To prevent multiple commands and responses from getting crossed over Bluetooth I'm using a "wclSyncClient" - the goal is to ensure that one command/response pair is complete before sending the next command. The wclsyncClient should be exactly what I need. I'm relying on the "wclsyncClient.Read" and the fact that is should be waiting for a response (with an associated timeout). However, the wclsyncClient.Read seems to be letting other messages through... as if it isn't really synchronous.
Quite often, I'm finding the "FormClosing" event being handled in the midst of a "wclsyncClient.Read". That would imply that the sync client isn't all that synchronous. It also puts me in a situation where the wclsyncClient is closed while in the middle of the wclsyncClient.Read. Thus hanging the application.
Here's a bit of code as an example. Note: this isn't my actual compiled code. This is just to show the concept of what I'm trying to do:
private void timerHeartbeat_Tick(object sender, EventArgs e)
{
timerHeartbeat.Enabled = false;
byte[] array = Encoding.ASCII.GetBytes("READ");
wclsyncClient.Write(array, (UInt32)array.Length);
String strValue = GetString(100);
timerHeartbeat.Enabled = true;
}
private String GetString(uint uTimeoutMSEC)
{
int nResult;
List<Byte> bList = new List<Byte>();
Byte bTest = (Byte)'\n';
do
{
nResult = wclsyncClient.Read(ref byteCurrent, ref nSize, uTimeoutMSEC);
if (nResult == wcl.wclErrors.WCL_E_SUCCESS)
{
if (byteCurrent[0] == bTest)
{
bFound = true;
}
else
{
bList.Add(byteCurrent[0]);
}
}
} while (!bFound && (nResult == wcl.wclErrors.WCL_E_SUCCESS));
// return as much of the string that was found
Byte[] bArray = bList.ToArray();
return ASCIIEncoding.ASCII.GetString(bArray);
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// Here's the problem... this occurs in the middle of the GetString's execution
// thus closing the client and causing the GetString reading to hang
wclsyncClient.Disconnect();
}
So... is the wclsyncClient.Read really synchronous? How can I prevent events from interrupting my string reading?
Thanks,
- Mark