我正在为 modbus 和串行连接构建一个类库,我需要返回一个字节数组,但是当使用 System.IO.Ports 中的 DataReceived 事件时,我无法返回任何内容,因为它的类型是无效的。另外,我注意到 DataReceived 没有触发。以下是我的代码:
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);
}
}
以某种方式,我想返回从DataReceived 未触发的port_DataReceived
或从DataReceived 接收的字节。ConnectSerialModBus_Loopback
请帮助这是非常紧急的