using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeneralGommunication
{
    public static class Protocol7ECommon
    {
        /// <summary>
        /// 第0个byte是 7E
        /// </summary>
        /// <param name="pdu"></param>
        /// <returns></returns>
        public static bool Pdu2Data(IEnumerable<byte> pdu, out List<byte> datas)
        {
            datas = new List<byte>();
            for (int i = 1; i < pdu.Count(); i++)
            {
                byte p = pdu.ElementAt(i);
                if (p == 0x7D)
                {
                    if (i + 1 < pdu.Count())
                    {
                        i++;
                        p = pdu.ElementAt(i);
                        //转义符
                        if (p == 0x5E)
                        {
                            datas.Add(0x7E);
                        }
                        else if (p == 0x5D)
                        {
                            datas.Add(0x7D);
                        }
                        else
                        {
                            //异常,不能转义
                            return false;
                        }
                    }
                    else
                    {
                        //异常,没有转义信息
                        return false;
                    }
                }
                else
                {
                    datas.Add(p);
                }
            }
            return true;
        }

        /// <summary>
        /// 第0个byte是 7E
        /// </summary>
        /// <param name="pdu"></param>
        /// <returns></returns>
        public static bool Data2Pdu(IEnumerable<byte> datas, out List<byte> pdu)
        {
            pdu = new List<byte>();
            pdu.Add(0x7E);
            for (int i = 0; i < datas.Count(); i++)
            {
                byte b = datas.ElementAt(i);
                if (b == 0x7E)
                {
                    pdu.Add(0x7D);
                    pdu.Add(0x5E);
                }
                else if (b == 0x7D)
                {
                    pdu.Add(0x7D);
                    pdu.Add(0x5D);
                }
                else
                {
                    pdu.Add(b);
                }
            }
            return true;
        }
    }
}