tags:

views:

105

answers:

1

I am using Serial port to receive the messages. The below function is running in a thread. When i debug i find that the thread is running properly. But "if (sp.IsOpen)" is always false, due to which the code is not executing inside the IF condition at all. It says the Port is closed.

I will be having multiple serial ports in my system and i will not know, which port will receive the message. So i need to listen to all the ports in one Thread.

How can i solve my problem here ?

 private void ListenerPorts()
    {

        log.Info("Listening Thread Started");

        while (true)
        {
            //foreach (SerialPort sp in storeport)
            foreach (SerialPort sp in comPortsList)
            {

                if (sp.IsOpen)
                {
                    sp.ReadTimeout = readTimeoutInMs;
                    sp.WriteTimeout = writeTimeoutInMs;

                    try
                    {
                        string msg = sp.ReadLine();
                        this.GetMessageRichTextBox("Message : " + msg + "\n");
                        sp.WriteLine(sp.PortName);

                        if (msg.Contains("COM"))
                        {
                            // is AutoScan
                            receiverPortName = sp.ReadLine();
                            this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + msg + "\n");
                        }
                        else
                        {
                            //standalone is uppercase
                            ReceiverPortName = sp.ReadLine();
                            this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + ReceiverPortName + "\n");

                        }
                    }

                    catch (Exception ex)
                    {
                        // no data
                        System.Diagnostics.Debug.WriteLine(sp.PortName + " : " + ex.Message);

                    }
                }           
            }
        }
    }
A: 

Where's your initialization code for the serial ports? And in particular the line SerialPort.Open();?

Take a look at using

SerialPort.DataReceived += 
  new SerialDataReceivedEventHandler(SerialDataReceivedEventHandler);

to receive the data from them instead.

Hightechrider
So, do mean that i need to open all the ports in my system for receiving the messages ?
Anuya
Yes. See http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx
Hightechrider
You could instead use a separate thread per port (instead of the DataReceived event handler) but you'll still need to open the port before you can use it.
Hightechrider