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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM