Hello,
I am looking for a good way to query the serial port.
Inputstring
When I receive S and E, the message is complete.
If I receive S and E does not come after n time, timeout message to the operator.
How can I reach the goal, how do I solve the timeout?
When S comes I have to start.
If timeout I have to empty the buffer.
The string, I can receive the message. That is good. The timeout is the problem.
How can I set an existing array to default to 0, like memset in C++?
My trials
public byte BreakCondition { get; } Byte 13, can be also Byte 5
ASerialPort = new SerialPort(ConfigRS232.PortName, this.ConfigRS232.BaudRate, ConfigRS232.Parity, ConfigRS232.DataBits, ConfigRS232.StopBits);
ASerialPort.Handshake = ConfigRS232.Handshake;
ASerialPort.DataReceived += ReadDataFromSerialPort;
ASerialPort.Open();
private void ReadDataFromSerialPort(object sender, SerialDataReceivedEventArgs e)
{
try
{
DataToReceive += ASerialPort.ReadExisting();
byte[] bytesReceived = Encoding.ASCII.GetBytes(DataToReceive);
byte[] bytesDestination = new byte[DataToReceive.Length];
int i = 0;
int iStart = 0;
bool startCharacter = false;
bool endCharacter = false;
foreach (var item in bytesReceived)
{
i++;
if (startCharacter == false)
{
if (Convert.ToChar(item) == 'P')
{
startCharacter = true;
iStart = i;
}
continue;
}
if (item == BreakCondition)
{
endCharacter = true;
break;
}
}
if (endCharacter)
{
Buffer.BlockCopy(bytesReceived, iStart, bytesDestination, 0, i - iStart);
string program = Encoding.UTF8.GetString(bytesDestination, 0, i - iStart);
EvHaContentReceivedTrigger?.Invoke(this, program );
DataToReceive = "";
//EvNewMessageReceived.Set();
ASerialPort?.DiscardInBuffer();
ASerialPort?.DiscardOutBuffer();
}
}
catch (Exception ex)
{
throw new ArgumentException($"COM port 'ReadDataFromSerialPort' {ex.Message + ex.StackTrace}");
}
}