Reputation: 2654
Is there any possibility to read Data from 2 RS232 Ports parallel?
It seems, that when i have 2 DataReceived-Events there are blocking each other. I have also tried to set the SerialPort.ReceivedBytesThreshold to a value of 50/100
class DataCollector
{
private SerialPort _serialPort;
List<String> Data;
private bool _finished = false;
private bool _handshake = true;
public DataCollector(SerialPort serialPort, bool handshake=true)
{
Data = new List<String>();
_serialPort = serialPort;
_serialPort.DataReceived += SerialPortDataReceived;
_handshake = handshake;
if (_serialPort.IsOpen)
{
_serialPort.DiscardInBuffer();
}
}
~DataCollector()
{
if (_serialPort.IsOpen)
{
_serialPort.DiscardInBuffer();
}
Data.Clear();
}
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (_handshake == false)
{
String str =_serialPort.ReadLine();
str.Insert(str.Length, "\n");
Data.Add(str);
if (Data.Count == 48)
{
_finished = true;
}
}
else
{
Char readedByte = (char)_serialPort.ReadByte();
if ((readedByte != (char)5) && Data.Count == 0)
{
return;
}
if (readedByte.CompareTo((char)2) == 0)
{
readLine();
sendAck();
}
else if (readedByte.CompareTo((char)5) == 0)
{
Data.Add(((char)5).ToString());
sendAck();
}
else if (readedByte == (char)4)
{
_finished = true;
}
}
private void sendAck()
{
if (_serialPort.IsOpen )
{
Byte[] bytes = {6};
_serialPort.Write(bytes,0,1);
}
}
private void readLine(){
String str = _serialPort.ReadLine();
Data.Add(str);
}
}
There are 2 defined in the Main:
_inputCollector = new DataCollector(_RS232Input);
_inputSecondCollector = new DataCollector(_RS232SecondInput, false);
Upvotes: 0
Views: 1231
Reputation: 24529
Comment
I would seriously reconsider that implementation of only having a single thread - you should realistically have two separate threads each dealing with its own serial port (as currently, the program will 'freeze' if a large message was passed in - meaning the second port will be 'unusable' until this msg has finished).
Answer
Your system is currently running on a single thread. But implementing a muti-threading system - one which will listen to the first port, and another to listen to the second port. That way, they can both work at the same time.
Currently, (on this single thread) if data is received on one port, (and the other receives also) the thread will 'freeze' until the first message has been received/dealt with - and THEN will read the second port (that is, if it has not already timed out). So by using two threads, both ports can be written/read simultaneously (or, seem to be anyway).
Upvotes: 1