修复提交
This commit is contained in:
87
linesider_screen_tool/Hepler/SerialPortHepler.cs
Normal file
87
linesider_screen_tool/Hepler/SerialPortHepler.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO.Ports;
|
||||
using System.Text.RegularExpressions;
|
||||
using MQTTnet;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace linesider_screen_tool
|
||||
{
|
||||
public class SerialPortHepler:IDisposable
|
||||
{
|
||||
private SerialPort _serialPort;
|
||||
// 内部缓冲区用于存储接收到的数据
|
||||
private StringBuilder receiveBuffer = new StringBuilder();
|
||||
public event Action<string> DataReceived;
|
||||
|
||||
public SerialPortHepler(string portName,int baudRaate,int parity,int dataBits,int stopBits)
|
||||
{
|
||||
_serialPort = new SerialPort(portName, baudRaate, (Parity)parity, dataBits, (StopBits)stopBits);
|
||||
}
|
||||
|
||||
public async void Open()
|
||||
{
|
||||
if (_serialPort != null && _serialPort.IsOpen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
_serialPort.Open();
|
||||
_serialPort.DataReceived += SerialPort_DataReceived;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
public void Close()
|
||||
{
|
||||
if (_serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
_serialPort.DataReceived -= SerialPort_DataReceived;
|
||||
_serialPort.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
}
|
||||
public void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
||||
{
|
||||
string newData = _serialPort.ReadExisting();
|
||||
receiveBuffer.Append(newData);
|
||||
|
||||
// 处理缓冲区中的数据
|
||||
string bufferContent = receiveBuffer.ToString();
|
||||
string[] lines = Regex.Split(bufferContent, @"\r\n|\n|\r", RegexOptions.None);
|
||||
|
||||
for (int i = 0; i < lines.Length - 1; i++)
|
||||
{
|
||||
string line = lines[i].Trim();
|
||||
if (!string.IsNullOrEmpty(line))
|
||||
DataReceived.Invoke(line); ;
|
||||
}
|
||||
// 将最后一行保留到缓冲区中
|
||||
receiveBuffer.Clear();
|
||||
if (lines.Length > 0)
|
||||
{
|
||||
receiveBuffer.Append(lines[lines.Length - 1]);
|
||||
}
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
Close();
|
||||
_serialPort?.Dispose();
|
||||
_serialPort = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user