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