Reputation: 973
I am reading a Bluetooth COM port, getting data from a microcontroller. After initializing the port, I am using this to read the port:
while(1)
if(WaitCommEvent(com_hnd, &dwEventMask, NULL))
This works fine, but if I close the COM port, the program will wait forever in this loop, without detecting the fact that the COM port is gone (I have an else for that if(), where I check for errors).
How can I check and see if it still open?
Upvotes: 1
Views: 1309
Reputation: 214880
As already suggested in comments, you will probably want some external way to stop the waiting, like an event + WaitForMultipleObjects(). You can also wait for the actual COM port handle obtained from CreateFile.
Do you actually need to use WaitCommEvent? As far as I know, you should only need that function if you are using handshaking signals and other such oddities. You can use ReadFile if you are only interested in the data. In my experience, that function is more reliable.
I have worked with similar COM port devices and the most robust way to spot that they have been disconnected seems to be checking the result of ReadFile:
BOOL result;
result = ReadFile(...);
if(result == FALSE)
{
DWORD last_error = GetLastError();
if(last_error == ERROR_OPERATION_ABORTED) // disconnected ?
{
close(); // close the port
}
}
I'm of course not sure whether or not this will work in your specific case, but I'm using this method in some production code that has ended up with multiple crappy USB-to-serial adapters.
Upvotes: 2