1

I have application that connects to a controller via serial port as well as by Ethernet. Controller continuously throws data to PC. I am writing application in C#. I have created SerialPort object in c# and receiving data in dataReceived method. Similarly for Ethernet I have used TCPListener and its method startAcceptClient to accept connections from client.

Now, my question is if the controller is powered off or the cable removed from the PC; How to detect these events in the application?

KSK
  • 65
  • 1
  • 9
  • These are two different questions. RS232 (Serial Port) **can** detect broken layer 0. TCP/IP cannot. Only chance for TCP is to try to write which would result in IOException if the connection is broken. A good hint would be to track frequency of incoming messages. If you detect a severe drop in frequency you could trigger an investigation regarding connection outage. – Fildor Jan 25 '18 at 10:52
  • Thanks for prompt response. Then how to detect in Serial Port case – KSK Jan 25 '18 at 10:54
  • 1
    For Serial Port you may have a look into here: https://stackoverflow.com/q/13408476/982149 – Fildor Jan 25 '18 at 10:57
  • 1
    You'd expect the PinChanged event to fire to tell you that the DsrChanged handshake signal turned off. It is not 100% reliable, serial devices don't always turn it on and a disconnected long rs-232 cable can act like an antenna and pick up electrical noise. By far the best way to operate a serial device is to never mess with it. – Hans Passant Jan 25 '18 at 14:34

1 Answers1

1

Im not that familiar with the TCPListener but for the SerialPort i use a timer, and each tick i check if the port is still open

private void ComTimer_Tick(object sender, EventArgs e)
    {
        if (SerialPort.IsOpen)
        {
            dostuff
        }
        else if (!SerialPort.IsOpen)
        {
            ComCheckTimer.Stop();
            MessageBox.Show("Connection lost"); 
    }
}

And for the timer

ComCheckTimer = new Timer();
ComCheckTimer.Tick += new EventHandler(ComTimer_Tick);
ComCheckTimer.Interval = 1000;

This creates a timer that ticks every 1000 milliseconds

FancyLord
  • 88
  • 13