C# Serial Port Check if Device is Connected -


i've been working serialport class lot lately. i'm trying figure out proper way check if device connected comm port application uses. there proper way check if device connected comm port? current method follows:

            while (isreading == true)             {                 try                 {                     received += serialport.readexisting();                      if (received.contains('>'))                         isreading = false;                 }                 catch (exception e)                 {                  }                 if (tick == 10000)                     if (received == "")                     {                         console.writeline("no data received. device isn't connected.");                         isreading = false;                     }                 tick++;             }             console.writeline(received); 

it works feel it's little hacky , unreliable. can keep if need i'd if there's proper alternative doing this.

edit: have set tick value 10,000 ensure it's reliable. otherwise fail receive data on occasion. setting 1000 or 5000 unreliable. then, it's not guaranteed reliable across multiple machines.

i need work serial ports, , believe me pain. method check if device connected revolves around issuing polling command. while method may work, cant reluctant use while loop when event suffice.

the .net serial port class offers useful events:

serial.datareceived serial.errorreceived , serial.write

usually issue polling command @ specified interval ensure device connected. when device responds fire datareceived event, , can deal response accordingly (along other neccessary data). can used in conjunction simple timer or incremented variable time response. note need set readtimeout , writetimeout value appropriately. this, along readexisting and/or readline method may of use in datareceived event handler.

so, summarize, (in pseudo code)

send polling command, start timer timer countdown specified time if timer fires, assume no response if datarecieved fires (and expected response) assume connection (of course handle specific exceptions (e.g timeoutexception, invalidoperationexception) 

Comments