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();
                    }
                };
            }
        }
    }
}
