Reputation: 5373
I'm comunicating with the device using SerialPort. The device has RS-485, on the other side (PC) is RS-232 (virtual port). The device works, sends and receives data correctly.
The problem is, the DataReceived event sometimes isn't fired. I send data to the device using System.Timer, once every 10 seconds. Most of the times it works fine, but every 1-10 minutes I don't get a response, then, after 2-4 more times the DataReceived event is finally fired and I get a cluster of data (everything I previously "asked" for is in the buffer).
My question is: How is that possible?
I can't put code example here, I'm sorry, but there is no multithreading in my app (only Main thread and the threads with Timer_Elapsed and DataReceived events, I think they're raised on separate threads), my DataReceived event is processed fast and shouldn't be raised in parallel (10 seconds is long enough, the device response time is below 1 second). If I use Thread.Sleep, it is in places where I'm sure it won't interfare with anything.
It may be more of a hardware than software problem, because the COM port is bahaving in the similar way when I test it using other applications (one of them, which the manufacturer of the device provided to test the connection, doesn't look as if it was written in C#). But I'm not that good with hardware. Maybe there's something wrong with the PC, or the COM port (it's not build-in but external)? Or can it be a Operating System related thing (my app is a Windows Service running under Windows Server 2003).
Upvotes: 1
Views: 2946
Reputation: 5373
It turned out that it was a hardware problem.
The connection betwen devices looks like this: Device <> RS-485 <> Converter1 <> LAN <> Converter2 <> RS-232 <> Computer <> virtual COM
Converter1 appears to be malfunctioning, it clusters and holds the data my device sends to it. Now I know what is wrong I can let competent people take care of it :)
Thanks @Matthew Rodatus for your help. Your answer in roundabout way guided me to check what exactly and when exactly is coming to my COM.
Upvotes: 1
Reputation: 1461
It sounds to me like the buffer isn't being flushed when you expect.
The DataReceived event is not guaranteed to be raised for every byte received. Use the BytesToRead property to determine how much data is left to be read in the buffer.
See http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx
(Btw, the DataReceived event is indeed raised on a secondary thread.)
Have you tried tweaking the ReadBufferSize and ReceivedBytesThreshold properties? That's where I would start investigating. Do you know the approximate size of the messages? You probably want to set the ReceivedBytesThreshold property to just below the minimum message size you expect to receive from the device. Then, you may need a short period of busy waiting to get the last few bytes to complete the message.
Upvotes: 3