using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;

namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
    public class StrongTempConnection : SerialPortConnectionBase
    {
        private List<byte> _lstCacheBuffer = new List<byte>();
        public StrongTempConnection(string portName) : base(portName, 9600, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "", false)
        {
            deviceTimer = new DeviceTimer();
        }
        public DeviceTimer deviceTimer;

        private int ErrorCount = 0;
        public override bool SendMessage(byte[] message)
        {
            _lstCacheBuffer.Clear();//每次发送前清除接收区缓存

            return base.SendMessage(message);
        }
        protected override MessageBase ParseResponse(byte[] rawMessage)
        {
            _lstCacheBuffer.AddRange(rawMessage);//持续添加通讯缓存


            //验证最后一位是不是结束符\r
            if (Array.IndexOf(rawMessage, 43) == -1)//byte 43  是通讯结束字符串C
                                                    //return IsTimeOut() ? ReceiveTempMessage(true, false, _lstCacheBuffer.ToArray()) : ReceiveTempMessage(false, false, _lstCacheBuffer.ToArray());
            {
                var mes = IsTimeOut() ? ReceiveTempMessage(true, false, _lstCacheBuffer.ToArray()) : ReceiveTempMessage(false, false, _lstCacheBuffer.ToArray());
                if (deviceTimer.IsIdle())
                    deviceTimer.Start(1000);
                return mes;
            }

            Reset();//复位状态和计数

            return ReceiveTempMessage(false, true, _lstCacheBuffer.ToArray());
        }

        public bool IsTimeOut()
        {
            if (deviceTimer.IsTimeout())
            {
                deviceTimer.Stop();
                ErrorCount += 1;
                if (ErrorCount >= 3)
                    return true;
                return false;
            }
            return false;
        }

        private void Reset()
        {
            ErrorCount = 0;
            deviceTimer.Stop();
        }

        private BinaryMessage ReceiveTempMessage(bool isError, bool isComplete, byte[] bytes)
        {
            BinaryMessage msg = new BinaryMessage();
            msg.IsError = isError;
            msg.IsComplete = isComplete;
            msg.RawMessage = bytes;
            return msg;
        }
    }
}
