110,535
社区成员
发帖
与我相关
我的任务
分享
void _serialPort_DataUpSend(object sender, SerialDataReceivedEventArgs e)
{
//禁止接收事件时直接退出
if (ReceiveEventFlag_Power)
{
return;
}
try
{
string readstr = null;
int n = _serialPort.BytesToRead;
byte[] byRecBuff = new byte[n];
_serialPort.Read(byRecBuff, 0, n);
readstr = myconverter.ToString(byRecBuff, 16);
buffer_rece.AddRange(strToToHexByte(readstr));
byte[] CRC_Result = new byte[2];
GetCRC(byRecBuff, ref CRC_Result);
while (buffer_rece.Count >= 8) //此处可以接收数据实时调试下,看看buffer_JZ中的接收数据是否出来完之前有无被覆盖
{
if ((buffer_rece[0] == 0x06) & (buffer_rece[1] == 0x03))
{
if ((CRC_Result[0] == byRecBuff[n - 2]) && (CRC_Result[1] == byRecBuff[n - 1])) //判断奇偶校验码是否正确
{
ReceiveEventFlag_Power=true;
DataReceived(sender, e, byRecBuff);
buffer_rece.RemoveRange(0, 8);
}
}
else
{
ReceiveEventFlag_Power = false;
buffer_rece.RemoveAt(0);
continue;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public void Send_Data_DataUpSend(object sender, SerialDataReceivedEventArgs e, byte[] bits) //modbus协议数据上传事件
{
if (((flag_GJ[0] & 0xFF) == 0) && ((flag_GJ[1] & 0xFF) == 0) && ((flag_GJ[2] & 0xFF) == 0) && ((flag_GJ[3] & 0xFF) == 0) && ((flag_GJ[4] & 0xFF) == 0))
{
send_byte[5] = (byte)(send_byte[5] & 0xFE);
}
else
{
send_byte[5] = (byte)(send_byte[5] | 0x01);
}
byte[] dst = new byte[(int)bits[5] * 2];
//发送故障信息
Buffer.BlockCopy(send_byte, (int)bits[3] * 2, dst, 0, (int)bits[5] * 2);
Send_Data.SendData(Send_Data.GetFrame(bits[0], bits[1], (byte)(bits[5] * 2), dst), 0, (int)bits[5] * 2 + 5);
}
public void SendData(byte[] data, int offset, int count)
{
//禁止接收事件时直接退出
if (ReceiveEventFlag)
{
return;
}
try
{
if (_serialPort.IsOpen)
{
_serialPort.Write(data, offset, count);
ReceiveEventFlag_Power = false;
}
}
catch (Exception ex)
{
throw ex;
}
}