Newer
Older
BRServer / BRServer / CasicReceiveFilter.cs
root on 30 Mar 2020 2 KB elec first commit
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.Facility.Protocol;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.Common;

namespace BRServer
{

    public class CasicReceiveFilter : FixedHeaderReceiveFilter<StringRequestInfo>
    {
        public CasicReceiveFilter()
            : base(4)
        {

        }

        protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
        {
            int tagLength = (int)header[offset + 2] * 256 + (int)header[offset + 3] - 12;
            return tagLength + 14 + (tagLength % 8 == 0 ? 0 : (8 - tagLength % 8));
        }


        protected override StringRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
        {
            byte[] tmpHead = header.Array;
            byte[] tmpBody = bodyBuffer.CloneRange(offset, length);

            byte[] src = new byte[tmpHead.Length + tmpBody.Length];

            tmpHead.CopyTo(src, 0);
            tmpBody.CopyTo(src, tmpHead.Length);

            String data = BitConverter.ToString(src, 0, src.Length).Replace("-", "");
            //TODO: construct the receving casic data
            String preamble = data.Substring(0, 2);
            String version = data.Substring(2, 2);
            String leng = data.Substring(4, 4);
            String deviceId = data.Substring(8, 12);

            String routeFlag = data.Substring(20, 2);
            String dstNodeAddr = data.Substring(22, 4);
            String pduType = data.Substring(26, 4);
            String seq = data.Substring(30, 2);

            //对tag进行TEA解密
            Byte[] dat = new Byte[data.Length / 2 - 18];
            Array.Copy(src, 16, dat, 0, data.Length / 2 - 18);

            TEA.decrypt(ref dat, dat.Length);
            String settings = BitConverter.ToString(dat, 0, dat.Length).Replace("-", "").Substring(0, Convert.ToInt32(leng, 16) * 2 - 12 * 2);

            String result = "Casic:" + preamble + "," + version + "," +
                   leng + "," + deviceId + "," + routeFlag + "," + dstNodeAddr + "," + pduType + "," +
                   seq + "," + settings;

            BasicRequestInfoParser m_Parser = new BasicRequestInfoParser(":", ",");
            return m_Parser.ParseRequestInfo(result);
        }
    }

}