You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
3.9 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Threading;
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2025 WenJY 保留所有权利。
* CLR版本4.0.30319.42000
* 机器名称T14-GEN3-7895
* 命名空间SlnMesnac.Business
* 唯一标识a0333022-6db6-4dd1-8aa7-bc46b57b6050
*
* 创建者WenJY
* 电子邮箱:
* 创建时间2025-06-23 13:50:07
* 版本V1.0.0
* 描述:
*
*--------------------------------------------------------------------
* 修改人:
* 时间:
* 修改说明:
*
* 版本V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business
{
public class SerialBusiness
{
private SerialPort serialPort;
public SerialBusiness()
{
serialPort = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
//serialPort.DataReceived += SerialPort_DataReceived;
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 数据接收事件处理
// 这里可以根据需要处理接收到的数据
}
public void OpenPort()
{
try
{
if (!serialPort.IsOpen)
{
serialPort.Open();
}
}
catch (Exception ex)
{
Console.WriteLine($"打开串口时出错: {ex.Message}");
}
}
public void ClosePort()
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
}
private byte[] receiveBuffer = new byte[1024];
private int bufferIndex = 0;
public byte[] SendDataAndWaitForResponse(byte[] dataToSend)
{
if (!serialPort.IsOpen)
{
throw new InvalidOperationException("串口未打开。");
}
// 清空接收缓冲区
serialPort.DiscardInBuffer();
bufferIndex = 0;
byte[] receivedData = new byte[0];
AutoResetEvent dataReceivedEvent = new AutoResetEvent(false);
serialPort.DataReceived += (sender, e) =>
{
int bytesToRead = serialPort.BytesToRead;
serialPort.Read(receiveBuffer, bufferIndex, bytesToRead);
bufferIndex += bytesToRead;
if (bufferIndex >= 5)
{
receivedData = new byte[bufferIndex];
Array.Copy(receiveBuffer, receivedData, bufferIndex);
dataReceivedEvent.Set();
}
};
try
{
// 发送数据
serialPort.Write(dataToSend, 0, dataToSend.Length);
// 等待数据返回,最多等待 5 秒
if (!dataReceivedEvent.WaitOne(5000))
{
throw new TimeoutException("在 5 秒内未收到响应。");
}
return receivedData;
}
finally
{
// 移除事件处理程序
serialPort.DataReceived -= (sender, e) =>
{
int bytesToRead = serialPort.BytesToRead;
serialPort.Read(receiveBuffer, bufferIndex, bytesToRead);
bufferIndex += bytesToRead;
if (bufferIndex >= 10)
{
receivedData = new byte[bufferIndex];
Array.Copy(receiveBuffer, receivedData, bufferIndex);
dataReceivedEvent.Set();
}
};
}
}
}
}