Hi there, I am building a class library for modbus and serial connections, I need to return an array of bytes back but when using the DataReceived event from System.IO.Ports I cannot return any since it's type is void. Also I am noticing that the DataReceived is not firing. The following is my code:
public void ConnectSerialModBus_Loopback(string COM, int baud, int meter_address, int function, int Code_HighByte, int Code_LowByte, int data_high_byte, int data_low_byte)
{
SerialPort port = new SerialPort(COM, baud);
try
{
if (!(port.IsOpen))
{
byte[] sendPacket = BuildPacket(meter_address, function, Code_HighByte, Code_LowByte, data_high_byte, data_low_byte);
double dataBytes = 2.0;
port.Open();
port.RtsEnable = false;//rts = high
port.Handshake = Handshake.None;
//SEND PACKET TO DEVICE
port.Write(sendPacket, 0, sendPacket.Length);
#region RECEIVE DATA FROM SERIAL
//MAKE DELAY TO SEND
Thread.Sleep(10);
port.RtsEnable = true;
//MAKE DELAY TO RECEIVE
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
//Thread.Sleep(CalculateDelay(dataBytes)+90);
port.Close();
port.Dispose();
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (port != null)
{
if (port.IsOpen)
{
port.Close();
}
port.Dispose();
}
}
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
byte[] readingbyte = new byte[port.BytesToRead];
if (port.BytesToRead > 0)
{
port.Read(readingbyte, 0, readingbyte.Length);
}
}
in some way I want to return the bytes received either from the port_DataReceived
or from the ConnectSerialModBus_Loopback
also the DataReceived is not firing. Please help this is very urgent