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:
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
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
Comment