C#仪器串口自动重连操作

private bool AutoConnectTimer()
{
int pBurante = 115200;
string[] ports = SerialPort.GetPortNames();
foreach (string itemprot in ports)
{
if (ConnectClient(itemprot, pBurante))
{
GCDataCache.ComStatus = "正在检测" + itemprot;
byte[] data = null;

//获取初始化通讯协议
byte[] send = TestModelToByte(0x01);
if (send == null || send.Length == 0) continue;
//下发指令并获得反馈数据
data = Communicate(send);
Thread.Sleep(200);
int trycount = 0;


while (data == null || data.Length == 0 || !TestParity(data, 35))
{
if (trycount >= 3)
{
break;
}
data = Communicate(send);
trycount++;
}

if (data!=null)
{
if (data.Length > 0 && TestParity(data,30))
{
GCDataCache.ComStatus = "当前连接端口"+ itemprot;
return true;
}

}

//如已打开串口,协议未通过,记得关闭串口

CloseConnect();
}
}

if (ports.Length == 0)
{
GCDataCache.ComStatus = "未连接" ;
}
return false;
}
#endregion

#region【方法:连接】
/// <summary>
/// 连接
/// </summary>
/// <returns>连接结果</returns>
public bool ConnectClient(string portname, int pBurante)
{
try
{
if (m_SerialPort != null && m_SerialPort.IsOpen)
return true;
else
{
CloseConnect();
}
if (m_SerialPort == null)
m_SerialPort = new SerialPort(portname, pBurante);
m_SerialPort.Open();
m_SerialPort.WriteTimeout = 2000;
m_SerialPort.ReadTimeout = 2000;
Thread.Sleep(200);
return true;
}
catch
{
return false;
}
}
#endregion

#region【方法:关闭连接】
/// <summary>
/// 关闭连接
/// </summary>
private void CloseConnect()
{
try
{
if (m_SerialPort != null)
{
if (m_SerialPort.IsOpen)
{
m_SerialPort.DiscardInBuffer();
m_SerialPort.DiscardOutBuffer();
m_SerialPort.Close();
}
}
}
catch (Exception ex)
{

}
finally
{
m_SerialPort = null;
}
}
#endregion


#region【方法:数据校验】
/// <summary>
/// 数据校验
/// </summary>
/// <param name="pReceiveData">待校验数据</param>
/// <returns></returns>
public bool TestParity(byte[] pReceiveData,int datalength)
{
if (pReceiveData != null && pReceiveData.Length > datalength)
{
int sum = 0;
for (int i = 2; i < pReceiveData.Length - 1; i++)
{
sum += (int)pReceiveData[i];
}
if ((sum % 256) == (int)pReceiveData[pReceiveData.Length - 1])
return true;
}
return false;
}
#endregion

#region【方法:数据对象转为字节流】
/// <summary>
/// 数据对象转为字节流
/// </summary>
public byte[] TestModelToByte(int pOperateType)
{
switch (pOperateType)
{
case 0x01:
return ModelToByteByNull(0x01);
default:
return null;
}
}
#endregion

#region【方法:初始化/获取反馈】
/// <summary>
/// 初始化/获取反馈
/// </summary>
/// <returns></returns>
private byte[] ModelToByteByNull(int pOperateType)
{
byte[] data = new byte[7];
//帧头
data[0] = 0x4D;
data[1] = 0x03;
data[2] = (byte)pOperateType;
data[3] = 0x00;
data[4] = 0x00;
data[5] = 0x00;
int sum = 0;
for (int i = 2; i < data.Length - 1; i++)
sum += data[i];

data[data.Length - 1] = (byte)(sum % 256);

return data;
}
#endregion

猜你喜欢

转载自www.cnblogs.com/yanranziruo/p/10291620.html