北斗数据包格式封装和解析

1.北斗协议的具体格式如下图

2.数据包类型 根据北斗协议类型定义如下枚举类型

 /// <summary>
    /// 数据包类型
    /// </summary>
    public enum BDFrameType : ushort
    {
        /// <summary>
        /// 默认
        /// </summary>
        Default = 0x00,

        /// <summary>
        /// 终端通用应答
        /// </summary>
        TerCommonResponse = 0x0001,

        /// <summary>
        /// 平台通用应答
        /// </summary>
        PlatCommonResponse = 0x8001,

        /// <summary>
        /// 终端心跳
        /// </summary>
        TerHeartbeat = 0x0002,

             /// <summary>
             /// 位置信息汇报
            /// </summary>
              Position = 0x0200

        //省略其他的数据包类型

    }

3.基础类封装 BDBaseFrame,使用 IByteBuffer 类来封装数据包,IByteBuffer 内置提供了很多字节操作方法(read,write)

byteBuffer.ReadUnsignedShort()
byteBuffer.WriteUnsignedShort()
//等等
public abstract class BDBaseFrame
    {
        /// <summary>
        /// 消息ID
        /// </summary>
        public BDFrameType FrameType { get; set; }

        /// <summary>
        /// 是否分包
        /// </summary>
        public bool IsSubpackage { get; set; }

        /// <summary>
        /// 加密方式
        /// </summary>
        public BDFrameEncryptType FrameEncryptType { get; set; }

        /// <summary>
        /// 消息体长度
        /// </summary>
        public UInt16 FrameContentLen { get; private set; }

        /// <summary>
        /// 终端手机号  唯一
        /// </summary>
        public string TerminalPhone { get; set; } = string.Empty;

        /// <summary>
        /// 消息流水号
        /// </summary>
        public ushort FrameSerialNum { get; set; }

        /// <summary>
        /// 消息总包数
        /// </summary>
        public ushort FramePackageCount { get; set; }

        /// <summary>
        /// 包序号  从 1开始
        /// </summary>
        public ushort FramePackageIndex { get; set; }

        private int m_frameBodyOffset = 13;

        /// <summary>
        /// 消息体 数据偏于量
        /// </summary>
        protected int FrameBodyOffset
        {
            get { return m_frameBodyOffset; }
        }

        private static ushort m_SendFrameSerialNum = 0;

        /// <summary>
        /// 获取发送的流水号
        /// </summary>
        public static ushort SendFrameSerialNum
        {
            get
            {
                if (m_SendFrameSerialNum == ushort.MaxValue)
                    m_SendFrameSerialNum = 0;

                m_SendFrameSerialNum++;

                return m_SendFrameSerialNum;
            }
        }

        /// <summary>
        /// 数据包内容 字节
        /// </summary>
        //public IByteBuffer ContentBuffer { get; set; }

        #region 解析数据包
        /// <summary>
        /// 解析头部
        /// </summary>
        private void DecoderHead(IByteBuffer byteBuffer)
        {
            //消息体属性
            byteBuffer.SetReaderIndex(1);
            FrameType = (BDFrameType)byteBuffer.ReadUnsignedShort();
            ushort frameProerty = byteBuffer.ReadUnsignedShort();
            IsSubpackage = FrameHelper.ReadBoolean16(frameProerty, 13);
            FrameContentLen = (UInt16)(frameProerty & 0x1FFF);//消息体长度
            if (IsSubpackage)
                m_frameBodyOffset = 17;
            //终端手机号
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 6; i++)
            {
                stringBuilder.Append(byteBuffer.ReadByte().ToString("X2"));
            }
            TerminalPhone = stringBuilder.ToString().TrimStart(new char[] { ‘0‘ });
            //消息流水号
            FrameSerialNum = byteBuffer.ReadUnsignedShort();
            //消息包封装项
            if (IsSubpackage)
            {
                FramePackageCount = byteBuffer.ReadUnsignedShort();
                FramePackageIndex = byteBuffer.ReadUnsignedShort();
            }
        }

        /// <summary>
        /// 解析内容
        /// </summary>
        public virtual void DecoderFrame(IByteBuffer byteBuffer)
        {
            //解析头部
            DecoderHead(byteBuffer);
        }

        #endregion

        #region 封装数据包

        public virtual IByteBuffer EncoderContent()
        {
            return null;
        }

        #endregion

        public override string ToString()
        {
            return $"{TerminalPhone} {FrameTypeHelper.GetFrameType(FrameType)}  {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
        }
    }

