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

2021-06-19 01:09

阅读:382

标签:except   mode   str   amp   auto   temp   buffer   else   数据对象   

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【方法:连接】
///


/// 连接
///

/// 连接结果
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【方法:关闭连接】
///


/// 关闭连接
///

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【方法:数据校验】
///


/// 数据校验
///

/// 待校验数据
///
public bool TestParity(byte[] pReceiveData,int datalength)
{
if (pReceiveData != null && pReceiveData.Length > datalength)
{
int sum = 0;
for (int i = 2; i {
sum += (int)pReceiveData[i];
}
if ((sum % 256) == (int)pReceiveData[pReceiveData.Length - 1])
return true;
}
return false;
}
#endregion

 

#region【方法:数据对象转为字节流】
///


/// 数据对象转为字节流
///

public byte[] TestModelToByte(int pOperateType)
{
switch (pOperateType)
{
case 0x01:
return ModelToByteByNull(0x01);
default:
return null;
}
}
#endregion

 

#region【方法:初始化/获取反馈】
///


/// 初始化/获取反馈
///

///
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 sum += data[i];

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

return data;
}
#endregion

 

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

标签:except   mode   str   amp   auto   temp   buffer   else   数据对象   

原文地址:https://www.cnblogs.com/yanranziruo/p/10291620.html


评论


亲,登录后才可以留言!