I also need to work with serial ports, and believe me, they hurt. My device connection verification method usually revolves around issuing a polling command. Although the method may work, I cannot help, but I do not want to use the while loop when there is enough event.
The .NET serial port class offers several useful events:
Serial.DataReceived Serial.ErrorReceived and Serial.Write
Usually I did a polling command at a given interval to make sure that the device is connected. When the device responds, it DataReceived event, and you can process the response accordingly (along with any other necessary data). This can be used in conjunction with a simple timer or an added variable during a response. Note that you will need to set the ReadTimeout and WriteTimeout values โโaccordingly. This, along with the ReadExisting and / or ReadLine , may be useful in your DataReceived event handler.
So, we summarize (in pseudo-code)
Send Polling command, Start Timer Timer to CountDown for a specified time If Timer fires, then assume no response If DataRecieved fires (and expected response) assume connection (of course handle any specific Exceptions (eg TimeOutException, InvalidOperationException)
Simon source share