using Masuit.Tools.Logging;
using System;
using System.IO.Ports;
using System.Text;

namespace Khd.Core.Wpf.Scan
{
    /// <summary>
    /// 串口帮助类
    /// </summary>
    public class SerialPortHelper
    {
        /// <summary>
        /// 定义委托
        /// </summary>
        /// <param name="info"></param>
        public delegate void ShowMesgDelegate(string info);

        public string message = "";
        //缓冲信息
        public string ReceiveData = "";
        private SerialPort myCom = new SerialPort();//串口对象
        /// <summary>
        /// 串口属性
        /// </summary>
        public SerialPort MyCom
        {
            get
            {
                return myCom;
            }
            set
            {
                myCom = value;
            }
        }

        private byte myReceiveByte = 0;//接收字节
        private byte[] bData = new byte[1024];//接收的字节数组
        private int index = 0;

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="entiry"></param>
        public void OpenMyConn(SerialPortModel entiry)
        {
            if (myCom.IsOpen)
            {
                myCom.Close();//关闭
            }
            myCom.PortName = entiry.PortName;//串口名称
            myCom.BaudRate = entiry.BaudRate;//波特率
            myCom.DataBits = entiry.DataBits;//数据位
            myCom.StopBits = entiry.StopBits;//停止位
            myCom.Parity = entiry.Parity;//校验位 
            myCom.ReceivedBytesThreshold = 1;//设置串口缓冲区的字节数
            myCom.DataReceived += MyCom_DataReceived;//串口接收数据事件 
            myCom.Open();//打开串口
        }
        /// <summary>
        /// 串口接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MyCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //读取串口缓冲区的字节数据,分两次传递结果
                byte[] result = new byte[MyCom.BytesToRead];
                MyCom.Read(result, 0, MyCom.BytesToRead);
                ReceiveData += Encoding.UTF8.GetString(result);
                if (ReceiveData.Contains('\r'))
                {
                    message = ReceiveData.Replace("\r", "").Trim();
                    SystemData.message = message;
                    ReceiveData = "";
                }
                SystemData.isUpdate = true;
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
            }

        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public void CloseMycom()
        {
            if (MyCom.IsOpen)
            {
                MyCom.Close();//关闭
            }
        }
    }

    public class SerialPortModel
    {
        public string PortName { get; set; }
        public int BaudRate { get; set; }
        public int DataBits { get; set; }
        public Parity Parity { get; set; }
        public StopBits StopBits { get; set; }
    }
}
