北斗數據包格式封裝和解析

来源:https://www.cnblogs.com/zhongzw/archive/2019/03/11/10513611.html
-Advertisement-
Play Games

1.北斗協議的具體格式如下圖 2.數據包類型 根據北斗協議類型定義如下枚舉類型 3.基礎類封裝 BDBaseFrame,使用 IByteBuffer 類來封裝數據包,IByteBuffer 內置提供了很多位元組操作方法(read,write) 4.具體數據包類型封裝 PositionFrame 5.d ...


1.北斗協議的具體格式如下圖

image.png

image.png

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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 參考 "Packaging Python Projects" , 源碼在 "nobodxbodon/test package for pypi" : setup.py中 與編寫Visual Studio Code插件初嘗試類似, name只能用英文. 生成發佈包 上傳到測試pypi平臺 測試安裝包. ...
  • 看了一個Beyond的紀錄片, 提到這個. 覺得心有不甘, 於是搜集了24首歌詞, 用Python做了簡單分詞和詞頻統計. 源碼(包括歌詞)在: "program in chinese/study" 統計了總出現次數( )和詞出現在歌曲的數目( ). 前者算進了所有重覆歌詞, 後者是算某個詞出現在了 ...
  • [TOC] 1. maven的作用 實現依賴管理、構建管理、模塊拆分管理的自動化 參考書籍《Maven in Action》 參考內容:基於中華石杉老師的授課內容整理 2. 依賴管理 2.1 坐標機制 groupId:以公司或者組織的官網的功能變數名稱倒序來開頭 + 項目名。如:com.baidu.oa a ...
  • 因為需要將之前mac下用QuickTime錄屏生成的文件(mov格式)轉換成gif文件, 便於傳到某些博客平臺, 於是找到了 "這個轉換工具" , 已將原代碼的命名中文化並簡化. Ruby和視頻轉換都是新手, 請多指教. 之前 "JavaScript實現ZLOGO: 前進方向和速度" 有兩個mov文 ...
  • 集合(set) 集合是一個無序的不重覆元素序列,使用大括弧({})、set()函數創建集合, 註意:創建一個空集合必須用set()而不是{},因為{}是用來創建一個空字典。 集合是無序的、不重覆的、沒有索引的 輸出結果: 添加集合元素 添加單個元素: 輸出結果: 添加多個元素、列表元素、字典元素 輸 ...
  • 歸併排序和快速排序是面試常考的兩大排序,兩者平均時間複雜度均可以達到O(nlogn)。接下來將記錄一下這兩種排序的動圖原理顯示以及代碼的記憶方式。 歸併排序 一、動圖展示 動圖原文鏈接:https://blog.csdn.net/qq_36442947/article/details/8161287 ...
  • 滿課一天,做25的時候還瘋狂WA,進度可以說是很慢了 哭泣 L1-025 正整數A+B 題的目標很簡單,就是求兩個正整數A和B的和,其中A和B都在區間[1,1000]。稍微有點麻煩的是,輸入並不保證是兩個正整數。 輸入格式: 輸入在一行給出A和B,其間以空格分開。問題是A和B不一定是滿足要求的正整數 ...
  • Z字形編排問題詳解(C++): 問題描述:給定一個矩陣matrix,輸出矩陣matrix進行Z字形編排後的內容。 原矩陣: 輸出形式: 演算法分析與詳細解答: 要解決這樣一個問題,可能一開始無從下手,但是我們只要認真觀察Z字形矩陣的走向過程,就不難發現其中的規律。對於原始矩陣matrix中的任意元素  ...
一周排行
    -Advertisement-
    Play Games
  • 概述:本文代碼示例演示瞭如何在WPF中使用LiveCharts庫創建動態條形圖。通過創建數據模型、ViewModel和在XAML中使用`CartesianChart`控制項,你可以輕鬆實現圖表的數據綁定和動態更新。我將通過清晰的步驟指南包括詳細的中文註釋,幫助你快速理解並應用這一功能。 先上效果: 在 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • 概述:本示例演示了在WPF應用程式中實現多語言支持的詳細步驟。通過資源字典和數據綁定,以及使用語言管理器類,應用程式能夠在運行時動態切換語言。這種方法使得多語言支持更加靈活,便於維護,同時提供清晰的代碼結構。 在WPF中實現多語言的一種常見方法是使用資源字典和數據綁定。以下是一個詳細的步驟和示例源代 ...
  • 描述(做一個簡單的記錄): 事件(event)的本質是一個委托;(聲明一個事件: public event TestDelegate eventTest;) 委托(delegate)可以理解為一個符合某種簽名的方法類型;比如:TestDelegate委托的返回數據類型為string,參數為 int和 ...
  • 1、AOT適合場景 Aot適合工具類型的項目使用,優點禁止反編 ,第一次啟動快,業務型項目或者反射多的項目不適合用AOT AOT更新記錄: 實實在在經過實踐的AOT ORM 5.1.4.117 +支持AOT 5.1.4.123 +支持CodeFirst和非同步方法 5.1.4.129-preview1 ...
  • 總說周知,UWP 是運行在沙盒裡面的,所有許可權都有嚴格限制,和沙盒外交互也需要特殊的通道,所以從根本杜絕了 UWP 毒瘤的存在。但是實際上 UWP 只是一個應用模型,本身是沒有什麼許可權管理的,許可權管理全靠 App Container 沙盒控制,如果我們脫離了這個沙盒,UWP 就會放飛自我了。那麼有沒... ...
  • 目錄條款17:讓介面容易被正確使用,不易被誤用(Make interfaces easy to use correctly and hard to use incorrectly)限制類型和值規定能做和不能做的事提供行為一致的介面條款19:設計class猶如設計type(Treat class de ...
  • title: 從零開始:Django項目的創建與配置指南 date: 2024/5/2 18:29:33 updated: 2024/5/2 18:29:33 categories: 後端開發 tags: Django WebDev Python ORM Security Deployment Op ...
  • 1、BOM對象 BOM:Broswer object model,即瀏覽器提供我們開發者在javascript用於操作瀏覽器的對象。 1.1、window對象 視窗方法 // BOM Browser object model 瀏覽器對象模型 // js中最大的一個對象.整個瀏覽器視窗出現的所有東西都 ...