SerialPort - How to send a message and await a reply?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JamesA
    New Member
    • Mar 2010
    • 1

    SerialPort - How to send a message and await a reply?

    I’ve written a program in C# which scans a network of devices connected to the serial port.
    I use a thread to send a message addressed to a external device then I use ManualResetEven t.WaitOne(200) to pause the thread and wait for a reply. If a correct response is received from the serial port, an event is fired which restarts the scan thread with ManualResetEven t.Set(). When a correct response is received or the ManualResetEven t times out, I increment the address and scan for the next device.

    This works fine until another program loads up the processor, which can cause the SerialPort DataReceived event to be delayed by over 2 seconds and the ManualResetEven t to time out therefore missing a valid response from a device.

    Pseudo code:

    Code:
    // Scan network method
    {
        private void  Scan (void)
        {
            MessageFilter.MessageFilterEvent += new MessageFilter.MessageReceivedHandler(MessageFilter_MessageFilterEvent);
    
            for(int address = 1; address <= 127; address ++)
            {
    	send serial message();
    	ManualResetEven.WaitOne(200);
    	if(message was received)
    	{
    	    Device found
    	}
    	ManualResetEvent.Reset();
           }
        }
    
        private void MessageFilter_MessageFilterEvent(object sender,MessageReceivedEventArgs e)
        {
            ManualResetEvent.Set();
        }
    }
    
    // SerialPort received event
    private void Serial_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        Process data
        if(this is a valid message)
        {
            Trigger MessageReceivedEvent event
        }
    }
    
    // Valid message received event
    private void MessageReceivedEvent(object sender, MessageReceivedEventArgs e)
    {
        // Filter messages
        if(received message == required message)
        }
        	Trigger MessageFilter_MessageFilterEvent event
        }
    }

    Can anyone think of a better way of writing the send – await response process that doesn’t rely on processor speed?

    Thanks in advance,
    James
    Last edited by tlhintoq; Mar 13 '10, 05:19 PM. Reason: [CODE] ...Your code goes between code tags [/CODE]
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

    Comment

    Working...