using System;
using System.ComponentModel;
using System.IO.Ports;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace YSDetection
{
public class SerialPortBase
{
private object _lock = new object();
///
/// 串口对象
///
private SerialPort _serialPort = null;
public event Action OnDataReceived;
public void Init(string port)
{
if (_serialPort == null)
{
lock (_lock)
{
if (_serialPort == null)
{
_serialPort = new SerialPort(port);
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits =8;
_serialPort.StopBits = StopBits.One;
_serialPort.DataReceived -= SerialPort_DataReceived;
_serialPort.DataReceived += SerialPort_DataReceived;
}
}
}
}
private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int count = _serialPort.BytesToRead;
byte[] buffer = new byte[count];
var rCount = Read(buffer, 0, count);
if (count != rCount)
{
return;
}
//Task.Run(async () =>
//{
// if (BytesCompare(buffer, _triggerdData))
// {
// if (IConfig.TriggerDelay > 0)
// {
// await Task.Delay(IConfig.TriggerDelay);
// }
// // OnTriggered?.Invoke();
// }
// else if (BytesCompare(buffer, _disconnectedData))
// {
// // OnDisconnected?.Invoke();
// }
//});
Task.Run(() =>
{
//if(count==9)
OnDataReceived?.Invoke(buffer);
});
}
private bool BytesCompare(byte[] b1, byte[] b2)
{
if (b1 == null || b2 == null) return false;
if (b1.Length != b2.Length) return false;
for (int i = 0; i < b1.Length; ++i)
{
if (b1[i] != b2[i]) return false;
}
return true;
}
public void Start()
{
try
{
_serialPort.Open();
// LogAsync(DateTime.Now, LogLevel.Assist, $"{Name}[{_serialPort.PortName}]已打开");
}
catch (Exception ex)
{
throw new Exception();
}
}
public void Stop()
{
try
{
_serialPort.Close();
}
catch (Exception ex)
{
throw new Exception();
}
}
public int Read(byte[] buffer, int offset, int count)
{
return _serialPort.Read(buffer, offset, count);
}
public void Writebty(byte[] buffer, int offset, int count)
{
_serialPort.Write(buffer, offset, count);
}
public void WriteStr(string buffer)
{
_serialPort.Write(buffer);
}
//protected void Read()
//{
// SerialPortHelper.ReadExisting(_serialPort);
//}
}
}