4.具体数据包类型封装 PositionFrame

 /// <summary>
    /// 位置信息汇报
    /// </summary>
    public class PositionFrame : BDBaseFrame
    {
        public PositionFrame()
        {
            FrameType = BDFrameType.Position;
        }

        /// <summary>
        /// 报警标志
        /// </summary>
        public UInt32 AlarmFlag { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public UInt32 StatusFlag { get; set; }

        /// <summary>
        /// 纬度 DWORD 以度为单位的纬度值乘以 10 的 6 次方,精确到百万分之一度
        /// </summary>
        public double Lat { get; set; }

        /// <summary>
        /// 经度 DWORD 以度为单位的经度值乘以 10 的 6 次方,精确到百万分之一度
        /// </summary>
        public double Lng { get; set; }

        /// <summary>
        /// 高程 WORD 海拔高度,单位为米(m)
        /// </summary>
        public UInt16 Height { get; set; }

        /// <summary>
        /// 速度 WORD 1/10km/h
        /// </summary>
        public float Speed { get; set; }

        /// <summary>
        /// 方向 WORD 0-359,正北为 0,顺时针
        /// </summary>
        public UInt16 Direction { get; set; }

        /// <summary>
        /// 时间 BCD[6] YY-MM-DD-hh-mm-ss(GMT+8 时间,本标准中之后涉及的时间均采用此时区)
        /// </summary>
        public DateTime GpsDateTime { get; set; }

        public override void DecoderFrame(IByteBuffer byteBuffer)
        {
            base.DecoderFrame(byteBuffer);

            AlarmFlag = byteBuffer.ReadUnsignedInt();
            StatusFlag = byteBuffer.ReadUnsignedInt();
            Lat = byteBuffer.ReadUnsignedInt() / 1000000.0;
            Lng = byteBuffer.ReadUnsignedInt() / 1000000.0;
            Height = byteBuffer.ReadUnsignedShort();
            Speed = byteBuffer.ReadUnsignedShort() / 10.0f;
            Direction = byteBuffer.ReadUnsignedShort();
            //时间 BCD[6]
            byte[] bcdTime = new byte[6];
            byteBuffer.ReadBytes(bcdTime);
            string bcdTimeString = FrameHelper.Bcd2String(bcdTime);
            DateTime gpsTime;
            if (DateTime.TryParseExact(bcdTimeString, "yyMMddHHmmss", new CultureInfo("zh-CN", true), DateTimeStyles.None, out gpsTime))
                GpsDateTime = gpsTime;
            else
                GpsDateTime = new DateTime(2001, 1, 1, 0, 0, 0);
        }

        public override IByteBuffer EncoderContent()
        {
            IByteBuffer contentBuffer = Unpooled.Buffer(100, 1024);
            contentBuffer.WriteInt((int)AlarmFlag);
            contentBuffer.WriteInt((int)StatusFlag);
            contentBuffer.WriteInt((int)(Lat * 1000000));
            contentBuffer.WriteInt((int)(Lng * 1000000));
            contentBuffer.WriteUnsignedShort(Height);
            contentBuffer.WriteUnsignedShort((UInt16)(Speed * 10));
            contentBuffer.WriteUnsignedShort(Direction);
            //时间 BCD[6]
            byte[] timeBcdBuffer = FrameHelper.WriteBCDString(GpsDateTime.ToString("yyMMddHHmmss"));
            contentBuffer.WriteBytes(timeBcdBuffer);
            return contentBuffer;
        }

        public override string ToString()
        {
            return string.Format("通讯号:{0},时间:{1},经纬度{2}|{3},高度:{4},方向:{5}", TerminalPhone, GpsDateTime.ToString("yyyy-MM-dd HH:mm:ss"), Lng, Lat, Height, Direction);
        }
    }

5.dotnetty EncoderHandler 封装,上面封装的只是消息体的数据,没有包括标识位,消息头,验证码,标识位,在发送数据通道中,需要把数据加上标识位,消息头,验证码,标识位。包括数据包转义

 /// <summary>
    /// 北斗数据包 封装
    /// </summary>
    public class BeiDouContentEncoderHandler : MessageToByteEncoder<BDBaseFrame>
    {
        protected override void Encode(IChannelHandlerContext context, BDBaseFrame message, IByteBuffer output)
        {
            EncodeFrame(message, output);
        }

        private void EncodeFrame(BDBaseFrame message, IByteBuffer output)
        {
            //IByteBuffer frameBuffer = output;
            output.MarkReaderIndex();
            //内容
            IByteBuffer contentBuffer = message.EncoderContent();
            if (contentBuffer == null)
                contentBuffer = Unpooled.Empty;
            //byte[] content = new byte[contentBuffer.ReadableBytes];
            //contentBuffer.ReadBytes(content, 0, content.Length);
            //写头标志
            output.WriteByte(BDFrameConst.FRAME_FLAG);
            //消息 ID
            output.WriteUnsignedShort((ushort)message.FrameType);
            //消息体属性  加密没做
            // ushort contentLen = (ushort)content.Length;
            ushort contentLen = (ushort)contentBuffer.ReadableBytes;
            if (message.IsSubpackage)
            {
                contentLen = (ushort)(contentLen | 0x2000);
                output.WriteUnsignedShort(contentLen);
            }
            else
            {
                output.WriteUnsignedShort(contentLen);
            }
            //终端手机号
            string tPhone = message.TerminalPhone.ToStringFramePropertyLength(12, ‘0‘);
            byte[] tPhoneBuffer = CZEFrameHelper.WriteBCDString(tPhone);
            output.WriteBytes(tPhoneBuffer);
            //消息流水号
            output.WriteUnsignedShort(message.FrameSerialNum);
            //消息包封装项
            if (message.IsSubpackage)
            {
                output.WriteUnsignedShort(message.FramePackageCount);
                output.WriteUnsignedShort(message.FramePackageIndex);
            }
            //消息体
            output.WriteBytes(contentBuffer);
            contentBuffer.Release();
            //计算校验码
            byte[] checkCodeBuffer = new byte[output.ReadableBytes];
            output.ReadBytes(checkCodeBuffer, 0, checkCodeBuffer.Length);
            byte value = checkCodeBuffer[1];
            for (int i = 2; i < checkCodeBuffer.Length; i++)
                value ^= checkCodeBuffer[i];
            output.WriteByte(value);
            //写尾标志
            output.WriteByte(BDFrameConst.FRAME_FLAG);
            //转义
            output.ResetReaderIndex();
            checkCodeBuffer = new byte[output.ReadableBytes];
            output.ReadBytes(checkCodeBuffer, 0, checkCodeBuffer.Length);
            byte[] frame = FrameEscaping.BDEscapingBufferSend(checkCodeBuffer);

            //数据写入 frameBuffer
            output.Clear();
            output.WriteBytes(frame);
        }

    }

6.使用 BeiDouContentEncoderHandler,在通道中加入BeiDouContentEncoderHandler,通道里面的顺序很重要,BeiDouContentEncoderHandler必须要在你发送的Handler前加到通道中去如下图

主要的代码就这些,水平有限,请大家多多指教

原文地址 http://www.dncblogs.cn/Blog/LookBlog/71

原文地址:https://www.cnblogs.com/zhongzw/p/10513611.html

时间: 2024-08-05 19:26:38

北斗数据包格式封装和解析的相关文章

NC传送数据包格式以及用其制作手机短信炸弹

NC -v IP地址 端口<c:\1.txt 具体实例:NC -v 211.157.106.78 8080 <c:\1.txt 打开记事本,写一段批处理让nc自动传包  格式 :go nc -v 211.157.106.78 8080<c:1.txt goto go 将文件保存为批处理1.bat NC传送数据包格式以及用其制作手机短信炸弹,码迷,mamicode.com

ETHERNET数据包格式( IP &amp; UDP &amp; ICMP &amp; ARP )

ETHERNET数据包格式( IP & UDP & ICMP & ARP ) ETHERNET数据包格式 一.ETHERNET 数据包的协议类型 TYPE 的值为 0x0800:IP协议,即:ETHERTYPE_IP,    该值在 /usr/include/net/ethernet.h中有定义.ETHERNET 数据包的格式又细分    为如下几种情况: (1) IP 报头中的协议号码为 IPPROTO_TCP,其值为 6 .ETHERNET 数据包的格式如下: |<---

路由器转发数据包的封装过程

如图,Host A 向Host B 发送数据,路由器会对数据包的封装如下.1.Host A 在网络层将上层的数据封装成IP数据包,其首部包含了源地址和目的地址.源地址本机的IP 192.168.1.2,目的地址为192.168.2.2.在数据链路层将上层的数据封装成数据帧,源地址的Mac地址为 00-11-12-21-11-11 目的Mac地址不知道,Host A通过ARP协议广播想要获取Host B 主机mac地址,获得A路由器的E0接口MAC地址 00-11-12-21-22-22.这时在以

IP数据包格式

0 4 8 16 31 |4位版本 | 4位首部长度 | 8位服务类型 | 16位总长度(字节数)| |16位标识 | 3位标志 | 13位片偏移 | |8位生存时间| 8位协议 | 16位首部校验和 | |32位源IP地址| |32位目的IP地址| |选项(可无)| |数据| netinet/ip.h中定义ip: struct ip { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ip_hl:4; /* header length */ u

TCP/IP数据包格式详解-包括数据链路层的头部

图中括号中的数字代表的是当前域所占的空间大小,单位是bit位. 黄色的是数据链路层的头部,一共14字节 绿色的部分是IP头部,一般是20字节 紫色部分是TCP头部,一般是20字节 最内部的是数据包内容 黄色部分:链路层 目的MAC:当前step目的主机的mac地址 源MAC:当前step的源主机的mac地址 类型:指定网络层所用的协议类型,通常是IP协议,0x0800 绿色部分:网络层,这里用的是IP包头格式 版本:记录数据报属于哪一个版本的协议,如IPv4或IPv6 首部长度:指明IP头部长度

8.1.7 OSPF数据包格式

OSPF的协议号为89,当OSPF数据包多播发生时,它们的TTL设置为1,, 1.数据包头部 所有的OSPF数据包都是由一个24个八位组字节的头部开始 版本version OSPF的版本号,OSPF的版本号为2. 类型Type 跟在头部后面的数据包类型 数据包长度 Packet Length OSPF数据包的长度,包括数据包头部的长度,以八位组字节计 路由器ID Router ID 始发路由器的ID 区域ID Area ID 始发数据包的路由器所在的区域 校验和Checksum 对整个数据包(包

蓝牙BLE数据包格式汇总

以蓝牙4.0为例说明: BLE包格式有:广播包.扫描包.初始化连接包.链路层控制包(LL层数据包).逻辑链路控制和自适应协议数据包(即L2CAP数据包)等: 其中广播包又分为:定向广播包和非定向广播包: 逻辑链路控制和自适应协议数据包又分为:ATT指令包.信令指令包.SMP包: 1. 首先,所有的包都符合如下格式: 2. 广播包: 3. 非定向广播包: 4. 定向广播包: 5. 扫描包: 6. 初始化连接包: 7. 链路层数据包: 8. 链路层控制包: 9. L2CAP层数据包: 10. 信令指

TCP数据包格式

TCP数据格式. 序列号(seq,32位长) * 如果含有同步化旗标(SYN),则此为最初的序列号:第一个数据比特的序列码为本序列号加一. * 如果没有同步化旗标(SYN),则此为第一个数据比特的序列码. * 确认号(ack,32位长)—期望收到的数据的开始序列号.也即已经收到的数据的字节长度加1. * 报头长度(4位长)—以4字节为单位计算出的数据段开始地址的偏移值. * 保留—须置0 * 标志符 * URG—为1表示高优先级数据包,紧急指针字段有效. * ACK—为1表示确认号字段有效 *

Linux 网络编程——IP 数据包格式详解

IP 数据报首部 TCP/IP 协议定义了一个在因特网上传输的包,称为 IP 数据报 (IP Datagram).这是一个与硬件无关的虚拟包,由首部和数据两部分组成. 首部的前一部分是固定长度,共 20 字节,是所有 IP 数据报必须具有的.在首部的固定部分的后面是一些可选字段,其长度是可变的.首都中的源地址和目的地址都是 IP 协议地址. IP 数据报首部的固定部分中的各字段: 1)版本:占4位,指IP协议的版本. 通信双方使用的 IP 协议版本必须一致.日前广泛使用的 IP 协议版本号为 4