TProPCMonitor/LoraGamepad/Models/SerialPort.cs

143 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
using Autolabor;
namespace LoraGamepad.Models;
/// <summary>
/// 串口驱动封装单例模式
/// </summary>
public class SerialPort
{
/// <summary>
/// 串口单例
/// </summary>
public static readonly SerialPort Me = new();
/// <summary>
/// 串口驱动基类
/// </summary>
private readonly SerialBase _serial = new();
private bool _isPortOpen = false;
private Action? _onWriteError;
/// <summary>
/// 串口是否打开属性
/// </summary>
public bool IsPortOpen => _isPortOpen;
/// <summary>
/// 搜索串口列表
/// </summary>
/// <returns></returns>
public static List<SerialDevice> FindPorts()
{
return SerialBase.EnumeratePorts();
}
public void LisenningPort(Action? onWriteError)
{
_onWriteError = onWriteError;
}
/// <summary>
/// 保护性构造函数
/// </summary>
private SerialPort() { }
/// <summary>
/// 打开串口
/// </summary>
/// <param name="port">串口名</param>
/// <param name="baudRate">波特率</param>
/// <param name="timeout">超时时间</param>
public void Open(string port,int baudRate,int timeout)
{
_serial.Port = port;
_serial.Baudrate = baudRate;
_serial.ReadTimeout = timeout;
try
{
_serial.Open();
_isPortOpen = true;
}
catch (SerialBaseException e)
{
Console.WriteLine(e);
}
}
/// <summary>
/// 串口发送
/// </summary>
/// <param name="data">Byte数据</param>
public void Write(byte[] data)
{
try
{
if (Me.IsPortOpen)
{
_serial.Write(data);
}
}
catch (SerialBaseException e)
{
_onWriteError?.Invoke();
Console.WriteLine(e);
}
}
/// <summary>
/// 读取串口
/// </summary>
/// <returns>Byte数组</returns>
public byte[] Read()
{
try
{
return _serial.Read();
}
catch (SerialBaseException e)
{
Console.WriteLine("My Line:" + e);
return Array.Empty<byte>();
}
}
public bool TryRead(out byte[] data)
{
if (_isPortOpen)
{
try
{
data = _serial.Read();
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
data = Array.Empty<byte>();
return false;
}
/// <summary>
/// 关闭串口
/// </summary>
public void Close()
{
try
{
_isPortOpen = false;
_serial.Close();
}
catch (SerialBaseException e)
{
Console.WriteLine(e);
}
}
}