Ver código fonte

USB解码 初版

lijinwen 3 meses atrás
pai
commit
5a9c7a38ba
58 arquivos alterados com 1993 adições e 1116 exclusões
  1. 1 1
      BaseEnums/Channels.h
  2. 1 1
      BaseEnums/DataCheckEnums.h
  3. 1 1
      BaseEnums/EdgePulseEnums.h
  4. 1 1
      BaseEnums/LogerEnums.h
  5. 1 1
      BaseEnums/ProtocolEnums.h
  6. 1 1
      BaseEnums/QuantizedEnums.h
  7. 63 0
      BaseHelper/CommonHelper.cpp
  8. 63 4
      BaseHelper/CommonHelper.h
  9. 18 0
      BaseHelper/Constants.h
  10. 9 1
      BaseHelper/DataCheckHelper.cpp
  11. 3 1
      BaseHelper/DataCheckHelper.h
  12. 1 1
      BaseHelper/DecodeDataHelper.cpp
  13. 1 1
      BaseHelper/DecodeDataHelper.h
  14. 1 1
      BaseHelper/Logger.cpp
  15. 1 1
      BaseHelper/Logger.h
  16. 1 1
      DecodeEvent.cpp
  17. 2 2
      DecodeEvent.h
  18. 1 1
      DecodeResult.cpp
  19. 1 2
      DecodeResult.h
  20. 39 3
      EdgePulse.cpp
  21. 12 3
      EdgePulse.h
  22. 1 1
      EdgePulseData.cpp
  23. 1 1
      EdgePulseData.h
  24. 18 10
      ExportMethod.cpp
  25. 5 6
      ExportMethod.h
  26. 2 2
      ProtocolDecodeBase.cpp
  27. 1 1
      ProtocolDecodeBase.h
  28. 17 5
      ProtocolDecoder.vcxproj
  29. 1 1
      ProtocolRS232/Constants.h
  30. 1 1
      ProtocolRS232/Protocol.RS232.Options.h
  31. 1 1
      ProtocolRS232/ProtocolRS232Enums.h
  32. 434 436
      ProtocolRS232/RS232Decode.cpp
  33. 4 4
      ProtocolRS232/RS232Decode.h
  34. 1 1
      ProtocolRS232/RS232DecodeEvent.cpp
  35. 1 1
      ProtocolRS232/RS232DecodeEvent.h
  36. 1 1
      ProtocolRS232/RS232DecodeResult.cpp
  37. 2 2
      ProtocolRS232/RS232DecodeResult.h
  38. 1 1
      ProtocolRS232/RS232Packet.cpp
  39. 1 1
      ProtocolRS232/RS232Packet.h
  40. 1 1
      ProtocolRS232/RS232Params.h
  41. 2 2
      ProtocolUSB/Constants.cpp
  42. 29 6
      ProtocolUSB/Constants.h
  43. 58 21
      ProtocolUSB/ProtocolUSBEnums.h
  44. 21 10
      ProtocolUSB/SYNC.h
  45. 0 332
      ProtocolUSB/USBDecode.cpp
  46. 0 84
      ProtocolUSB/USBDecode.h
  47. 433 0
      ProtocolUSB/USBDecoder.cpp
  48. 99 0
      ProtocolUSB/USBDecoder.h
  49. 443 99
      ProtocolUSB/USBPacket.cpp
  50. 54 28
      ProtocolUSB/USBPacket.h
  51. 2 2
      ProtocolUSB/UsbDecodeEvent.cpp
  52. 57 2
      ProtocolUSB/UsbDecodeEvent.h
  53. 6 2
      ProtocolUSB/UsbDecodeOptions.h
  54. 6 6
      ProtocolUSB/UsbDecodeResult.cpp
  55. 64 14
      ProtocolUSB/UsbDecodeResult.h
  56. 1 1
      QuantizeParams.cpp
  57. 1 1
      QuantizeParams.h
  58. 1 1
      dllmain.cpp

+ 1 - 1
BaseEnums/Channels.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseEnums/DataCheckEnums.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseEnums/EdgePulseEnums.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseEnums/LogerEnums.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseEnums/ProtocolEnums.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseEnums/QuantizedEnums.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 63 - 0
BaseHelper/CommonHelper.cpp

@@ -0,0 +1,63 @@
+// // ******************************************************************
+// //       /\ /|       @File         CommonHelper.cpp
+// //       \ V/        @Brief
+// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
+// //       /  |        @Creation      2024-05-31
+// //      /  \\        @Modified      2024-05-31
+// //    *(__\_\
+// // ******************************************************************
+
+#include "CommonHelper.h"
+   
+namespace Protocol
+{
+    // 移除数组中第一个元素,如果它与其他元素的差异最大
+    std::vector<int32_t> CommonHelper::RemoveFirstIfMostDifferent(const std::vector<int32_t>& array)
+    {
+        if (array.size() < 2)
+        {
+            throw std::invalid_argument("Array must contain at least two elements.");
+        }
+        int32_t first_value = array[0];
+        int32_t max_difference = 0;
+        int32_t most_different_index = 0;
+
+        // 找到与第一个元素差异最大的元素
+        for (int32_t i = 1; i < static_cast<int32_t>(array.size()); ++i)
+        {
+            int32_t difference = std::abs(array[i] - first_value);
+            if (difference > max_difference)
+            {
+                max_difference = difference;
+                most_different_index = i;
+            }
+        }
+
+        // 如果第一个元素与其他元素差异最大,则移除第一个元素
+        if (most_different_index == 0)
+        {
+            return std::vector<int32_t>(array.begin() + 1, array.end());
+        }
+
+        return array; // 如果第一个元素不是差异最大的,则返回原数组
+    }
+
+    uint8_t CommonHelper::SwapHighLowBits(uint8_t value)
+    {
+        // 获取低4位
+        uint8_t lowerNibble = value & 0x0F;
+        // 获取高4位
+        uint8_t higherNibble = (value >> 4) & 0x0F;
+        // 交换高低4位
+        return static_cast<uint8_t>(higherNibble | lowerNibble << 4);
+    }
+    uint8_t CommonHelper::ReverseOrderBits(uint8_t value)
+    {
+        value = SwapHighLowBits(value); //高低互换
+        value = static_cast<uint8_t>((value & 0xCC) >> 2 | (value & 0x33) << 2); //交换每对相邻的位
+        value = static_cast<uint8_t>((value & 0xAA) >> 1 | (value & 0x55) << 1); //交换每对相邻的位
+        return value;
+    }
+
+    
+}

+ 63 - 4
BaseHelper/CommonHelper.h

@@ -3,25 +3,39 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #pragma once
 #include <type_traits>
 #include <typeinfo>
+#include <vector>
 
+#include "Logger.h"
+// 检查类型是否为指针
+template <typename T>
+struct IsPointer : std::false_type
+{
+};
+
+template <typename T>
+struct IsPointer<T*> : std::true_type
+{
+};
 namespace Protocol
 {
     class CommonHelper
     {
     public:
-        template <typename EnumType>
+        // 没达到预期效果
+        /*template <typename EnumType>
         static bool EnumIsDefined(int value)
         {
             static_assert(std::is_enum_v<EnumType>, "EnumType must be an enumeration type");
-            return std::underlying_type_t<EnumType>(value) >= 0;
-        }
+            int32_t result = std::underlying_type_t<EnumType>(value);
+            return result >= 0;
+        }*/
 
         template <typename EnumType>
         struct EnumTypeInfo
@@ -31,5 +45,50 @@ namespace Protocol
                 return typeid(EnumType);
             }
         };
+
+        // 通用函数模板,用于将指针数组转换为std::vector
+        template <typename T>
+        static std::vector<T> ConvertPointerArrayToVector(T* array, size_t size);
+        static uint8_t SwapHighLowBits(uint8_t value);
+        static uint8_t ReverseOrderBits(uint8_t value);
+        static std::vector<int32_t> RemoveFirstIfMostDifferent(const std::vector<int32_t>& array);
+        //static bool NeedRemoveFirstIfMostDifferent(const int32_t* start_indexs, const int32_t count);
     };
+    template <typename T>
+      auto CommonHelper::ConvertPointerArrayToVector(T* array, size_t size) -> std::vector<T>
+      {
+        std::vector<T> vec;
+        vec.reserve(size);  // 预分配内存以避免多次重新分配
+
+        // 根据类型是否为指针,进行不同的处理
+        if constexpr (IsPointer<T>::value)
+        {
+            // T是指针类型,直接移动指针指向的对象
+            for (size_t i = 0; i < size; ++i)
+            {
+                vec.emplace_back(std::move(*array[i]));
+            }
+        }
+        else
+        {
+            // T不是指针类型,直接复制对象
+            for (size_t i = 0; i < size; ++i)
+            {
+                //vec.emplace_back(array[i]);
+                vec.push_back(array[i]);
+            }
+        }
+
+        // 如果T是指针类型,清理原始指针数组(如果需要)
+        if constexpr (IsPointer<T>::value)
+        {
+            for (size_t i = 0; i < size; ++i)
+            {
+                delete array[i];
+            }
+        }
+
+        return vec;
+    }
+   
 }

+ 18 - 0
BaseHelper/Constants.h

@@ -0,0 +1,18 @@
+// // ******************************************************************
+// //       /\ /|       @File         Constants.h
+// //       \ V/        @Brief
+// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
+// //       /  |        @Creation      2024-05-20
+// //      /  \\        @Modified      2024-05-30
+// //    *(__\_\
+// // ******************************************************************
+
+#pragma once
+
+namespace Protocol
+{
+
+    //用于设置比较的容忍度
+    constexpr double FLOAT_EQUAL_EPSILON = 1e-6;
+
+};

+ 9 - 1
BaseHelper/DataCheckHelper.cpp

@@ -3,12 +3,16 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #include "DataCheckHelper.h"
 
+#include <cmath>
+
+#include "Constants.h"
+
 namespace Protocol
 {
     bool DataCheckHelper::CheckDataByOddEven(uint8_t data, int32_t dataBitCount,
@@ -27,4 +31,8 @@ namespace Protocol
         if (checkType == OddEvenCheck::Odd) temp = !temp;
         return temp;
     }
+    bool DataCheckHelper::CheckDoubleIsEqual(double a, double b)
+    {
+        return fabs(a - b) < FLOAT_EQUAL_EPSILON;
+    }
 }

+ 3 - 1
BaseHelper/DataCheckHelper.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -20,5 +20,7 @@ namespace Protocol
     {
     public:
         static bool CheckDataByOddEven(uint8_t data, int32_t dataBitCount, OddEvenCheck checkType);
+        //比较浮点数是否相等
+        static bool CheckDoubleIsEqual(double a, double b);
     };
 }

+ 1 - 1
BaseHelper/DecodeDataHelper.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseHelper/DecodeDataHelper.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseHelper/Logger.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
BaseHelper/Logger.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
DecodeEvent.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 2 - 2
DecodeEvent.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -18,6 +18,6 @@ namespace Protocol
         int64_t EventIndex = -1; //事件序号
         int64_t StartIndex = 0; //事件时域起始帧序号
         int64_t EndIndex = 0; //事件时域结束帧序号
-        char* Name; //string 事件名称
+        //char* Name; //string 事件名称
     };
 }

+ 1 - 1
DecodeResult.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 2
DecodeResult.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -24,7 +24,6 @@ namespace Protocol
         bool IsEventInfo = false; //是否是事件帧
     };
 
-
     struct DecodeResult
     {
         //协议类型

+ 39 - 3
EdgePulse.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -21,13 +21,49 @@ namespace Protocol
     //     CurrentLevel = current;
     // }
 
-    ThreeLevelEdgePulseStatusType ThreeLevelEdgePulse::ConvertToStatus(const bool highLevel, const bool lowLoglevel)
+    ThreeLevelEdgePulseStatusType ThreeLevelEdgePulse::ConvertToStatus(const bool high_level, const bool low_loglevel)
     {
-        return static_cast<ThreeLevelEdgePulseStatusType>((highLevel ? 1 : 0) << 1 | (lowLoglevel ? 1 : 0));
+        return static_cast<ThreeLevelEdgePulseStatusType>((high_level ? 1 : 0) << 1 | (low_loglevel ? 1 : 0));
     }
 
     ThreeLevelEdgePulse::ThreeLevelEdgePulse(ThreeLevelEdgePulseStatusType current)
     {
         CurrentLevel = current;
     }
+
+    bool CheckNodeValid(const EdgePulse* edge)
+    {
+        if (edge == nullptr)
+        {
+            return false;
+        }
+        return CheckNodeValid(edge[0]);
+    }
+    bool CheckNodeValid(EdgePulse edge)
+    {
+        if (edge.StartIndex < 0 || edge.EndIndex < 0 || edge.EndIndex <= edge.StartIndex
+            || edge.Edge == Edge::None)
+        {
+            return false;
+        }
+        return true;
+    }
+    void ReversalLevel(Edge& edge)
+    {
+        if (edge == Edge::Falling)
+        {
+            edge = Edge::Rise;
+        }
+        else if (edge == Edge::Rise)
+        {
+            edge = Edge::Falling;
+        }
+    }
+    void ReversalLevel(std::vector<Protocol::EdgePulse>& edge_pulses)
+    {
+        for (int i = 0; i < static_cast<int>(edge_pulses.size()); i++)
+        {
+            ReversalLevel(edge_pulses[i].Edge);
+        }
+    }
 }

+ 12 - 3
EdgePulse.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -34,7 +34,7 @@ namespace Protocol
 
         int32_t GetLength() const
         {
-            return EndIndex > StartIndex && StartIndex > 0 ? EndIndex - StartIndex : 0;
+            return EndIndex > StartIndex && StartIndex >= 0 ? EndIndex - StartIndex : 0;
         }
 
         // uint32_t LevelCount() const override { return 2; }
@@ -51,7 +51,7 @@ namespace Protocol
     struct ThreeLevelEdgePulse final : EdgePulse
     {
         //电平类型  High = 0b11,Middle = 0b01,Low = 0b00,None = 0b10,
-        static ThreeLevelEdgePulseStatusType ConvertToStatus(bool highLevel, bool lowLoglevel);
+        static ThreeLevelEdgePulseStatusType ConvertToStatus(bool high_level, bool low_loglevel);
 
         //uint32_t LevelCount() const override { return 3; }
         static uint32_t LevelCount() { return 3; }
@@ -59,4 +59,13 @@ namespace Protocol
 
         ThreeLevelEdgePulseStatusType CurrentLevel = ThreeLevelEdgePulseStatusType::None;
     };
+
+    //初查节点有效
+    bool CheckNodeValid(const EdgePulse* edge);
+    //初查节点有效
+    bool CheckNodeValid(EdgePulse edge);
+    //电平反转
+    void ReversalLevel(Edge& edge);
+    //电平反转
+    void ReversalLevel(std::vector<Protocol::EdgePulse>& edge_pulses);
 }

+ 1 - 1
EdgePulseData.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
EdgePulseData.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 18 - 10
ExportMethod.cpp

@@ -1,16 +1,24 @@
-#include "ExportMethod.h"
+// // ******************************************************************
+// //       /\ /|       @File         ExportMethod.cpp
+// //       \ V/        @Brief
+// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
+// //       /  |        @Creation      2024-05-20
+// //      /  \\        @Modified      2024-05-30
+// //    *(__\_\
+// // ******************************************************************
 
-//#include "ProtocolUSB/USBDecode.h"
+#include "ExportMethod.h"
 
+#include "ProtocolUSB/USBDecoder.h"
 
 namespace Protocol
 {
-
-    // bool Parse_USB(UsbDecodeOptions option, std::vector<Protocol::TwoLevelEdgePulse> edgePluses1,
-    //                std::vector<Protocol::TwoLevelEdgePulse> edgePluses2, UsbDecodeResult& result)
-    // {
-    //     //todo
-    //     //return USBDecode::DecodeUSB(option, edgePluses1, edgePluses2, result);
-    //     return false;
-    // }
+    //静态方式 对象只有放在全局
+    USBDecoder usb_decode = {};
+    bool Parse_USB(UsbDecodeOptions option, const EdgePulseDataTwoLevels& edge_pluses_data1,
+                   const EdgePulseDataTwoLevels& edge_pluses_data2, UsbDecodeResult& result)
+    {
+        return usb_decode.DecodeUSB(option, edge_pluses_data1, edge_pluses_data2, result);
+        return false;
+    }
 }

+ 5 - 6
ExportMethod.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-20
-// //      /  \\        @Modified      2024-05-20
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -15,8 +15,8 @@
 #include "QuantizeParams.h"
 #include "ProtocolRS232/Protocol.RS232.Options.h"
 #include "ProtocolRS232/RS232DecodeResult.h"
-//#include "ProtocolUSB/UsbDecodeOptions.h"
-//#include "ProtocolUSB/USBDecodeResult.h"
+#include "ProtocolUSB/UsbDecodeOptions.h"
+#include "ProtocolUSB/USBDecodeResult.h"
 
 #ifdef LIBMATH_EXPORTS
 #define LIBMATH_API __declspec(dllexport)
@@ -26,9 +26,8 @@
 namespace Protocol
 {
     extern "C" {
-
-    // LIBMATH_API bool Parse_USB(UsbDecodeOptions option, std::vector<Protocol::TwoLevelEdgePulse> edgePluses1,
-    //                            std::vector<Protocol::TwoLevelEdgePulse> edgePluses2, UsbDecodeResult& result);
+    LIBMATH_API bool Parse_USB(UsbDecodeOptions option, const EdgePulseDataTwoLevels& edge_pluses_data1,
+                               const EdgePulseDataTwoLevels& edge_pluses_data2, UsbDecodeResult& result);
 
 
     LIBMATH_API bool Parse_RS232(const ProtocolRS232Options& options,

+ 2 - 2
ProtocolDecodeBase.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -16,7 +16,7 @@
 
 namespace Protocol
 {
- 
+
 
 }
 

+ 1 - 1
ProtocolDecodeBase.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 17 - 5
ProtocolDecoder.vcxproj

@@ -157,6 +157,7 @@
         </Link>
     </ItemDefinitionGroup>
     <ItemGroup>
+        <ClCompile Include="BaseHelper\CommonHelper.cpp"/>
         <ClCompile Include="BaseHelper\DataCheckHelper.cpp">
             <RuntimeLibrary>MultiThreadedDebugDll</RuntimeLibrary>
             <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
@@ -311,12 +312,17 @@
         <ClCompile Include="dllmain.cpp"/>
         <ClCompile Include="EdgePulse.cpp"/>
         <ClCompile Include="EdgePulseData.cpp"/>
-        <ClCompile Include="ExportMethod.cpp" />
+        <ClCompile Include="ExportMethod.cpp"/>
         <ClCompile Include="ProtocolDecodeBase.cpp"/>
         <ClCompile Include="ProtocolRS232\RS232Decode.cpp"/>
         <ClCompile Include="ProtocolRS232\RS232DecodeEvent.cpp"/>
         <ClCompile Include="ProtocolRS232\RS232DecodeResult.cpp"/>
         <ClCompile Include="ProtocolRS232\RS232Packet.cpp"/>
+        <ClCompile Include="ProtocolUSB\Constants.cpp"/>
+        <ClCompile Include="ProtocolUSB\USBDecoder.cpp"/>
+        <ClCompile Include="ProtocolUSB\UsbDecodeEvent.cpp"/>
+        <ClCompile Include="ProtocolUSB\UsbDecodeResult.cpp"/>
+        <ClCompile Include="ProtocolUSB\USBPacket.cpp"/>
         <ClCompile Include="QuantizeParams.cpp"/>
     </ItemGroup>
     <ItemGroup>
@@ -327,6 +333,7 @@
         <ClInclude Include="BaseEnums\ProtocolEnums.h"/>
         <ClInclude Include="BaseEnums\QuantizedEnums.h"/>
         <ClInclude Include="BaseHelper\CommonHelper.h"/>
+        <ClInclude Include="BaseHelper\Constants.h"/>
         <ClInclude Include="BaseHelper\DataCheckHelper.h"/>
         <ClInclude Include="BaseHelper\DecodeDataHelper.h"/>
         <ClInclude Include="BaseHelper\Logger.h"/>
@@ -334,7 +341,7 @@
         <ClInclude Include="DecodeResult.h"/>
         <ClInclude Include="EdgePulse.h"/>
         <ClInclude Include="EdgePulseData.h"/>
-        <ClInclude Include="ExportMethod.h" />
+        <ClInclude Include="ExportMethod.h"/>
         <ClInclude Include="ProtocolDecodeBase.h"/>
         <ClInclude Include="ProtocolRS232\Constants.h"/>
         <ClInclude Include="ProtocolRS232\Protocol.RS232.Options.h"/>
@@ -344,11 +351,16 @@
         <ClInclude Include="ProtocolRS232\RS232DecodeEvent.h"/>
         <ClInclude Include="ProtocolRS232\RS232DecodeResult.h"/>
         <ClInclude Include="ProtocolRS232\RS232Packet.h"/>
+        <ClInclude Include="ProtocolUSB\Constants.h"/>
+        <ClInclude Include="ProtocolUSB\ProtocolUSBEnums.h"/>
+        <ClInclude Include="ProtocolUSB\SYNC.h"/>
+        <ClInclude Include="ProtocolUSB\USBDecoder.h"/>
+        <ClInclude Include="ProtocolUSB\UsbDecodeEvent.h"/>
+        <ClInclude Include="ProtocolUSB\UsbDecodeOptions.h"/>
+        <ClInclude Include="ProtocolUSB\UsbDecodeResult.h"/>
+        <ClInclude Include="ProtocolUSB\USBPacket.h"/>
         <ClInclude Include="QuantizeParams.h"/>
     </ItemGroup>
-    <ItemGroup>
-      <Folder Include="ProtocolUSB\" />
-    </ItemGroup>
     <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets"/>
     <ImportGroup Label="ExtensionTargets">
     </ImportGroup>

+ 1 - 1
ProtocolRS232/Constants.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
ProtocolRS232/Protocol.RS232.Options.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
ProtocolRS232/ProtocolRS232Enums.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 434 - 436
ProtocolRS232/RS232Decode.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -15,439 +15,437 @@
 
 namespace Protocol
 {
-	
-	std::vector<RS232DecodeResultCell> decodeResultUnits;
-	std::vector<RS232DecodeEventUnit> decodeEventUnitsStorage;
-	std::vector<RS232DecodeEvent> decodeEvents;
-	
-
-	int32_t getStartIndex(const ProtocolRS232Options& options, TwoLevelEdgePulse*& node,
-		double count,
-		double& realCount,
-		const int32_t startIndex,
-		TwoLevelEdgePulseStatusType& startStatus)
-	{
-		startStatus = options.Polarity == Polarity::Pos
-			? TwoLevelEdgePulseStatusType::High
-			: TwoLevelEdgePulseStatusType::Low;
-
-		while (node != nullptr)
-		{
-			if (node->CurrentLevel != startStatus && node->StartIndex >= startIndex)
-			{
-				//计算该脉宽中,最大包括几个bit信息宽度
-				const double bitCount = std::round(node->GetLength() / count);
-				if (bitCount > 0 && bitCount < static_cast<int32_t>(options.DataBitWidth) + 4)
-				{
-					realCount = node->GetLength() / bitCount;
-				}
-				if (bitCount > 0) break;
-			}
-
-			node++;
-		}
-		return node == nullptr ? -1 : node->StartIndex;
-	}
-
-	bool pauseDataRS232(const ProtocolRS232Options& options, TwoLevelEdgePulse* edgePulses,
-		const uint64_t edgePulseCount,
-		const uint64_t waveformDataCount, const double sampleRate,
-		RS232DecodeResult& decodeResult)
-
-	{
-		canceled = false;
-		WriteLog(LogLevel::LevelDebug, " SignalType:%d, DataBitWidth:%d"
-			, static_cast<int>(options.SignalType), static_cast<int>(options.DataBitWidth));
-		if (canceled)
-		{
-			WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
-
-			return false;
-		}
-
-		//栈上 初始化内存
-		std::vector<RS232Packet> rs232Packets;
-		rs232Packets = {};
-		decodeEvents = {};
-		decodeResultUnits = {};
- 
-		auto decodeResultUnitsPtr = &decodeResultUnits;
-		auto decodeEventsPtr = &decodeEvents;
-		WriteLog(LogLevel::LevelDebug, "  decodeResultUnitsPtr:0x%X\n", static_cast<void*>(decodeResultUnitsPtr));
-		WriteLog(LogLevel::LevelDebug, "  decodeEventsPtr:0x%X\n", static_cast<void*>(decodeEventsPtr));
-		canceled = false;
-
-		if (canceled)
-		{
-			WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
-			return false;
-		}
-		if (edgePulses == nullptr)
-		{
-			WriteLog(LogLevel::Level2, " EdgePulseDataPtr is nullptr\n");
-			return false;
-		}
-		//if (edgePulseData.edgePulses.empty())
-		if (waveformDataCount == 0)
-		{
-			std::cout << "  DataCount is 0 or sampleRate error\n";
-			WriteLog(LogLevel::Level2, " DataCount is 0 or sampleRate error\n");
-			return false;
-		}
-
-		int32_t dataBitCount = 0;
-		switch (options.DataBitWidth)
-		{
-		case RS232Enums::DataBitWidth::DataBitWidth_5Bit:
-			dataBitCount = 5;
-			break;
-		case RS232Enums::DataBitWidth::DataBitWidth_6Bit:
-			dataBitCount = 6;
-			break;
-		case RS232Enums::DataBitWidth::DataBitWidth_7Bit:
-			dataBitCount = 7;
-			break;
-		case RS232Enums::DataBitWidth::DataBitWidth_8Bit:
-			dataBitCount = 8;
-			break;
-		}
-
-
-		uint64_t edgePulseIndex = 0;
-
-		//每bit理论长度
-		const double count = 1.0 / options.BaudRate * sampleRate;
-		WriteLog(LogLevel::LevelDebug, "  bit count:%f", count);
-		//const double count = static_cast<double>(dataCount);
-		//每bit实际长度
-		double realCount = count;
-
-		const int32_t stopBitCount = options.StopBit == RS232Enums::StopBit::StopBit_1bit
-			? 1
-			: options.StopBit == RS232Enums::StopBit::StopBit_2bit
-			? 2
-			: 1;
-
-		WriteLog(LogLevel::LevelDebug, "  realCount:%f", realCount);
-		WriteLog(LogLevel::LevelDebug, "  edgePulsePointer:0x%x", reinterpret_cast<void*>(edgePulses));
-		//WriteLog("  edgePulsePointer:0x%x", edgePulses);
-		WriteLog(LogLevel::LevelDebug, "  edgePulse StartIndex:%d", edgePulses->StartIndex);
-		WriteLog(LogLevel::LevelDebug, "  edgePulse EndIndex:%d", edgePulses->EndIndex);
-		WriteLog(LogLevel::LevelDebug, "  edgePulseCount:%d", edgePulseCount);
-
-		try
-		{
-			int32_t startIndex = 0;
-
-			while (edgePulses != nullptr && edgePulseIndex < edgePulseCount)
-			{
-				if (count <= 2) break;
-				TwoLevelEdgePulseStatusType levelState;
-				//找到帧头 根据帧头得到实际bit宽度realCount  帧头起始位置startIndex 电平状态levelState
-				int32_t packetStartIndex =
-					getStartIndex(options, edgePulses, count, realCount, startIndex, levelState);
-				//WriteLog("  GetStartIndex PacketStartIndex:%d\n", packetStartIndex);
-				if (canceled)
-				{
-					WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
-					return false;
-				}
-
-				if (packetStartIndex == -1) break;
-				//std::cout << " packetStartIndex:" << packetStartIndex << " ,realCount:" << realCount << "\n";
-				//构造帧
-				RS232Packet packet = {};
-				packetStartIndex += static_cast<int32_t>(std::round(realCount / 2));
-
-				if (edgePulses->StartIndex >= edgePulses->EndIndex || !CommonHelper::EnumIsDefined<
-					TwoLevelEdgePulseStatusType>(static_cast<int>(edgePulses->CurrentLevel)))
-				{
-					std::ostringstream msg;
-					msg << " =>178 loop break Index:" << packetStartIndex << " ,dataCount:" <<
-						waveformDataCount << "\n";
-					WriteLog(LogLevel::LevelDebug, msg.str().c_str());
-					break;
-				}
-				if (packetStartIndex >= static_cast<int32_t>(waveformDataCount))
-				{
-					std::ostringstream msg;
-					msg << " =>186 loop break Index:" << packetStartIndex << " ,dataCount:" <<
-						waveformDataCount << "\n";
-					WriteLog(LogLevel::LevelDebug, msg.str().c_str());
-					break;
-				}
-
-				if (startIndex == static_cast<int32_t>(waveformDataCount)) break;
-
-				packet.StartBit = levelState == TwoLevelEdgePulseStatusType::High;
-				packet.StartIndex = packetStartIndex - static_cast<int32_t>(std::round(realCount / 2));
-				packet.DataIndex = packetStartIndex + static_cast<int32_t>(std::round(realCount / 2));
-				packet.PerBitLenght = realCount;
-
-				WriteLog(LogLevel::LevelDebug, "=> Tst  StartIndex:%d,dataBitCount:%d", packet.StartIndex, dataBitCount);
-				for (int32_t dataBitIndex = 0; dataBitIndex < dataBitCount; dataBitIndex++)
-				{
-					if (canceled)
-					{
-						WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
-						return false;
-					}
-
-					packetStartIndex += static_cast<int32_t>(std::round(realCount));
-
-					//std::cout << "  P150 Test" << "\n";
-					if (packetStartIndex >= static_cast<int32_t>(waveformDataCount))
-					{
-						startIndex = static_cast<int32_t>(waveformDataCount);
-						WriteLog(LogLevel::LevelDebug, "  =>%d break \n", __LINE__);
-						break;
-					}
-					//std::cout << "  P157 Test" << "\n";
-					TwoLevelEdgePulseStatusType bitStatus;
-					if (!getRS232Bit(edgePulses, packetStartIndex, bitStatus))
-					{
-						//gMutex.unlock(); // 执行完操作后手动释放锁
-						return false;
-					}
-					//按位构造数据
-					if (options.MSBOrLSB == MSBOrLSB::MSB)
-					{
-						packet.Data = static_cast<uint8_t>(packet.Data << 1);
-						packet.Data |= bitStatus == TwoLevelEdgePulseStatusType::High ? 1 : 0;
-					}
-					else
-					{
-						packet.Data |= static_cast<uint8_t>((bitStatus ==
-							TwoLevelEdgePulseStatusType::High
-							? 1
-							: 0) << dataBitIndex);
-					}
-					WriteLog(LogLevel::LevelDebug, "Tst CurrentLevel:%d, bitStatus:%d", edgePulses->CurrentLevel, bitStatus);
-				}
-				//std::cout << "  P177 Test" << "\n";
-				if (startIndex == static_cast<int32_t>(waveformDataCount)) break;
-				//校验位
-				if (options.OddEvenCheckType != OddEvenCheck::None)
-				{
-					packetStartIndex += static_cast<int32_t>(std::round(realCount));
-
-					if (packetStartIndex >= static_cast<int32_t>(waveformDataCount))
-					{
-						//startIndex = static_cast<int32_t>(bufferLength);
-						rs232Packets.push_back(packet);
-						WriteLog(LogLevel::LevelDebug, "  =>%d break \n", __LINE__);
-						break;
-					}
-					TwoLevelEdgePulseStatusType bitStatus;
-					if (!getRS232Bit(edgePulses, packetStartIndex, bitStatus))
-					{
-						//gMutex.unlock(); // 执行完操作后手动释放锁
-						return false;
-					}
-					packet.ParityFind = true;
-					packet.ParityBit = bitStatus == TwoLevelEdgePulseStatusType::High;
-					packet.ParityResult = DataCheckHelper::CheckDataByOddEven(
-						packet.Data, dataBitCount, options.OddEvenCheckType);
-					packet.ParityIndex = packet.DataIndex + static_cast<int32_t>(
-						std::round(realCount * dataBitCount));
-				}
-				//std::cout << "  P203 Test" << "\n";
-				rs232Packets.push_back(packet);
-
-				packetStartIndex += static_cast<int32_t>(realCount * stopBitCount);
-				startIndex = packetStartIndex;
-				edgePulseIndex++;
-			}
-		}
-		catch (const char* ex)
-		{
-			WriteLog(LogLevel::LevelDebug, "  ParsingData L%d catch :%s", __LINE__, ex);
-			return false;
-		}
-
-		{
-			std::ostringstream msg;
-			msg << "  edgePulseIndex:" << edgePulseIndex << ",";
-			msg << "  rs232Packets count:" << rs232Packets.size() << ",";
-			msg << "  get events && results";
-			WriteLog(LogLevel::Level2, msg.str().c_str());
-		}
-		//get events && results
-		//std::cout << "  P218 Test rs232Packets Count:" << rs232Packets.size() << "\n";
-		if (!rs232Packets.empty())
-		{
-			decodeEventUnitsStorage = {};
-			//for (int64_t i = 0; i < static_cast<int64_t>(rs232Packets.size()); i++)
-			for (auto packet : rs232Packets)
-			{
-				if (canceled)
-				{
-					WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
-					//gMutex.unlock(); // 执行完操作后手动释放锁
-					return false;
-				}
-				RS232DecodeResultCell resultUnit;
-				RS232DecodeEvent decodeEvent = {};
-				auto eventPtr = &decodeEvent;
-				RS232DecodeEventUnit eventStart;
-				RS232DecodeEventUnit eventData;
-				int64_t eventStartIndex = packet.StartIndex;
-				int64_t oneBitLength = static_cast<int64_t>(packet.PerBitLenght);
-
-				eventPtr->StartIndex = packet.StartIndex;
-
-				eventStart.StartIndex = packet.StartIndex;
-				eventStart.Length = oneBitLength;
-				eventStartIndex += 1;
-				eventStart.EventType = RS232Enums::RS232DecodeEventType::Start;
-
-				eventData.StartIndex = eventStart.StartIndex;
-				eventData.Length = oneBitLength * dataBitCount;
-				eventData.Data = packet.Data;
-				eventData.EventType = RS232Enums::RS232DecodeEventType::Data;
-				eventStartIndex += 8;
-
-
-				//std::cout << "  P249 Test I:" << i << "\n";
-				if (packet.ParityFind)
-				{
-					RS232DecodeEventUnit eventUints[3];
-					eventUints[0] = eventStart;
-					eventUints[1] = eventData;
-					RS232DecodeEventUnit eventParity;
-					//std::cout << "  P253 Test I:" << i << "\n";
-					eventParity.Data = packet.ParityResult ? 1 : 0;
-					eventParity.StartIndex = eventStartIndex;
-					eventParity.Length = oneBitLength;
-					eventParity.EventType = RS232Enums::RS232DecodeEventType::Parity;
-					eventPtr->ParityResult = packet.ParityResult ? 1 : 0;
-					eventUints[2] = eventParity;
-					//eventPtr->EventData = eventUints;
-					eventStartIndex += 8;
-					eventPtr->EventDataCount = 3;
-					eventPtr->EndIndex = packet.StartIndex + oneBitLength * (dataBitCount + 1);
-					// 将eventUints复制到decodeEventUnitsStorage中
-					decodeEventUnitsStorage.insert(decodeEventUnitsStorage.end(), std::begin(eventUints),
-						std::end(eventUints));
-					//最后来赋值
-					//decodeEvent.EventData = decodeEventUnitsStorage.data() + decodeEventUnitsStorage.size() - 3;
-				}
-				else
-				{
-					RS232DecodeEventUnit eventUints[2];
-					eventUints[0] = eventStart;
-					eventUints[1] = eventData;
-					eventPtr->EventDataCount = 2;
-
-					//eventPtr->EventData = eventUints;
-					//std::cout << "  P263 Test I:" << i << "\n";
-					eventPtr->ParityResult = 0;
-					eventPtr->EndIndex = packet.StartIndex + oneBitLength * (dataBitCount);
-					// 将eventUints复制到decodeEventUnitsStorage中
-					decodeEventUnitsStorage.insert(decodeEventUnitsStorage.end(), std::begin(eventUints),
-						std::end(eventUints));
-					//最后来赋值
-					//decodeEvent.EventData = decodeEventUnitsStorage.data() + decodeEventUnitsStorage.size() - 2;
-				}
-
-				//std::cout << "  P266 Test I:" << i << "\n";
-				resultUnit.StartIndex = packet.StartIndex;
-				//最后来赋值
-				//resultUnit.Data = &packet.Data;
-				WriteLog(LogLevel::LevelDebug, "  Tst Data Ptr:0x%x , Data:%d", static_cast<void*>(resultUnit.Data),
-					packet.Data);
-				resultUnit.DataCount = 1;
-				resultUnit.Length = eventStartIndex - packet.StartIndex;
-
-				eventPtr->EventIndex = static_cast<int64_t>(decodeEventsPtr->size());
-
-				decodeEvents.push_back(decodeEvent);
-				decodeResultUnits.push_back(resultUnit);
-
-				decodeResult.DecodeEventNeedUpdate = true;
-				decodeResult.DecodeResultNeedUpdate = true;
-			}
-		}
-
-		/////////////////////////// 指针赋值 /////////////////////////////////
-		int64_t eventDataIndex = 0;
-		for (int i = 0; i < decodeEvents.size(); i++) // NOLINT(modernize-loop-convert, clang-diagnostic-sign-compare)
-		{
-			decodeEvents[i].EventData = decodeEventUnitsStorage.data() + eventDataIndex;
-			eventDataIndex += decodeEvents[i].EventDataCount;
-		}
-
-		for (int i = 0; i < decodeResultUnits.size(); i++)  // NOLINT(clang-diagnostic-sign-compare)
-		{
-			int64_t startIndex = decodeResultUnits[i].StartIndex;
-			for (int x = 0; i < rs232Packets.size(); x++) // NOLINT(clang-diagnostic-sign-compare)
-			{
-				if (rs232Packets[x].StartIndex == startIndex)
-				{
-					decodeResultUnits[i].Data = &(rs232Packets[x].Data);
-					break;
-				}
-			}
-		}
-		
-		decodeResult.DecodeEventsPtr = decodeEventsPtr->data();
-		decodeResult.DecodeResultUnitsPtr = decodeResultUnitsPtr->data();
-		decodeResult.DecodeEventCount = decodeEventsPtr->size();
-		decodeResult.DecodeResultCount = decodeResultUnitsPtr->size();
-		  
-		WriteLog(LogLevel::Level1, "  Cpp ParsingData Done,return True \n\n");
-
-		return true;
-	}
-
-
-
-	std::vector<const char*> getEventInfoTitles()
-	{
-		return eventInfoTitles;
-	}
-
-	bool getRS232Bit(TwoLevelEdgePulse*& edgePulse,
-		int32_t targetIndex, TwoLevelEdgePulseStatusType& status)
-	{
-		status = TwoLevelEdgePulseStatusType::None;
-		if (edgePulse == nullptr)
-		{
-			return false;
-		}
-		if (targetIndex <= 0 || edgePulse->StartIndex > targetIndex)
-		{
-			return false;
-		}
-		while (edgePulse != nullptr)
-		{
-			if (edgePulse->StartIndex <= targetIndex && edgePulse->EndIndex > targetIndex)
-			{
-				status = edgePulse->CurrentLevel;
-				//test
-				WriteLog(LogLevel::Level2, "StartIndex:%d , status:%d", edgePulse->StartIndex, status);
-				return true;
-			}
-			edgePulse++;
-		}
-		return false;
-	}
-
-	bool quantizeParamsDecodeRS232(const QuantizeParams& quantizeParams, const ProtocolRS232Options& options,
-		RS232DecodeResult& decodeResult)
-	{
-		canceled = false;
-		//todo
-		return false;
-	}
-
-	bool Parse_RS232(const ProtocolRS232Options& options,
-		const EdgePulseDataTwoLevels& edgePulseData,
-		RS232DecodeResult& decodeResult)
-	{
-		return pauseDataRS232(options, edgePulseData.GetDataAddrPtr(),
-			edgePulseData.EdgePulsesCount,
-			edgePulseData.WaveformDataCount, edgePulseData.SampleRate,
-			decodeResult);
-	}
+
+    std::vector<RS232DecodeResultCell> decodeResultUnits;
+    std::vector<RS232DecodeEventUnit> decodeEventUnitsStorage;
+    std::vector<RS232DecodeEvent> decodeEvents;
+
+
+    int32_t getStartIndex(const ProtocolRS232Options& options, TwoLevelEdgePulse*& node,
+                          double count,
+                          double& realCount,
+                          const int32_t startIndex,
+                          TwoLevelEdgePulseStatusType& startStatus)
+    {
+        startStatus = options.Polarity == Polarity::Pos
+                          ? TwoLevelEdgePulseStatusType::High
+                          : TwoLevelEdgePulseStatusType::Low;
+
+        while (node != nullptr)
+        {
+            if (node->CurrentLevel != startStatus && node->StartIndex >= startIndex)
+            {
+                //计算该脉宽中,最大包括几个bit信息宽度
+                const double bitCount = std::round(node->GetLength() / count);
+                if (bitCount > 0 && bitCount < static_cast<int32_t>(options.DataBitWidth) + 4)
+                {
+                    realCount = node->GetLength() / bitCount;
+                }
+                if (bitCount > 0) break;
+            }
+
+            node++;
+        }
+        return node == nullptr ? -1 : node->StartIndex;
+    }
+
+    bool pauseDataRS232(const ProtocolRS232Options& options, TwoLevelEdgePulse* edge_pulses,
+                        const uint64_t edge_pulse_count,
+                        const uint64_t waveform_data_count, const double sample_rate,
+                        RS232DecodeResult& decode_result)
+
+    {
+        canceled = false;
+        WriteLog(LogLevel::LevelDebug, " SignalType:%d, DataBitWidth:%d"
+                 , static_cast<int>(options.SignalType), static_cast<int>(options.DataBitWidth));
+        if (canceled)
+        {
+            WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
+
+            return false;
+        }
+
+        //栈上 初始化内存
+        std::vector<RS232Packet> rs232_packets;
+        rs232_packets = {};
+        decodeEvents = {};
+        decodeResultUnits = {};
+
+        auto decodeResultUnitsPtr = &decodeResultUnits;
+        auto decodeEventsPtr = &decodeEvents;
+        WriteLog(LogLevel::LevelDebug, "  decodeResultUnitsPtr:0x%X\n", static_cast<void*>(decodeResultUnitsPtr));
+        WriteLog(LogLevel::LevelDebug, "  decodeEventsPtr:0x%X\n", static_cast<void*>(decodeEventsPtr));
+        canceled = false;
+
+        if (canceled)
+        {
+            WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
+            return false;
+        }
+        if (edge_pulses == nullptr)
+        {
+            WriteLog(LogLevel::Level2, " EdgePulseDataPtr is nullptr\n");
+            return false;
+        }
+        //if (edgePulseData.edgePulses.empty())
+        if (waveform_data_count == 0)
+        {
+            std::cout << "  DataCount is 0 or sampleRate error\n";
+            WriteLog(LogLevel::Level2, " DataCount is 0 or sampleRate error\n");
+            return false;
+        }
+
+        int32_t dataBitCount = 0;
+        switch (options.DataBitWidth)
+        {
+        case RS232Enums::DataBitWidth::DataBitWidth_5Bit:
+            dataBitCount = 5;
+            break;
+        case RS232Enums::DataBitWidth::DataBitWidth_6Bit:
+            dataBitCount = 6;
+            break;
+        case RS232Enums::DataBitWidth::DataBitWidth_7Bit:
+            dataBitCount = 7;
+            break;
+        case RS232Enums::DataBitWidth::DataBitWidth_8Bit:
+            dataBitCount = 8;
+            break;
+        }
+
+
+        uint64_t edgePulseIndex = 0;
+
+        //每bit理论长度
+        const double count = 1.0 / options.BaudRate * sample_rate;
+        WriteLog(LogLevel::LevelDebug, "  bit count:%f", count);
+        //const double count = static_cast<double>(dataCount);
+        //每bit实际长度
+        double realCount = count;
+
+        const int32_t stopBitCount = options.StopBit == RS232Enums::StopBit::StopBit_1bit
+                                         ? 1
+                                         : options.StopBit == RS232Enums::StopBit::StopBit_2bit
+                                         ? 2
+                                         : 1;
+
+        WriteLog(LogLevel::LevelDebug, "  realCount:%f", realCount);
+        WriteLog(LogLevel::LevelDebug, "  edgePulsePointer:0x%x", reinterpret_cast<void*>(edge_pulses));
+        //WriteLog("  edgePulsePointer:0x%x", edgePulses);
+        WriteLog(LogLevel::LevelDebug, "  edgePulse StartIndex:%d", edge_pulses->StartIndex);
+        WriteLog(LogLevel::LevelDebug, "  edgePulse EndIndex:%d", edge_pulses->EndIndex);
+        WriteLog(LogLevel::LevelDebug, "  edgePulseCount:%d", edge_pulse_count);
+
+        try
+        {
+            int32_t startIndex = 0;
+
+            while (edge_pulses != nullptr && edgePulseIndex < edge_pulse_count)
+            {
+                if (count <= 2) break;
+                TwoLevelEdgePulseStatusType levelState;
+                //找到帧头 根据帧头得到实际bit宽度realCount  帧头起始位置startIndex 电平状态levelState
+                int32_t packetStartIndex =
+                    getStartIndex(options, edge_pulses, count, realCount, startIndex, levelState);
+                //WriteLog("  GetStartIndex PacketStartIndex:%d\n", packetStartIndex);
+                if (canceled)
+                {
+                    WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
+                    return false;
+                }
+
+                if (packetStartIndex == -1) break;
+                //std::cout << " packetStartIndex:" << packetStartIndex << " ,realCount:" << realCount << "\n";
+                //构造帧
+                RS232Packet packet = {};
+                packetStartIndex += static_cast<int32_t>(std::round(realCount / 2));
+
+                if (edge_pulses->StartIndex >= edge_pulses->EndIndex)
+                {
+                    std::ostringstream msg;
+                    msg << " =>178 loop break Index:" << packetStartIndex << " ,dataCount:" <<
+                        waveform_data_count << "\n";
+                    WriteLog(LogLevel::LevelDebug, msg.str().c_str());
+                    break;
+                }
+                if (packetStartIndex >= static_cast<int32_t>(waveform_data_count))
+                {
+                    std::ostringstream msg;
+                    msg << " =>186 loop break Index:" << packetStartIndex << " ,dataCount:" <<
+                        waveform_data_count << "\n";
+                    WriteLog(LogLevel::LevelDebug, msg.str().c_str());
+                    break;
+                }
+
+                if (startIndex == static_cast<int32_t>(waveform_data_count)) break;
+
+                packet.StartBit = levelState == TwoLevelEdgePulseStatusType::High;
+                packet.StartIndex = packetStartIndex - static_cast<int32_t>(std::round(realCount / 2));
+                packet.DataIndex = packetStartIndex + static_cast<int32_t>(std::round(realCount / 2));
+                packet.PerBitLenght = realCount;
+
+                WriteLog(LogLevel::LevelDebug, "=> Tst  StartIndex:%d,dataBitCount:%d", packet.StartIndex, dataBitCount);
+                for (int32_t dataBitIndex = 0; dataBitIndex < dataBitCount; dataBitIndex++)
+                {
+                    if (canceled)
+                    {
+                        WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
+                        return false;
+                    }
+
+                    packetStartIndex += static_cast<int32_t>(std::round(realCount));
+
+                    //std::cout << "  P150 Test" << "\n";
+                    if (packetStartIndex >= static_cast<int32_t>(waveform_data_count))
+                    {
+                        startIndex = static_cast<int32_t>(waveform_data_count);
+                        WriteLog(LogLevel::LevelDebug, "  =>%d break \n", __LINE__);
+                        break;
+                    }
+                    //std::cout << "  P157 Test" << "\n";
+                    TwoLevelEdgePulseStatusType bitStatus;
+                    if (!getRS232Bit(edge_pulses, packetStartIndex, bitStatus))
+                    {
+                        //gMutex.unlock(); // 执行完操作后手动释放锁
+                        return false;
+                    }
+                    //按位构造数据
+                    if (options.MSBOrLSB == MSBOrLSB::MSB)
+                    {
+                        packet.Data = static_cast<uint8_t>(packet.Data << 1);
+                        packet.Data |= bitStatus == TwoLevelEdgePulseStatusType::High ? 1 : 0;
+                    }
+                    else
+                    {
+                        packet.Data |= static_cast<uint8_t>((bitStatus ==
+                                                             TwoLevelEdgePulseStatusType::High
+                                                                 ? 1
+                                                                 : 0) << dataBitIndex);
+                    }
+                    WriteLog(LogLevel::LevelDebug, "Tst CurrentLevel:%d, bitStatus:%d", edge_pulses->CurrentLevel, bitStatus);
+                }
+                //std::cout << "  P177 Test" << "\n";
+                if (startIndex == static_cast<int32_t>(waveform_data_count)) break;
+                //校验位
+                if (options.OddEvenCheckType != OddEvenCheck::None)
+                {
+                    packetStartIndex += static_cast<int32_t>(std::round(realCount));
+
+                    if (packetStartIndex >= static_cast<int32_t>(waveform_data_count))
+                    {
+                        //startIndex = static_cast<int32_t>(bufferLength);
+                        rs232_packets.push_back(packet);
+                        WriteLog(LogLevel::LevelDebug, "  =>%d break \n", __LINE__);
+                        break;
+                    }
+                    TwoLevelEdgePulseStatusType bitStatus;
+                    if (!getRS232Bit(edge_pulses, packetStartIndex, bitStatus))
+                    {
+                        //gMutex.unlock(); // 执行完操作后手动释放锁
+                        return false;
+                    }
+                    packet.ParityFind = true;
+                    packet.ParityBit = bitStatus == TwoLevelEdgePulseStatusType::High;
+                    packet.ParityResult = DataCheckHelper::CheckDataByOddEven(
+                        packet.Data, dataBitCount, options.OddEvenCheckType);
+                    packet.ParityIndex = packet.DataIndex + static_cast<int32_t>(
+                        std::round(realCount * dataBitCount));
+                }
+                //std::cout << "  P203 Test" << "\n";
+                rs232_packets.push_back(packet);
+
+                packetStartIndex += static_cast<int32_t>(realCount * stopBitCount);
+                startIndex = packetStartIndex;
+                edgePulseIndex++;
+            }
+        }
+        catch (const char* ex)
+        {
+            WriteLog(LogLevel::LevelDebug, "  ParsingData L%d catch :%s", __LINE__, ex);
+            return false;
+        }
+
+        {
+            std::ostringstream msg;
+            msg << "  edgePulseIndex:" << edgePulseIndex << ",";
+            msg << "  rs232Packets count:" << rs232_packets.size() << ",";
+            msg << "  get events && results";
+            WriteLog(LogLevel::Level2, msg.str().c_str());
+        }
+        //get events && results
+        //std::cout << "  P218 Test rs232Packets Count:" << rs232Packets.size() << "\n";
+        if (!rs232_packets.empty())
+        {
+            decodeEventUnitsStorage = {};
+            //for (int64_t i = 0; i < static_cast<int64_t>(rs232Packets.size()); i++)
+            for (auto packet : rs232_packets)
+            {
+                if (canceled)
+                {
+                    WriteLog(LogLevel::Level2, "  ParsingData canceled.\n");
+                    //gMutex.unlock(); // 执行完操作后手动释放锁
+                    return false;
+                }
+                RS232DecodeResultCell resultUnit;
+                RS232DecodeEvent decodeEvent = {};
+                auto eventPtr = &decodeEvent;
+                RS232DecodeEventUnit eventStart;
+                RS232DecodeEventUnit eventData;
+                int64_t eventStartIndex = packet.StartIndex;
+                int64_t oneBitLength = static_cast<int64_t>(packet.PerBitLenght);
+
+                eventPtr->StartIndex = packet.StartIndex;
+
+                eventStart.StartIndex = packet.StartIndex;
+                eventStart.Length = oneBitLength;
+                eventStartIndex += 1;
+                eventStart.EventType = RS232Enums::RS232DecodeEventType::Start;
+
+                eventData.StartIndex = eventStart.StartIndex;
+                eventData.Length = oneBitLength * dataBitCount;
+                eventData.Data = packet.Data;
+                eventData.EventType = RS232Enums::RS232DecodeEventType::Data;
+                eventStartIndex += 8;
+
+
+                //std::cout << "  P249 Test I:" << i << "\n";
+                if (packet.ParityFind)
+                {
+                    RS232DecodeEventUnit eventUints[3];
+                    eventUints[0] = eventStart;
+                    eventUints[1] = eventData;
+                    RS232DecodeEventUnit eventParity;
+                    //std::cout << "  P253 Test I:" << i << "\n";
+                    eventParity.Data = packet.ParityResult ? 1 : 0;
+                    eventParity.StartIndex = eventStartIndex;
+                    eventParity.Length = oneBitLength;
+                    eventParity.EventType = RS232Enums::RS232DecodeEventType::Parity;
+                    eventPtr->ParityResult = packet.ParityResult ? 1 : 0;
+                    eventUints[2] = eventParity;
+                    //eventPtr->EventData = eventUints;
+                    eventStartIndex += 8;
+                    eventPtr->EventDataCount = 3;
+                    eventPtr->EndIndex = packet.StartIndex + oneBitLength * (dataBitCount + 1);
+                    // 将eventUints复制到decodeEventUnitsStorage中
+                    decodeEventUnitsStorage.insert(decodeEventUnitsStorage.end(), std::begin(eventUints),
+                                                   std::end(eventUints));
+                    //最后来赋值
+                    //decodeEvent.EventData = decodeEventUnitsStorage.data() + decodeEventUnitsStorage.size() - 3;
+                }
+                else
+                {
+                    RS232DecodeEventUnit eventUints[2];
+                    eventUints[0] = eventStart;
+                    eventUints[1] = eventData;
+                    eventPtr->EventDataCount = 2;
+
+                    //eventPtr->EventData = eventUints;
+                    //std::cout << "  P263 Test I:" << i << "\n";
+                    eventPtr->ParityResult = 0;
+                    eventPtr->EndIndex = packet.StartIndex + oneBitLength * (dataBitCount);
+                    // 将eventUints复制到decodeEventUnitsStorage中
+                    decodeEventUnitsStorage.insert(decodeEventUnitsStorage.end(), std::begin(eventUints),
+                                                   std::end(eventUints));
+                    //最后来赋值
+                    //decodeEvent.EventData = decodeEventUnitsStorage.data() + decodeEventUnitsStorage.size() - 2;
+                }
+
+                //std::cout << "  P266 Test I:" << i << "\n";
+                resultUnit.StartIndex = packet.StartIndex;
+                //最后来赋值
+                //resultUnit.Data = &packet.Data;
+                WriteLog(LogLevel::LevelDebug, "  Tst Data Ptr:0x%x , Data:%d", static_cast<void*>(resultUnit.Data),
+                         packet.Data);
+                resultUnit.DataCount = 1;
+                resultUnit.Length = eventStartIndex - packet.StartIndex;
+
+                eventPtr->EventIndex = static_cast<int64_t>(decodeEventsPtr->size());
+
+                decodeEvents.push_back(decodeEvent);
+                decodeResultUnits.push_back(resultUnit);
+
+                decode_result.DecodeEventNeedUpdate = true;
+                decode_result.DecodeResultNeedUpdate = true;
+            }
+        }
+
+        /////////////////////////// 指针赋值 /////////////////////////////////
+        int64_t eventDataIndex = 0;
+        for (int i = 0; i < decodeEvents.size(); i++) // NOLINT(modernize-loop-convert, clang-diagnostic-sign-compare)
+        {
+            decodeEvents[i].EventData = decodeEventUnitsStorage.data() + eventDataIndex;
+            eventDataIndex += decodeEvents[i].EventDataCount;
+        }
+
+        for (int i = 0; i < decodeResultUnits.size(); i++)  // NOLINT(clang-diagnostic-sign-compare)
+        {
+            int64_t startIndex = decodeResultUnits[i].StartIndex;
+            for (int x = 0; i < rs232_packets.size(); x++) // NOLINT(clang-diagnostic-sign-compare)
+            {
+                if (rs232_packets[x].StartIndex == startIndex)
+                {
+                    decodeResultUnits[i].Data = &(rs232_packets[x].Data);
+                    break;
+                }
+            }
+        }
+
+        decode_result.DecodeEventsPtr = decodeEventsPtr->data();
+        decode_result.DecodeResultCellsPtr = decodeResultUnitsPtr->data();
+        decode_result.DecodeEventCount = decodeEventsPtr->size();
+        decode_result.DecodeResultCount = decodeResultUnitsPtr->size();
+
+        WriteLog(LogLevel::Level1, "  Cpp ParsingData Done,return True \n\n");
+
+        return true;
+    }
+
+
+    std::vector<const char*> getEventInfoTitles()
+    {
+        return eventInfoTitles;
+    }
+
+    bool getRS232Bit(TwoLevelEdgePulse*& edge_pulse,
+                     int32_t targetIndex, TwoLevelEdgePulseStatusType& status)
+    {
+        status = TwoLevelEdgePulseStatusType::None;
+        if (edge_pulse == nullptr)
+        {
+            return false;
+        }
+        if (targetIndex <= 0 || edge_pulse->StartIndex > targetIndex)
+        {
+            return false;
+        }
+        while (edge_pulse != nullptr)
+        {
+            if (edge_pulse->StartIndex <= targetIndex && edge_pulse->EndIndex > targetIndex)
+            {
+                status = edge_pulse->CurrentLevel;
+
+                WriteLog(LogLevel::LevelDebug, "StartIndex:%d , status:%d", edge_pulse->StartIndex, status);
+                return true;
+            }
+            edge_pulse++;
+        }
+        return false;
+    }
+
+    bool quantizeParamsDecodeRS232(const QuantizeParams& quantizeParams, const ProtocolRS232Options& options,
+                                   RS232DecodeResult& decodeResult)
+    {
+        canceled = false;
+        //todo
+        return false;
+    }
+
+    bool Parse_RS232(const ProtocolRS232Options& options,
+                     const EdgePulseDataTwoLevels& edgePulseData,
+                     RS232DecodeResult& decodeResult)
+    {
+        return pauseDataRS232(options, edgePulseData.GetDataAddrPtr(),
+                              edgePulseData.EdgePulsesCount,
+                              edgePulseData.WaveformDataCount, edgePulseData.SampleRate,
+                              decodeResult);
+    }
 }

+ 4 - 4
ProtocolRS232/RS232Decode.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -25,13 +25,13 @@
 
 namespace Protocol
 {
-    static bool getRS232Bit(TwoLevelEdgePulse*& edgePulse,
+    static bool getRS232Bit(TwoLevelEdgePulse*& edge_pulse,
                             int32_t targetIndex, TwoLevelEdgePulseStatusType& status);
     inline std::vector<const char*> eventInfoTitles = {
         "Index", "Start Time", "Data", "Parity", "Error"
     };
 
     std::vector<const char*> getEventInfoTitles();
-     
-    
+
+
 }

+ 1 - 1
ProtocolRS232/RS232DecodeEvent.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
ProtocolRS232/RS232DecodeEvent.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
ProtocolRS232/RS232DecodeResult.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 2 - 2
ProtocolRS232/RS232DecodeResult.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -30,7 +30,7 @@ namespace Protocol
         // void ClearData();
         bool DecodeResultNeedUpdate = false;
         bool DecodeEventNeedUpdate = false;
-        RS232DecodeResultCell* DecodeResultUnitsPtr; //解码数据结果指针
+        RS232DecodeResultCell* DecodeResultCellsPtr; //解码数据结果指针
         RS232DecodeEvent* DecodeEventsPtr; //解码结果事件指针
         uint64_t DecodeResultCount; //结果数量
         uint64_t DecodeEventCount; //事件数量

+ 1 - 1
ProtocolRS232/RS232Packet.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
ProtocolRS232/RS232Packet.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
ProtocolRS232/RS232Params.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 2 - 2
ProtocolUSB/Constants.cpp

@@ -2,8 +2,8 @@
 // //       /\ /|       @File         Constants.cpp
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 29 - 6
ProtocolUSB/Constants.h

@@ -2,16 +2,39 @@
 // //       /\ /|       @File         Constants.h
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #pragma once
+#include <cstdint>
+
 namespace Protocol
 {
-    class Constants
-    {
-    public:
-    };
+    //差分非对称长度比例阈值
+    constexpr double USB_DIFF_LEN_DIFFERENCE_THRESHOLD = 0.95;
+
+    //最小序列长度
+    constexpr int32_t USB_MINIMUM_SEQUENCE_LENGTH = 12;
+    //时域差异容差阈值
+    constexpr double USB_TIME_DIFFERENCE_THRESHOLD = 0.28;
+    //同步帧长度容差
+    constexpr double USB_SYNC_BIT_TOL = 0.95;
+    //同步帧长度
+    constexpr int32_t USB_SYNC_BYTE_LEN = 8;
+    //NRZI 连续补位/个数
+    constexpr int32_t USB_NRZI_COMPLEMENT_PER_NUM = 6;
+
+    constexpr double USB_LOW_SPEED_MHZ = 1.5;
+    constexpr double USB_FULL_SPEED_MHZ = 12;
+    constexpr double USB_HIGH_SPEED_MHZ = 480;
+
+
+    constexpr int32_t USB_ADDR_BIT_COUNT = 7;
+    constexpr int32_t USB_ENDPOINT_BIT_COUNT = 4;
+    constexpr int32_t USB_FRAMEID_BIT_COUNT = 11;
+    constexpr int32_t USB_CRC5_BIT_COUNT = 5;
+    constexpr int32_t USB_CRC16_BIT_COUNT = 16;
+
 }

+ 58 - 21
ProtocolUSB/ProtocolUSBEnums.h

@@ -2,8 +2,8 @@
 // //       /\ /|       @File         ProtocolUSBEnums.h
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-3
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -12,12 +12,49 @@
 
 namespace Protocol
 {
-    class Enums
+    class USBEnums
     {
     public:
+        enum class EventInfoTitles
+        {
+            UNKNOW,
+            INDEX,
+            START_TIME,
+            SYNC,
+            SOF,
+            SETUP,
+            PID,
+            DATA0,
+            DATA1,
+            DATA2,
+            MDATA,
+            ADDR,
+            ACK,
+            //IN,关键字
+            TIN,
+            //OUT,关键字
+            TOUT,
+            NAK,
+            STALL,
+            NYET,
+            FNUM,
+            CRC5,
+            CRC16,
+            EOP,
+            //ERROR, 关键字
+            ERR,
+        };
+
+        enum class USBSpeed
+        {
+            LOW_SPEED = 0,
+            FULL_SPEED = 1,
+            HIGH_SPEED = 2,
+        };
+
         enum class USBFieldType
         {
-            NoDefine = 0,
+            NO_DEFINE = 0,
             SOP,
             SYNC,
             PID,
@@ -29,11 +66,11 @@ namespace Protocol
 
         enum class USBPacketType
         {
-            NoDefine = 0,
-            Token,
-            Data,
-            HandShake,
-            Special,
+            NO_DEFINE = 0,
+            TOKEN,
+            DATA,
+            HAND_SHAKE,
+            SPECIAL,
         };
 
         enum class Condition
@@ -60,10 +97,10 @@ namespace Protocol
 
         enum class TokenPackageType //: uint8_t
         {
-            Out = 0b0001,
-            SOF = 0b0101,
-            IN = 0b1001,
-            SETUP = 0b1101,
+            Out = 0b0001,  //1
+            SOF = 0b0101,  //5
+            In = 0b1001,   //9
+            Setup = 0b1101,//13
         };
 
         enum class SpecialPacketType //: uint8_t
@@ -77,18 +114,18 @@ namespace Protocol
 
         enum class HandshakePackageType //: uint8_t
         {
-            ACK = 0b0010,
-            NAK = 0b1010,
-            STALL = 0b1110,
-            Nyet = 0b0110,
+            ACK = 0b0010,   //2
+            NAK = 0b1010,   //10
+            Stall = 0b1110, //14
+            Nyet = 0b0110,  //6
         };
 
         enum class DataPackageType //: uint8_t
         {
-            Data0 = 0b0011,
-            Data1 = 0b1011,
-            Data2 = 0b0111,
-            MData = 0b1111,
+            Data0 = 0b0011, //3
+            Data1 = 0b1011, //11
+            Data2 = 0b0111, //7
+            MData = 0b1111, //15
         };
 
         enum class ErrorPackageType

+ 21 - 10
ProtocolUSB/SYNC.h

@@ -2,25 +2,31 @@
 // //       /\ /|       @File         SYNC.h
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-3
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #pragma once
+#include "Constants.h"
+
 namespace Protocol
 {
     class SYNC
     {
     public:
-        int StartIndex;
+        Protocol::TwoLevelEdgePulse* NodePtr;
         int EndIndex;
         int SingleBitTimingLength;
         int OneByteTimingLength;
 
         int Length() const
         {
-            return EndIndex - StartIndex;
+            if (NodePtr == nullptr || NodePtr->StartIndex < 0)
+            {
+                return 0;
+            }
+            return EndIndex - NodePtr->StartIndex;
         }
 
         int PacketEndIndex() const
@@ -33,17 +39,22 @@ namespace Protocol
             packetEndIndex = value;
         }
 
-        SYNC()
+        SYNC() : NodePtr(nullptr), EndIndex(0), SingleBitTimingLength(0), OneByteTimingLength(0), packetEndIndex(0)
         {
         }
 
-        SYNC(int startIndex, int endIndex, int singleBitTimingLength) :
-            StartIndex(startIndex),
-            EndIndex(endIndex),
-            SingleBitTimingLength(singleBitTimingLength),
-            OneByteTimingLength(singleBitTimingLength * 8),
+        SYNC(Protocol::TwoLevelEdgePulse* node_ptr, int end_index, int single_bit_timing_length) : NodePtr(node_ptr),
+            EndIndex(end_index),
+            SingleBitTimingLength(single_bit_timing_length),
+            OneByteTimingLength(single_bit_timing_length * USB_SYNC_BYTE_LEN),
             packetEndIndex(0)
         {
+            int32_t fix_sync_end_index = node_ptr->StartIndex + static_cast<int32_t>(single_bit_timing_length * USB_SYNC_BYTE_LEN
+                * USB_SYNC_BIT_TOL);
+            if (end_index < fix_sync_end_index)
+            {
+                EndIndex = fix_sync_end_index;
+            }
         }
 
     private:

+ 0 - 332
ProtocolUSB/USBDecode.cpp

@@ -1,332 +0,0 @@
-// // ******************************************************************
-// //       /\ /|       @File         USBDecode.cpp
-// //       \ V/        @Brief
-// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
-// //    *(__\_\
-// // ******************************************************************
-
-#include "USBDecode.h"
-
-namespace Protocol
-{
-    double USBDecode::GetBitRateByPs() const
-    {
-        double result = 1.0;
-        switch (signalRate)
-        {
-        case Enums::SignalRate::LowRate:
-            result /= 1.5E6;
-            break;
-        case Enums::SignalRate::FullRate:
-            result /= 12E6;
-            break;
-        case Enums::SignalRate::HighRate:
-            result /= 480E6;
-            break;
-        default: break;
-        }
-        return result;
-    }
-
-    std::vector<std::string> USBDecode::EventInfoTitles() const
-    {
-        return {"Index", "Start Time", "Sync", "PID", "Data", "Addr", "FNUM", "CRC5", "CRC16", "EOP", "Error"};
-    }
-
-    Enums::SignalRate USBDecode::SignalRate() const
-    {
-        return signalRate;
-    }
-
-    void USBDecode::SetSignalRate(Enums::SignalRate value)
-    {
-        signalRate = value;
-    }
-
-    uint16_t USBDecode::ByteCount() const
-    {
-        return byteCount;
-    }
-
-    void USBDecode::SetByteCount(uint16_t value)
-    {
-        byteCount = value;
-    }
-
-    uint16_t USBDecode::MaxByteCount()
-    {
-        return 1023;
-    }
-
-    uint16_t USBDecode::MinByteCount()
-    {
-        return 0;
-    }
-
-    bool USBDecode::DecodeUSB(UsbDecodeOptions option,std::vector<Protocol::TwoLevelEdgePulse> edgePluses1,
-                        std::vector<Protocol::TwoLevelEdgePulse> edgePluses2,UsbDecodeResult& result)
-    {
-        //todo
-        
-        return  true;
-    }
-
-    bool USBDecode::ParseData(std::vector<Protocol::TwoLevelEdgePulse> edgePluses,
-                                     std::promise<void>& cancellationSignal)
-    {
-        if (edgePluses.empty()) return false;
-        // 使用 std::future 来检测取消请求
-        std::future<void> cancellationFuture = cancellationSignal.get_future();
-
-        // 检查是否取消
-        if (cancellationFuture.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready)
-        {
-            std::cout << "AsyncFunction canceled." << '\n';
-            return false;
-        }
-        int32_t leftdataSize = static_cast<int32_t>(edgePluses.size());
-        if (FindPackets(edgePluses.data(), leftdataSize, usbPackets, cancellationSignal))
-        {
-            if (usbPackets.empty())
-            {
-                return false;
-            }
-            //resultData.ClearData();
-
-            //todo 事件总线和绘图对象 下沉后在这里构建事件总线和绘图序列  这里只做简单逻辑暂时,细节未实现
-            for (auto&& element : usbPackets)
-            {
-                resultData.Add(new UsbDecodeResultCell(element));
-            }
-        }
-
-        return true;
-    }
-
-    bool USBDecode::CheckDifferenceWithinThreshold(double* array, int32_t size, double threshold)
-    {
-        //threshold = 0.15;
-        for (int i = 1; i < size; i++)
-        {
-            double difference = std::abs(array[i] - array[i - 1]);
-            double percentageDifference = difference / array[i - 1];
-            if (difference < 50)
-            {
-                threshold = 0.28;
-            }
-            if (percentageDifference > threshold)
-            {
-                return false; // 如果差异大于阈值,则返回 false
-            }
-        }
-
-        return true; // 所有元素之间的差异都小于阈值
-    }
-
-    void USBDecode::ClearEdgeArray(Protocol::Edge* edges, int32_t size)
-    {
-        for (int i = 0; i < size; ++i)
-        {
-            edges[i] = Protocol::Edge::None;
-        }
-    }
-
-    bool USBDecode::CheckSyncEdges(Protocol::Edge startEdge, Protocol::Edge* edges)
-    {
-        return edges[0] == edges[1] && edges[0] == startEdge && edges[0] == edges[6];
-    }
-
-    bool USBDecode::CheckSyncSpans(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize
-                                        , const int32_t count, int32_t& avgSpans)
-    {
-        if (count < 1)
-        {
-            return false;
-        }
-        auto startIndexs = new int32_t[count + 1];
-        avgSpans = 0;
-        if ((node - 1) != nullptr)
-        {
-            node--;
-        }
-
-        for (int i = count; i >= 0; i--)
-        {
-            if (node == nullptr)
-            {
-                return false;
-            }
-            startIndexs[i] = node->StartIndex;
-            node--;
-        }
-        return CheckSyncSpansByArrary(startIndexs, count, avgSpans);
-    }
-
-    bool USBDecode::CheckSyncSpansByArrary(int32_t* startIndexs, const int32_t count,
-                                                int32_t& avgSpans)
-    {
-        if (count < 1)
-        {
-            return false;
-        }
-        auto tmpSpans = new double[count - 1];
-        for (int i = 1; i < count; i++)
-        {
-            tmpSpans[i - 1] = (double)(startIndexs[i] - startIndexs[i - 1]);
-        }
-        double totalSpans = 0;
-        for (int i = 0; i < count - 1; i++)
-        {
-            totalSpans += std::abs(tmpSpans[0]);
-        }
-        avgSpans = (int)(totalSpans / (count - 1));
-        return CheckDifferenceWithinThreshold(tmpSpans, count - 1);
-    }
-
-    bool USBDecode::FindAllSyncs(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize,
-                                      std::vector<SYNC>& allSYNC, std::promise<void>& cancellationSignal,
-                                      bool polarity)
-    {
-        // 使用 std::future 来检测取消请求
-        std::future<void> cancellationFuture = cancellationSignal.get_future();
-        allSYNC.clear();
-        int firstAvgSpan = 0;
-
-        if (node == nullptr || node - 1 == nullptr)
-        {
-            return false;
-        }
-
-        const int syncBitLen = 8;
-        Protocol::Edge nextEdge = polarity ? Protocol::Edge::Rise : Protocol::Edge::Falling;
-        Protocol::Edge startEdge = nextEdge;
-
-        Protocol::TwoLevelEdgePulse* startInfoNode = nullptr;
-        Protocol::Edge tmpEdges[syncBitLen];
-        ClearEdgeArray(tmpEdges, syncBitLen);
-
-        int tmpEdgeCount = 0;
-        Protocol::TwoLevelEdgePulse* tmpNode = node;
-
-        while (tmpNode != nullptr)
-        {
-            if (cancellationFuture.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready)
-            {
-                std::cout << "AsyncFunction canceled." << '\n';
-                return false;
-            }
-            if (tmpEdgeCount <= 7)
-            {
-                if (tmpEdgeCount == 0)
-                {
-                    startInfoNode = tmpNode;
-                }
-
-                tmpEdges[tmpEdgeCount] = tmpNode->Edge;
-                tmpEdgeCount++;
-            }
-            else
-            {
-                if (CheckSyncEdges(startEdge, tmpEdges))
-                {
-                    int avgSpans;
-                    if (CheckSyncSpans(tmpNode, leftOverSize, syncBitLen - 1, avgSpans))
-                    {
-                        if (allSYNC.empty())
-                        {
-                            firstAvgSpan = avgSpans;
-                            allSYNC.emplace_back(startInfoNode->StartIndex, (tmpNode - 1)->StartIndex,
-                                                 avgSpans);
-                        }
-                        else if (startInfoNode != nullptr && (startInfoNode - 1) != nullptr && (startInfoNode - 1)->
-                            GetLength() > firstAvgSpan * 8)
-                        {
-                            allSYNC.emplace_back(startInfoNode->StartIndex, (tmpNode - 1)->StartIndex,
-                                                 avgSpans);
-                        }
-
-                        ClearEdgeArray(tmpEdges, syncBitLen);
-                        tmpEdgeCount = 0;
-                        tmpNode++;
-                        leftOverSize--;
-                        continue;
-                    }
-                }
-
-                for (int i = 0; i < syncBitLen - 1; i++)
-                {
-                    tmpEdges[i] = tmpEdges[i + 1];
-                }
-
-                tmpEdges[syncBitLen - 1] = tmpNode->Edge;
-                startInfoNode++;
-            }
-
-            tmpNode++;
-            leftOverSize--;
-        }
-
-        return !allSYNC.empty();
-    }
-
-    bool USBDecode::FindPackets(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize,
-                                     std::vector<USBPacket>& allPacket, std::promise<void>& cancellationSignal,
-                                     bool polarity)
-    {
-        // 使用 std::future 来检测取消请求
-        const std::future<void> cancellationFuture = cancellationSignal.get_future();
-        allPacket.clear();
-        std::vector<SYNC> allSYNC;
-        if (!FindAllSyncs(node, leftOverSize, allSYNC, cancellationSignal, polarity) || allSYNC.empty())
-        {
-            return false;
-        }
-
-        Protocol::TwoLevelEdgePulse* tmpNode = node;
-        for (const auto& sync : allSYNC)
-        {
-            while (tmpNode != nullptr && tmpNode->StartIndex < sync.StartIndex)
-            {
-                if (cancellationFuture.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready)
-                {
-                    std::cout << "AsyncFunction canceled." << '\n';
-                    return false;
-                }
-                tmpNode--;
-            }
-
-            if (tmpNode == nullptr || tmpNode - 1 == nullptr)
-            {
-                break;
-            }
-
-            if (sync.StartIndex != tmpNode->StartIndex)
-            {
-                continue;
-            }
-
-            while (sync.EndIndex > tmpNode->StartIndex && tmpNode != nullptr)
-            {
-                tmpNode++;
-                if (cancellationFuture.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready)
-                {
-                    std::cout << "AsyncFunction canceled." << '\n';
-                    return false;
-                }
-            }
-
-            if (tmpNode != nullptr)
-            {
-                USBPacket packet(tmpNode, leftOverSize, sync, polarity);
-                if (packet.IsValid())
-                {
-                    allPacket.push_back(packet);
-                }
-            }
-        }
-
-        return true;
-    }
-}

+ 0 - 84
ProtocolUSB/USBDecode.h

@@ -1,84 +0,0 @@
-// // ******************************************************************
-// //       /\ /|       @File         USBDecode.h
-// //       \ V/        @Brief
-// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
-// //    *(__\_\
-// // ******************************************************************
-
-#pragma once
-#include <iostream>
-#include <future>
-#include <chrono>
-#include <thread>
-#include <cmath>
-
- 
-#include "../EdgePulse.h"
-
-#include "SYNC.h"
-#include "ProtocolUSBEnums.h"
-#include "USBDecodeOptions.h"
-#include "USBDecodeResult.h"
-#include "USBPacket.h"
-
-namespace Protocol
-{
-    class USBDecode
-    {
-   
-
-    public:
-        USBDecode(): signalRate(), byteCount(0)
-        {
-        }
-
-        double GetBitRateByPs() const;
-
-        std::vector<std::string> EventInfoTitles() const;
-
-        Enums::SignalRate SignalRate() const;
-
-        void SetSignalRate(Enums::SignalRate value);
-
-        uint16_t ByteCount() const;
-
-        void SetByteCount(uint16_t value);
-
-        static uint16_t MaxByteCount();
-
-        static uint16_t MinByteCount();
-
-        static bool DecodeUSB(UsbDecodeOptions option,std::vector<Protocol::TwoLevelEdgePulse> edgePluses1,
-                         std::vector<Protocol::TwoLevelEdgePulse> edgePluses2,UsbDecodeResult& result);
-    private:
-        UsbDecodeResult resultData;
-        Enums::SignalRate signalRate;
-
-        uint16_t byteCount;
-
-        std::vector<USBPacket> usbPackets;
-        
-    private:
-        bool CheckDifferenceWithinThreshold(double* array, int32_t size, double threshold = 0.15);
-
-        void ClearEdgeArray(Protocol::Edge* edges, int32_t size);
-
-        bool CheckSyncEdges(Protocol::Edge startEdge, Protocol::Edge* edges);
-
-        bool CheckSyncSpans(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, int32_t count,
-                            int32_t& avgSpans);
-
-        bool CheckSyncSpansByArrary(int32_t* startIndexs, const int32_t count, int32_t& avgSpans);
-
-        bool FindAllSyncs(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize,
-                          std::vector<SYNC>& allSYNC, std::promise<void>& cancellationSignal, bool polarity = false);
-
-        bool FindPackets(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize,
-                         std::vector<USBPacket>& allPacket, std::promise<void>& cancellationSignal,
-                         bool polarity = false);
-        bool ParseData(std::vector<Protocol::TwoLevelEdgePulse> edgePluses,
-                                     std::promise<void>& cancellationSignal);
-    };
-}

+ 433 - 0
ProtocolUSB/USBDecoder.cpp

@@ -0,0 +1,433 @@
+// // ******************************************************************
+// //       /\ /|       @File         USBDecoder.cpp
+// //       \ V/        @Brief
+// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
+// //    *(__\_\
+// // ******************************************************************
+
+#include "USBDecoder.h"
+
+#include <utility>
+
+#include "Constants.h"
+#include "../ExportMethod.h"
+#include "../BaseHelper/DataCheckHelper.h"
+// #include <cstddef>
+
+namespace Protocol
+{
+    std::vector<std::string> USBDecoder::EventInfoTitles()
+    {
+        return {"Index", "Start Time", "Sync", "PID", "Data", "Addr", "FNUM", "CRC5", "CRC16", "EOP", "Error"};
+    }
+
+    //主解码函数入口
+    bool USBDecoder::DecodeUSB(const UsbDecodeOptions& option, const EdgePulseDataTwoLevels& edge_pulses_dp,
+                               const EdgePulseDataTwoLevels& edge_pulses_dm, UsbDecodeResult& result)
+    {
+        std::vector<Protocol::TwoLevelEdgePulse> edge_pulses2 =
+            CommonHelper::ConvertPointerArrayToVector<Protocol::TwoLevelEdgePulse>(
+                edge_pulses_dm.GetDataAddrPtr(), edge_pulses_dm.EdgePulsesCount);
+        std::vector<Protocol::TwoLevelEdgePulse> edge_pulses1 =
+            CommonHelper::ConvertPointerArrayToVector<Protocol::TwoLevelEdgePulse>(
+                edge_pulses_dp.GetDataAddrPtr(), edge_pulses_dp.EdgePulsesCount);
+        differenceEopIndexs = {};
+        double set_bit_time_span = 0;
+        //////参数判断
+        if (!CheckOptions(option, edge_pulses1, edge_pulses2, set_bit_time_span))
+        {
+            return false;
+        }
+        resultCells = {};
+        usbDiffUnalignedFramesIndex = {};
+
+        //////处理差分逻辑
+        if (option.SignType == SignType::Diff)
+        {
+            if (!ParseDiffSignalData(edge_pulses1, edge_pulses2))
+            {
+                return false;
+            }
+        }
+        else
+        {
+            if (edge_pulses1.size() < edge_pulses2.size())
+            {
+                signEdgePulse = std::move(edge_pulses2);
+            }
+            else
+            {
+                signEdgePulse = std::move(edge_pulses1);
+            }
+        }
+        waveMaxTimeIndexLen = signEdgePulse[signEdgePulse.size() - 1].EndIndex;
+        //////处理单端逻辑
+        if (option.AutoClock) set_bit_time_span = -1;
+        if (ParseSingleData(set_bit_time_span))
+        {
+            result = {};
+            result.DecodeEventsPtr = resultEvents.data();
+            result.DecodeResultCellsPtr = resultCells.data();
+            result.DecodeEventCount = resultEvents.size();
+            result.DecodeResultCount = resultCells.size();
+            result.DecodeResultNeedUpdate = !resultCells.empty();
+            result.DecodeEventNeedUpdate = !resultEvents.empty();
+
+            // WriteLog(LogLevel::LevelDebug, "Offset 1: %d" , offsetof(UsbDecodeEvent, PacketTitle));
+            // WriteLog(LogLevel::LevelDebug, "Offset 2: %d" , offsetof(UsbDecodeEvent, FrameId));
+            // WriteLog(LogLevel::LevelDebug, "Offset 2.5: %d" , offsetof(UsbDecodeEvent, EndPoint));
+            // WriteLog(LogLevel::LevelDebug, "Offset 3: %d" , offsetof(UsbDecodeEvent, CrcSignNum));
+            // WriteLog(LogLevel::LevelDebug, "Offset 3.5: %d" , offsetof(UsbDecodeEvent, CrcData));
+            // WriteLog(LogLevel::LevelDebug, "Offset 4: %d" , offsetof(UsbDecodeEvent, DataCount));
+            // WriteLog(LogLevel::LevelDebug, "Offset 5: %d" , offsetof(UsbDecodeEvent, DecodeDatasPtr));
+            return true;
+        }
+        return false;
+    }
+
+    bool USBDecoder::ParseSingleData(double set_bit_time_span)
+    {
+        if (signEdgePulse.empty()) return false;
+        WriteLog(LogLevel::Level2, "ParseSingleData start");
+
+        // 检查是否取消
+        if (canceled)
+        {
+            WriteLog(LogLevel::Level2, "AsyncFunction canceled");
+            return false;
+        }
+        int32_t left_data_size = static_cast<int32_t>(signEdgePulse.size());
+        //找数据包
+        if (FindPackets(left_data_size, usbPackets, set_bit_time_span))
+        {
+            if (usbPackets.empty())
+            {
+                WriteLog(LogLevel::Level2, "ParseSingleData false - usbPackets is empty");
+                return false;
+            }
+
+            for (auto&& element : usbPackets)
+            {
+                //resultData.Add(new UsbDecodeResultCell(element));
+                resultEvents.emplace_back(element);
+                resultEvents[resultEvents.size() - 1].EventIndex = static_cast<int64_t>(resultEvents.size());
+            }
+        }
+        WriteLog(LogLevel::Level2, "ParseSingleData done");
+        return true;
+    }
+
+    bool USBDecoder::CheckTimeDifferenceWithinThreshold(const double* array, int32_t size, double threshold)
+    {
+        //threshold = 0.15;
+        for (int i = 2; i < size; i++)
+        {
+            double difference = std::abs(array[i] - array[i - 1]);
+            double percentage_difference = difference / array[i - 1];
+            if (difference < 50)
+            {
+                threshold = USB_TIME_DIFFERENCE_THRESHOLD;
+            }
+            if (percentage_difference > threshold)
+            {
+                return false; // 如果差异大于阈值,则返回 false
+            }
+        }
+
+        return true; // 所有元素之间的差异都小于阈值
+    }
+
+    void USBDecoder::ClearEdgeArray(Protocol::Edge* edges, int32_t size)
+    {
+        for (int i = 0; i < size; ++i)
+        {
+            edges[i] = Protocol::Edge::None;
+        }
+    }
+
+    //检查同步域边沿
+    bool USBDecoder::CheckSyncEdges(Protocol::Edge start_edge, const Protocol::Edge* edges)
+    {
+        return edges[0] != edges[1] && edges[0] == start_edge && edges[0] == edges[6];
+    }
+
+    //检查同步域在时域间隔
+    bool USBDecoder::CheckSyncSpans(const Protocol::TwoLevelEdgePulse* node, const int32_t count, int32_t& avg_spans)
+    {
+        if (count < 1)
+        {
+            return false;
+        }
+        auto start_indexs = new int32_t[count + 1];
+        avg_spans = 0;
+        if ((node - 1) != nullptr)
+        {
+            node--;
+        }
+
+        for (int i = count - 1; i >= 0; i--)
+        {
+            node--;
+            if (node == nullptr)
+            {
+                return false;
+            }
+            start_indexs[i] = node->StartIndex;
+        }
+        return CheckSyncSpansByArray(start_indexs, count, avg_spans);
+    }
+
+
+    bool USBDecoder::CheckSyncSpansByArray(const int32_t* start_indexs, const int32_t count,
+                                           int32_t& avg_spans)
+    {
+        if (count < 1)
+        {
+            return false;
+        }
+
+        auto tmp_spans = new double[count - 1];
+        for (int i = 1; i < count; i++)
+        {
+            tmp_spans[i - 1] = static_cast<double>(start_indexs[i] - start_indexs[i - 1]);
+        }
+
+        double total_spans = 0;
+        for (int i = 0; i < count - 1; i++)
+        {
+            total_spans += std::abs(tmp_spans[2 + (i / 2)]);
+        }
+        avg_spans = static_cast<int>(total_spans / (count - 1));
+        return CheckTimeDifferenceWithinThreshold(tmp_spans, count - 1);
+    }
+
+    bool USBDecoder::FindAllSyncs(Protocol::TwoLevelEdgePulse* node, std::vector<SYNC>& all_sync
+                                  , double set_bit_time_span, bool polarity)
+    {
+        all_sync.clear();
+        int first_avg_span = 0;
+
+        if (node == nullptr || node - 1 == nullptr)
+        {
+            return false;
+        }
+
+        constexpr int sync_bit_len = 8;
+        Edge next_edge = polarity ? Protocol::Edge::Rise : Protocol::Edge::Falling;
+        Edge start_edge = next_edge;
+
+        TwoLevelEdgePulse* start_info_node = nullptr;
+        Edge tmp_edges[sync_bit_len];
+        TwoLevelEdgePulse* tmp_edges_ptr[sync_bit_len];
+        int32_t tmp_edges_len[sync_bit_len];
+        ClearEdgeArray(tmp_edges, sync_bit_len);
+
+        int tmp_edge_count = 0;
+        Protocol::TwoLevelEdgePulse* tmp_node = node;
+
+        while (tmp_node != nullptr)
+        {
+            if (canceled)
+            {
+                WriteLog(LogLevel::Level2, "AsyncFunction canceled");
+                return false;
+            }
+            if (tmp_node->StartIndex < 0 || tmp_node->EndIndex < 0
+                || tmp_node->StartIndex > tmp_node->EndIndex || tmp_node->LevelCount() <= 0)
+            {
+                WriteLog(LogLevel::Level2, "FindAllSyncs break,SYNC count:%d", all_sync.size());
+                break;
+            }
+            //可能找到目标头
+            if (first_avg_span != 0 && tmp_node->GetLength() > first_avg_span * 8)
+            {
+                tmp_edge_count = 0;
+            }
+
+            if (tmp_edge_count <= 7)
+            {
+                if (tmp_edge_count == 0)
+                {
+                    start_info_node = tmp_node;
+                }
+
+                tmp_edges[tmp_edge_count] = tmp_node->Edge;
+                tmp_edges_ptr[tmp_edge_count] = tmp_node;
+                tmp_edges_len[tmp_edge_count] = tmp_node->GetLength();
+                tmp_edge_count++;
+            }
+            else
+            {
+                if (CheckSyncEdges(start_edge, tmp_edges))
+                {
+                    int avg_spans;
+                    if (CheckSyncSpans(tmp_node, sync_bit_len - 1, avg_spans))
+                    {
+                        if (all_sync.empty())
+                        {
+                            int32_t set_bit_span = static_cast<int>(set_bit_time_span);
+
+                            first_avg_span = set_bit_span >= 0 ? set_bit_span : avg_spans;
+                            all_sync.emplace_back(start_info_node, (tmp_node - 2)->StartIndex + first_avg_span,
+                                                  first_avg_span);
+                        }
+                        else if (start_info_node != nullptr && (start_info_node - 1) != nullptr && (start_info_node - 1)->
+                            GetLength() > first_avg_span * 8)
+                        {
+                            int32_t set_bit_span = static_cast<int>(set_bit_time_span);
+                            avg_spans = set_bit_span >= 0 ? set_bit_span : avg_spans;
+                            all_sync.emplace_back(start_info_node, (tmp_node - 2)->StartIndex + avg_spans,
+                                                  avg_spans);
+                        }
+
+                        ClearEdgeArray(tmp_edges, sync_bit_len);
+                        tmp_edge_count = 0;
+                        tmp_node++;
+                        //left_over_size--;
+                        continue;
+                    }
+                    else
+                    {
+                    }
+                }
+
+                for (int i = 0; i < sync_bit_len - 1; i++)
+                {
+                    tmp_edges[i] = tmp_edges[i + 1];
+                    tmp_edges_ptr[i] = tmp_edges_ptr[i + 1];
+                    tmp_edges_len[i] = tmp_edges_len[i + 1];
+                }
+
+                tmp_edges[sync_bit_len - 1] = tmp_node->Edge;
+                tmp_edges_ptr[sync_bit_len - 1] = tmp_node;
+                tmp_edges_len[sync_bit_len - 1] = tmp_node->GetLength();
+                start_info_node++;
+            }
+
+            tmp_node++;
+            //left_over_size--;
+        }
+
+        return !all_sync.empty();
+    }
+
+    bool USBDecoder::FindPackets(int32_t& left_over_size,
+                                 std::vector<USBPacket>& all_packet, double set_bit_time_span,
+                                 bool polarity)
+    {
+        Protocol::TwoLevelEdgePulse* node = signEdgePulse.data();
+        all_packet.clear();
+        std::vector<SYNC> all_sync;
+        //找的全部同步帧
+        if (!FindAllSyncs(node, all_sync, set_bit_time_span, polarity) || all_sync.empty())
+        {
+            return false;
+        }
+
+        for (const auto& sync : all_sync)
+        {
+            if (sync.NodePtr == nullptr)
+            {
+                continue;
+            }
+            if (canceled)
+            {
+                WriteLog(LogLevel::Level2, "AsyncFunction canceled");
+                return false;
+            }
+            Protocol::TwoLevelEdgePulse* tmp_node = sync.NodePtr;
+
+            int32_t eop_index = -1;
+            //有差分Eop情况
+            if (!differenceEopIndexs.empty() && differenceEopIndexs.size() > all_packet.size())
+            {
+                eop_index = differenceEopIndexs[all_packet.size()];
+            }
+            if (eop_index <= 0)
+            {
+                //如果存在后续同步帧,用下个同步帧头-1的起始做可能结束 
+                if (static_cast<int32_t>(all_sync.size()) > (all_packet.size() + 2))
+                {
+                    eop_index = (all_sync[all_packet.size() + 2].NodePtr - 1)->StartIndex;
+                }
+                else
+                {
+                    eop_index = waveMaxTimeIndexLen;
+                }
+            }
+            int32_t packetMaxTimeLen = eop_index - sync.NodePtr->StartIndex;
+            if (packetMaxTimeLen <= 0)
+            {
+                WriteLog(LogLevel::Level2, "FindPackets Warning: packetMaxTimeLen <= 0");
+            }
+            USBPacket packet(tmp_node, left_over_size, sync, polarity, packetMaxTimeLen);
+            if (packet.IsValid())
+            {
+                all_packet.push_back(packet);
+            }
+        }
+
+        return true;
+    }
+    bool USBDecoder::CheckOptions(UsbDecodeOptions option, const std::vector<Protocol::TwoLevelEdgePulse>& edge_pulses_dp,
+                                  const std::vector<Protocol::TwoLevelEdgePulse>& edge_pulses_dm, double& set_bit_time_span)
+    {
+        double usb_speed = 0;
+        switch (option.USBSpeed)
+        {
+        case USBEnums::USBSpeed::LOW_SPEED:
+            usb_speed = USB_LOW_SPEED_MHZ;
+            break;
+        case USBEnums::USBSpeed::FULL_SPEED:
+            usb_speed = USB_FULL_SPEED_MHZ;
+            break;
+        case USBEnums::USBSpeed::HIGH_SPEED:
+            usb_speed = USB_HIGH_SPEED_MHZ;
+            break;
+        default:
+            WriteLog(LogLevel::Level2, "CheckOptions Failed, usbSpeed error");
+            return false;
+        }
+        if (!option.AutoClock && option.SamplingFrequency < usb_speed * 2)
+        {
+            WriteLog(LogLevel::Level2, "CheckOptions Failed, samplingFrequency error");
+            return false;
+        }
+        if (option.SignType == SignType::SingleEnded)
+        {
+            WriteLog(LogLevel::Level2, "CheckOptions SignType:%d", static_cast<int>(option.SignType));
+            if (edge_pulses_dp.size() < USB_MINIMUM_SEQUENCE_LENGTH && edge_pulses_dm.size() < USB_MINIMUM_SEQUENCE_LENGTH)
+            {
+                WriteLog(LogLevel::Level2, "CheckOptions Failed, edgePulses.size too short");
+                return false;
+            }
+        }
+        else
+        {
+            auto edgePulsesSize1 = static_cast<double>(edge_pulses_dp.size());
+            auto edgePulsesSize2 = static_cast<double>(edge_pulses_dm.size());
+            //// 差分长度判断
+            if (!DataCheckHelper::CheckDoubleIsEqual(edgePulsesSize1, edgePulsesSize2)
+                && ((USB_DIFF_LEN_DIFFERENCE_THRESHOLD * edgePulsesSize1) > edgePulsesSize2
+                    || (USB_DIFF_LEN_DIFFERENCE_THRESHOLD * edgePulsesSize2) > edgePulsesSize1))
+            {
+                WriteLog(LogLevel::Level2, "CheckOptions Failed,diff edgePulses size is not equal");
+                return false;
+            }
+
+            if (edge_pulses_dp.size() < USB_MINIMUM_SEQUENCE_LENGTH)
+            {
+                WriteLog(LogLevel::Level2, "CheckOptions Failed, edgePulses size too short");
+                return false;
+            }
+
+            usbDiffSignalRealEdgesCount = static_cast<int32_t>(edge_pulses_dp.size() > edge_pulses_dm.size()
+                                                                   ? edge_pulses_dm.size()
+                                                                   : edge_pulses_dp.size());
+        }
+        set_bit_time_span = option.SamplingFrequency / usb_speed;
+        return true;
+    }
+}

+ 99 - 0
ProtocolUSB/USBDecoder.h

@@ -0,0 +1,99 @@
+// // ******************************************************************
+// //       /\ /|       @File         USBDecoder.h
+// //       \ V/        @Brief
+// //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
+// //    *(__\_\
+// // ******************************************************************
+
+#pragma once
+#include <iostream>
+#include <future>
+#include <chrono>
+#include <thread>
+#include <cmath>
+
+#include "../EdgePulseData.h"
+#include "../EdgePulse.h"
+#include "../ProtocolDecodeBase.h"
+
+#include "SYNC.h"
+#include "ProtocolUSBEnums.h"
+#include "USBDecodeOptions.h"
+#include "USBDecodeResult.h"
+#include "USBPacket.h"
+
+namespace Protocol
+{
+    class USBDecoder
+    {
+    public:
+        USBDecoder() : usbDiffSignalRealEdgesCount(0)
+        {
+            differenceEopIndexs = {};
+            resultCells = {};
+            resultEvents = {};
+            usbPackets = {};
+            signEdgePulse = {};
+        }
+
+        static std::vector<std::string> EventInfoTitles();
+
+        bool DecodeUSB(const UsbDecodeOptions& option, const EdgePulseDataTwoLevels& edge_pulses_dp,
+                       const EdgePulseDataTwoLevels& edge_pulses_dm, UsbDecodeResult& result);
+
+    private:
+        std::vector<UsbDecodeResultCell> resultCells;
+        std::vector<UsbDecodeEvent> resultEvents;
+        std::vector<USBPacket> usbPackets;
+        std::vector<int32_t> differenceEopIndexs;
+
+        std::vector<Protocol::TwoLevelEdgePulse> signEdgePulse;
+
+        //usb差分信号非对齐位置
+        std::vector<int32_t> usbDiffUnalignedFramesIndex;
+
+        //差分信号可用长度
+        int32_t usbDiffSignalRealEdgesCount;
+        //传入波形最大时域长度
+        int32_t waveMaxTimeIndexLen;
+
+    private:
+        bool ParseDiffSignalData(std::vector<Protocol::TwoLevelEdgePulse> edge_pulses_dp,
+                                 std::vector<Protocol::TwoLevelEdgePulse> edge_pulses_dm)
+        {
+            //找出非对称边沿
+            //todo  add  differenceEopIndexs
+            //temp
+            signEdgePulse = std::move(edge_pulses_dp);
+
+            return true;
+        }
+
+        static bool CheckTimeDifferenceWithinThreshold(const double* array, int32_t size, double threshold = 0.15);
+
+        static void ClearEdgeArray(Protocol::Edge* edges, int32_t size);
+
+        static bool CheckSyncEdges(Protocol::Edge start_edge, const Protocol::Edge* edges);
+
+        //检查同步域在时域间隔
+        static bool CheckSyncSpans(const Protocol::TwoLevelEdgePulse* node, int32_t count,
+                                   int32_t& avg_spans);
+
+        static bool CheckSyncSpansByArray(const int32_t* start_indexs, int32_t count, int32_t& avg_spans);
+
+        static bool FindAllSyncs(Protocol::TwoLevelEdgePulse* node, std::vector<SYNC>& all_sync
+                                 , double set_bit_time_span, bool polarity = false);
+
+        // static bool FindAllSyncs(Protocol::TwoLevelEdgePulse* node, int32_t left_over_size,
+        //                          std::vector<SYNC>& all_sync, bool polarity = false);
+
+        bool FindPackets(int32_t& left_over_size,
+                         std::vector<USBPacket>& all_packet, double set_bit_time_span,
+                         bool polarity = false);
+        bool CheckOptions(UsbDecodeOptions option, const std::vector<Protocol::TwoLevelEdgePulse>& edge_pulses_dp,
+                          const std::vector<Protocol::TwoLevelEdgePulse>& edge_pulses_dm, double& set_bit_time_span);
+        bool ParseSingleData(double set_bit_time_span);
+    };
+}

+ 443 - 99
ProtocolUSB/USBPacket.cpp

@@ -2,40 +2,53 @@
 // //       /\ /|       @File         USBPacket.cpp
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-3
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #include "USBPacket.h"
 #include "../BaseHelper/CommonHelper.h"
- 
+#include "../BaseHelper/Logger.h"
+
 namespace Protocol
 {
-    USBPacket::USBPacket(): pid(0), lastNRBZDataBit(false), polarity(false), endPoint(0), crc5(0), isValid(false),
-                            isCRCChecked(false)
+    USBPacket::USBPacket() : PacketTitle(), pid(0), last_NRBZ_data_bit(false), polarity(false), end_point(0), crc_sign_num(0),
+                             crc16(0), is_valid(false),
+                             is_crc_checked(false),
+                             to_extracted_next_data_start_index(-1),
+                             to_NRZI_decode_next_data_start_index(-1),
+                             max_possible_data_length(-1)
+
+
     {
     }
 
-    USBPacket::USBPacket(Protocol::TwoLevelEdgePulse* pidNode, int32_t& leftOverSize, SYNC sync, bool polarity)
+    USBPacket::USBPacket(Protocol::TwoLevelEdgePulse* pid_node, int32_t& left_over_size, const SYNC& sync
+                         , bool polarity, int32_t max_data_length)
     {
         this->polarity = polarity;
-        this->packetSYNC = sync;
+        packet_SYNC = sync;
+        if (max_data_length >= 0)
+        {
+            max_possible_data_length = max_data_length;
+        }
+
         //this->pidType = nullptr;
 
-        if (!GetPID(pidNode, leftOverSize))
+        if (!GetPID(pid_node))
         {
             return;
         }
 
-        isValid = true;
+        is_valid = true;
 
-        if (this->type == Enums::USBPacketType::NoDefine)
+        if (this->packet_type == USBEnums::USBPacketType::NO_DEFINE)
         {
             return;
         }
-
-        DecodeFields(pidNode, leftOverSize, sync);
+        //解码域内容
+        DecodeFields(pid_node);
     }
 
     bool USBPacket::CheckNibblesInverse(uint8_t value)
@@ -45,43 +58,60 @@ namespace Protocol
         return highNibble == (~lowNibble & 0x0F);
     }
 
-    bool USBPacket::GetPID(Protocol::TwoLevelEdgePulse* pidNode, int32_t& leftOverSize)
+    bool USBPacket::GetPID(Protocol::TwoLevelEdgePulse*& pid_node)
     {
-        if (pidNode == nullptr || leftOverSize <= 0 || packetSYNC.SingleBitTimingLength <= 0)
+        if (!CheckNodeValid(static_cast<EdgePulse>(*pid_node)))
         {
+            WriteLog(LogLevel::Level2, "node check fail");
             return false;
         }
-        lastNRBZDataBit = true;
+        if (packet_SYNC.SingleBitTimingLength <= 0)
+        {
+            return false;
+        }
+        last_NRBZ_data_bit = false;
         uint8_t data;
-        if (!DecodeNextByte(pidNode, leftOverSize, data))
+        int32_t pid_start_index = packet_SYNC.EndIndex;
+
+        if (!DecodeNextByte(pid_node, pid_start_index, data))
         {
             return false;
         }
-        // if (pidNode != nullptr) {
-        //     pidEndIndex = pidNode.Parent().StartIndex();
-        // }
 
         pid = data;
-
-        if (CommonHelper::EnumIsDefined<Enums::TokenPackageType>(
-            static_cast<int>(RealPID())))
+        auto handshake_type = USBEnums::HandshakePackageType::NAK;
+        if (IsTokenPackageType())
         {
-            type = Enums::USBPacketType::Token;
+            packet_type = USBEnums::USBPacketType::TOKEN;
         }
-        else if (CommonHelper::EnumIsDefined<Enums::DataPackageType>(
-            static_cast<int>(RealPID())))
+        else if (IsDataPackageType())
         {
-            type = Enums::USBPacketType::Data;
+            packet_type = USBEnums::USBPacketType::DATA;
         }
-        else if (CommonHelper::EnumIsDefined<Enums::HandshakePackageType>(
-            static_cast<int>(RealPID())))
+        else if (IsHandshakePackageType(handshake_type))
         {
-            type = Enums::USBPacketType::HandShake;
+            packet_type = USBEnums::USBPacketType::HAND_SHAKE;
+            switch (handshake_type)
+            {
+            case USBEnums::HandshakePackageType::ACK:
+                PacketTitle = USBEnums::EventInfoTitles::ACK;
+                break;
+            case USBEnums::HandshakePackageType::NAK:
+                PacketTitle = USBEnums::EventInfoTitles::NAK;
+                break;
+            case USBEnums::HandshakePackageType::Stall:
+                PacketTitle = USBEnums::EventInfoTitles::STALL;
+                break;
+            case USBEnums::HandshakePackageType::Nyet:
+                PacketTitle = USBEnums::EventInfoTitles::NYET;
+                break;
+            default:  // NOLINT(clang-diagnostic-covered-switch-default)
+                return false;
+            }
         }
-        else if (CommonHelper::EnumIsDefined<Enums::SpecialPacketType>(
-            static_cast<int>(RealPID())))
+        else if (IsSpecialPacketType())
         {
-            type = Enums::USBPacketType::Special;
+            packet_type = USBEnums::USBPacketType::SPECIAL;
         }
         else
         {
@@ -90,152 +120,466 @@ namespace Protocol
         return true;
     }
 
-    bool USBPacket::DecodeNextByte(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, uint8_t& outData)
+    bool USBPacket::GetNRZIData(Protocol::TwoLevelEdgePulse*& node, int32_t need_bit_count, int32_t start_index,
+                                std::vector<bool>& out_data)
     {
-        outData = 0;
-        const bool highPolarityEdge = polarity;
-        const double singleBitTimingLengthThreshold = packetSYNC.SingleBitTimingLength * 0.95;
-        int gotbitCount = 0;
-        std::vector<bool> nrzi_data(8, false);
-
-        while (gotbitCount < 8)
+        if (!CheckNodeValid(node))
         {
-            if (node == nullptr || leftOverSize <= 0 || (*node).Edge == Protocol::Edge::None)
+            WriteLog(LogLevel::Level2, "node check fail");
+            return false;
+        }
+        const int32_t get_data_start_index = start_index;
+        //const int32_t get_data_start_index = node->StartIndex;
+        const bool high_polarity_edge = packet_SYNC.NodePtr->Edge == Protocol::Edge::Falling;
+        const double single_bit_timing_length_threshold = packet_SYNC.SingleBitTimingLength * USB_SYNC_BIT_TOL;
+        out_data = {};
+        //nrzi  补位个数
+        int32_t pre_complement_number = need_bit_count / USB_NRZI_COMPLEMENT_PER_NUM;
+        int32_t pre_complement_need_bit_count = need_bit_count + pre_complement_number;
+        std::vector<bool> nrzi_data(pre_complement_need_bit_count, false);
+        int32_t getbit_count = 0;
+        bool get_last_nrzi_bit_polarity = false;
+        while (getbit_count < pre_complement_need_bit_count)
+        {
+            if (!CheckNodeValid(node))
             {
+                WriteLog(LogLevel::Level2, "GetNRZIData node check fail");
                 return false;
             }
+            if (node->EndIndex < start_index)
+            {
+                node++;
+                continue;
+            }
+
+            ////fix
+            if (node->EndIndex - start_index < packet_SYNC.SingleBitTimingLength / 2)
+            {
+                node++;
+                if (!CheckNodeValid(node))
+                {
+                    WriteLog(LogLevel::Level2, "GetNRZIData node check fail");
+                    return false;
+                }
+            }
+            if (!get_last_nrzi_bit_polarity && CheckNodeValid(node - 1))
+            {
+                if (start_index - node->StartIndex > single_bit_timing_length_threshold)
+                {
+                    last_NRBZ_data_bit = node->CurrentLevel == TwoLevelEdgePulseStatusType::High;
+                }
+                else
+                {
+                    //不用改
+                    //last_NRBZ_data_bit = (node - 1)->CurrentLevel == TwoLevelEdgePulseStatusType::High;
+                }
 
-            if ((*node).EndIndex - (*node).StartIndex >= singleBitTimingLengthThreshold)
+                get_last_nrzi_bit_polarity = true;
+            }
+            if (node->EndIndex - start_index >= single_bit_timing_length_threshold)
             {
-                const int bitsCount = static_cast<int>(((*node).EndIndex - (*node).StartIndex) /
-                    singleBitTimingLengthThreshold);
+                const int bits_count = static_cast<int>((node->EndIndex - start_index) /
+                    single_bit_timing_length_threshold);
+
+                const int last_gotbit_count = getbit_count;
 
-                const int lastGotbitCount = gotbitCount;
-                for (int i = 0; i < bitsCount; i++)
+                for (int i = 0; i < bits_count; i++)
                 {
-                    if (lastGotbitCount + i >= 8)
+                    if (last_gotbit_count + i >= pre_complement_need_bit_count)
                     {
-                        continue;
+                        break;
                     }
-                    nrzi_data[lastGotbitCount + i] = highPolarityEdge == ((*node).Edge ==
+                    if ((last_gotbit_count + i) >= static_cast<int32_t>(nrzi_data.size()))
+                    {
+                        WriteLog(LogLevel::Level2, "GetNRZIData error: last_gotbit_count + i > nrzi_data.size()");
+                        break;
+                    }
+                    nrzi_data[last_gotbit_count + i] = high_polarity_edge == (node->Edge ==
                         Protocol::Edge::Rise);
-
-                    gotbitCount++;
+                    getbit_count++;
+                    start_index += packet_SYNC.SingleBitTimingLength;
                 }
             }
-            leftOverSize--;
+            else
+            {
+                nrzi_data[getbit_count] = node->Edge == Protocol::Edge::Rise;
+                getbit_count++;
+            }
+            if (getbit_count == pre_complement_need_bit_count)
+            {
+                break;
+            }
             node++;
+            if (start_index < node->StartIndex)
+            {
+                start_index = node->StartIndex;
+            }
         }
+        //待提取下个位标_位移数
+        int32_t move_bit_count = 0;
+
+        //lastNRBZDataBit = node->Edge == Edge::Rise;
+        //处理连续 输出结果
 
-        for (int i = 0; i < 8; i++)
+        int32_t continuous_count = 0;
+        bool last_value = false;
+        for (bool data : nrzi_data)
         {
-            if (lastNRBZDataBit != nrzi_data[i])
+            move_bit_count++;
+
+            //6个连续下一个翻转,必然是插入的bit
+            if (continuous_count == USB_NRZI_COMPLEMENT_PER_NUM && data != last_value)
+            {
+                continuous_count = 0;
+                continue;
+            }
+            if (last_value == data)
             {
-                lastNRBZDataBit = nrzi_data[i];
+                continuous_count++;
             }
             else
             {
-                outData |= (1 << i);
+                last_value = data;
+                continuous_count = 0;
+            }
+
+            out_data.push_back(data);
+            if (static_cast<int32_t>(out_data.size()) == need_bit_count)
+            {
+                // if (get_data_start_index == packetSYNC.NodePtr->StartIndex)
+                // {
+                // 	to_extracted_next_data_start_index = packetSYNC.EndIndex;
+                // }
+                // else
+                // {
+                to_extracted_next_data_start_index = get_data_start_index + (move_bit_count * packet_SYNC.
+                    SingleBitTimingLength);
+                //}
+                //while (pre_complement_number > 0 && to_extracted_next_data_start_index > 0 && to_extracted_next_data_start_index
+                //    < node->StartIndex)
+                //{
+                //    //退回多抽的点位标
+                //    pre_complement_number--;
+                //    node--;
+                //}
+                while (to_extracted_next_data_start_index > 0 && to_extracted_next_data_start_index
+                    < node->StartIndex)
+                {
+                    //退回多抽的点位标
+                    node--;
+                }
+                return true;
             }
         }
 
-        return true;
+        WriteLog(LogLevel::LevelDebug, "GetNRZIData return fail");
+        return false;
+    }
+    //NRZI解码下个字节
+    bool USBPacket::DecodeNextByteByDataField(Protocol::TwoLevelEdgePulse*& node, uint8_t& out_data)
+    {
+        bool result = DecodeNextByte(node, to_extracted_next_data_start_index, out_data);
+
+        return result;
     }
 
-    void USBPacket::DecodeFields(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, const SYNC& sync)
+    void USBPacket::NRBZToNormalData(const Protocol::TwoLevelEdgePulse* node,
+                                     int32_t need_bit_count, std::vector<bool> nrzi_data, uint8_t& out_data)
     {
-        if (leftOverSize <= 0)
+        //lastNRBZDataBit = node->Edge == Edge::Rise;
+        for (int i = 0; i < need_bit_count; i++)
         {
-            return;
+            //信号不变,就是数据1
+            if (last_NRBZ_data_bit == nrzi_data[i])
+            {
+                out_data |= (1 << i);
+            }
+            else
+            {
+                //信号变了就是数据0
+            }
+            last_NRBZ_data_bit = nrzi_data[i];
+        }
+        //out_data = CommonHelper::ReverseOrderBits(out_data);
+    }
+    //NRZI解码下个字节
+    bool USBPacket::DecodeNextByte(Protocol::TwoLevelEdgePulse*& node, int32_t start_index, uint8_t& out_data)
+    {
+        out_data = 0;
+        int32_t need_bit_count = 8;
+        std::vector<bool> nrzi_data = {};
+        if (!GetNRZIData(node, need_bit_count, start_index, nrzi_data))
+        {
+            WriteLog(LogLevel::Level2, "DecodeNextByte GetNRZIData fail");
+            return false;
         }
-        switch (type)
+        NRBZToNormalData(node, need_bit_count, nrzi_data, out_data);
+        return true;
+    }
+    bool USBPacket::DecodeTokenBytes(Protocol::TwoLevelEdgePulse*& node, USBEnums::TokenPackageType type)
+    {
+        bool is_sof_type = type == USBEnums::TokenPackageType::SOF;
+        bool result;
+        if (!is_sof_type)
+        {
+            //7addr-4enp-5crc bit
+            //////////////////////////// addr ////////////////////////////
+            std::vector<bool> addr_data = {};
+            uint8_t addr = 0;
+            result = GetNRZIData(node, USB_ADDR_BIT_COUNT, to_extracted_next_data_start_index,
+                                 addr_data);
+            if (!result)
+            {
+                return false;
+            }
+            NRBZToNormalData(node, USB_ADDR_BIT_COUNT, addr_data
+                             , addr);
+            address.push_back(addr);
+            //////////////////////////// endpoint ////////////////////////////
+            std::vector<bool> endpoint_data = {};
+
+            result = GetNRZIData(node, USB_ENDPOINT_BIT_COUNT, to_extracted_next_data_start_index,
+                                 endpoint_data);
+            if (!result)
+            {
+                return false;
+            }
+            NRBZToNormalData(node, USB_ENDPOINT_BIT_COUNT, endpoint_data
+                             , end_point);
+        }
+        else
+        {
+            //11frame-5bitcrc
+            //////////////////////////// frame ////////////////////////////
+            std::vector<bool> frame_data = {};
+            uint8_t frame_id_tmp = 0;
+            datas = {};
+            result = GetNRZIData(node, USB_FRAMEID_BIT_COUNT, to_extracted_next_data_start_index,
+                                 frame_data);
+            if (!result)
+            {
+                return false;
+            }
+
+            NRBZToNormalData(node, USB_FRAMEID_BIT_COUNT, frame_data
+                             , frame_id_tmp);
+            datas.push_back(frame_id_tmp);
+            frame_id_tmp = 0;
+            for (int i = 8; i < USB_FRAMEID_BIT_COUNT - 8; i++)
+            {
+                if (last_NRBZ_data_bit != frame_data[i])
+                {
+                    last_NRBZ_data_bit = frame_data[i];
+                }
+                else
+                {
+                    frame_id_tmp |= (1 << i);
+                }
+            }
+            datas.push_back(frame_id_tmp);
+        }
+
+        //////////////////////////// CRC5 ////////////////////////////
+        std::vector<bool> crc_data = {};
+        uint8_t crc = 0;
+        result = GetNRZIData(node, USB_CRC5_BIT_COUNT, to_extracted_next_data_start_index,
+                             crc_data);
+        if (!result)
+        {
+            return false;
+        }
+
+        NRBZToNormalData(node, USB_CRC5_BIT_COUNT, crc_data
+                         , crc);
+        crc_sign_num = USB_CRC5_BIT_COUNT;
+        crc16 = crc;
+        WriteLog(LogLevel::LevelDebug, "DecodeTokenBytes = true,crc_sign_num=%d,crc=0x%x"
+                 , crc_sign_num, crc16);
+        return true;
+    }
+
+    void USBPacket::DecodeFields(Protocol::TwoLevelEdgePulse*& node)
+    {
+        switch (packet_type)  // NOLINT(clang-diagnostic-switch-enum)
         {
-        case Enums::USBPacketType::Token:
-            DecodeFieldsByToken(node, leftOverSize, sync);
+        case USBEnums::USBPacketType::TOKEN:
+            DecodeFieldsByToken(node);
             break;
-        case Enums::USBPacketType::Data:
-            DecodeFieldsByData(node, leftOverSize, sync);
+        case USBEnums::USBPacketType::DATA:
+
+            DecodeFieldsByData(node);
             break;
-        case Enums::USBPacketType::HandShake:
-            DecodeFieldsByHandShake(node, leftOverSize, sync);
+        case USBEnums::USBPacketType::HAND_SHAKE:
             break;
-        case Enums::USBPacketType::Special:
-            DecodeFieldsBySpecial(node, leftOverSize, sync);
+        case USBEnums::USBPacketType::SPECIAL:
+            DecodeFieldsBySpecial(node);
             break;
         default:
             break;
         }
     }
 
-    void USBPacket::DecodeFieldsByToken(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, const SYNC& sync)
+    void USBPacket::DecodeFieldsByToken(Protocol::TwoLevelEdgePulse*& node)
     {
-        if (type == Enums::USBPacketType::NoDefine)
+        if (packet_type == USBEnums::USBPacketType::NO_DEFINE)
         {
+            WriteLog(LogLevel::Level2, "DecodeFieldsByToken error:packetType is NO_DEFINE");
             return;
         }
 
-        //todo
-        auto packageType = static_cast<
-            Enums::TokenPackageType>(RealPID());
-        switch (packageType)
+        switch (static_cast<
+            USBEnums::TokenPackageType>(RealPID()))
         {
-        case Enums::TokenPackageType::Out:
+        case USBEnums::TokenPackageType::SOF:
+            PacketTitle = USBEnums::EventInfoTitles::SOF;
+            DecodeTokenBytes(node, USBEnums::TokenPackageType::SOF);
             break;
-        case Enums::TokenPackageType::SOF:
+        case USBEnums::TokenPackageType::Setup:
+            PacketTitle = USBEnums::EventInfoTitles::SETUP;
+            DecodeTokenBytes(node, USBEnums::TokenPackageType::Setup);
             break;
-        case Enums::TokenPackageType::IN:
+        case USBEnums::TokenPackageType::In:
+            PacketTitle = USBEnums::EventInfoTitles::TIN;
+            DecodeTokenBytes(node, USBEnums::TokenPackageType::In);
             break;
-        case Enums::TokenPackageType::SETUP:
+        case USBEnums::TokenPackageType::Out:
+            PacketTitle = USBEnums::EventInfoTitles::TOUT;
+            DecodeTokenBytes(node, USBEnums::TokenPackageType::Out);
             break;
         default:
-            break;
+            return;
         }
     }
 
-    void USBPacket::DecodeFieldsByData(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, const SYNC sync)
+    void USBPacket::DecodeFieldsByData(Protocol::TwoLevelEdgePulse*& node)
     {
-        if (type == Enums::USBPacketType::NoDefine)
+        if (packet_type == USBEnums::USBPacketType::NO_DEFINE)
         {
+            WriteLog(LogLevel::Level2, "DecodeFieldsByToken error:packetType is NO_DEFINE");
             return;
         }
-        auto packageType = static_cast<Enums::DataPackageType>
-            (RealPID());
-        switch (packageType)
+        int32_t end_index = packet_SYNC.NodePtr->EndIndex;
+        std::vector<uint8_t> get_data_tmp = {};
+        switch (auto package_type = static_cast<USBEnums::DataPackageType>(RealPID()))
         {
-        case Enums::DataPackageType::Data0:
-        case Enums::DataPackageType::Data1:
+        case USBEnums::DataPackageType::Data0:
+        case USBEnums::DataPackageType::Data1:
+            PacketTitle = package_type == USBEnums::DataPackageType::Data0
+                              ? USBEnums::EventInfoTitles::DATA0
+                              : USBEnums::EventInfoTitles::DATA1;
             datas.clear();
-            while (node != nullptr && (*node).StartIndex < sync.PacketEndIndex())
+
+            if (max_possible_data_length >= 0 && max_possible_data_length
+                > packet_SYNC.Length())
+            {
+                end_index = max_possible_data_length + packet_SYNC.NodePtr->StartIndex;
+            }
+            while (CheckNodeValid(node) && node->StartIndex < end_index)
             {
                 uint8_t data;
-                DecodeNextByte(node, leftOverSize, data);
-                datas.push_back(data);
+                bool result = DecodeNextByteByDataField(node, data);
+                if (!result)
+                {
+                    WriteLog(LogLevel::Level2, "DecodeFieldsByData DecodeNextByte fail:StartIndex:%d", node->StartIndex);
+                    break;
+                }
+                get_data_tmp.push_back(data);
+            }
+            if (get_data_tmp.size() > 2)
+            {
+                //data
+                for (uint64_t i = 0; i < get_data_tmp.size() - 2; i++)
+                {
+                    datas.push_back(get_data_tmp[i]);
+                }
+                //crc16
+                /* for (uint64_t i = (get_data_tmp.size() - 2); i < get_data_tmp.size(); i++)
+                 {
+                 }*/
+                uint8_t crc16_h = CommonHelper::ReverseOrderBits(get_data_tmp[get_data_tmp.size() - 2]);
+                uint8_t crc16_l = CommonHelper::ReverseOrderBits(get_data_tmp[get_data_tmp.size() - 1]);
+                crc16 = (static_cast<uint16_t>(crc16_h) << 8) + static_cast<uint16_t>(crc16_l) ;
+               
+                crc_sign_num = 16;
             }
+            else
+            {
+                WriteLog(LogLevel::Level2, "Waring:DecodeFieldsByData Decode DataSize < 2 (%d)", get_data_tmp.size());
+                datas = std::move(get_data_tmp);
+            }
+            get_data_tmp.clear();
             break;
-        case Enums::DataPackageType::Data2:
+        case USBEnums::DataPackageType::Data2:
+            PacketTitle = USBEnums::EventInfoTitles::DATA2;
             break;
-        case Enums::DataPackageType::MData:
+        case USBEnums::DataPackageType::MData:
+            PacketTitle = USBEnums::EventInfoTitles::MDATA;
             break;
         default:
             break;
         }
     }
 
-    void USBPacket::DecodeFieldsByHandShake(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, SYNC sync)
+    void USBPacket::DecodeFieldsBySpecial(Protocol::TwoLevelEdgePulse*& node)
     {
         //todo
-        if (type != Enums::USBPacketType::HandShake)
+        if (packet_type != USBEnums::USBPacketType::SPECIAL)
         {
             return;
         }
     }
-
-    void USBPacket::DecodeFieldsBySpecial(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, SYNC sync)
+    bool USBPacket::IsTokenPackageType() const
     {
-        //todo
-        if (type != Enums::USBPacketType::Special)
+        int32_t real_pid = RealPID();
+        if (static_cast<int32_t>(USBEnums::TokenPackageType::In) == real_pid
+            || static_cast<int32_t>(USBEnums::TokenPackageType::Out) == real_pid
+            || static_cast<int32_t>(USBEnums::TokenPackageType::Setup) == real_pid
+            || static_cast<int32_t>(USBEnums::TokenPackageType::SOF) == real_pid
+        )
         {
-            return;
+            return true;
+        }
+        return false;
+    }
+    bool USBPacket::IsSpecialPacketType() const
+    {
+        int32_t real_pid = RealPID();
+        if (static_cast<int32_t>(USBEnums::SpecialPacketType::Err) == real_pid
+            || static_cast<int32_t>(USBEnums::SpecialPacketType::Ping) == real_pid
+            || static_cast<int32_t>(USBEnums::SpecialPacketType::Remain) == real_pid
+            || static_cast<int32_t>(USBEnums::SpecialPacketType::Split) == real_pid
+        )
+        {
+            return true;
+        }
+        return false;
+    }
+    bool USBPacket::IsHandshakePackageType(USBEnums::HandshakePackageType& type) const
+    {
+        int32_t real_pid = RealPID();
+        if (static_cast<int32_t>(USBEnums::HandshakePackageType::Nyet) == real_pid
+            || static_cast<int32_t>(USBEnums::HandshakePackageType::Stall) == real_pid
+            || static_cast<int32_t>(USBEnums::HandshakePackageType::ACK) == real_pid
+            || static_cast<int32_t>(USBEnums::HandshakePackageType::NAK) == real_pid
+        )
+        {
+            type = static_cast<USBEnums::HandshakePackageType>(real_pid);
+            return true;
+        }
+        return false;
+    }
+    bool USBPacket::IsDataPackageType()
+    {
+        int32_t real_pid = RealPID();
+        if (static_cast<int32_t>(USBEnums::DataPackageType::Data0) == real_pid
+            || static_cast<int32_t>(USBEnums::DataPackageType::Data1) == real_pid
+            || static_cast<int32_t>(USBEnums::DataPackageType::Data2) == real_pid
+            || static_cast<int32_t>(USBEnums::DataPackageType::MData) == real_pid
+        )
+        {
+            to_NRZI_decode_next_data_start_index = packet_SYNC.EndIndex + (packet_SYNC.OneByteTimingLength);
+            return true;
         }
+        return false;
     }
 }

+ 54 - 28
ProtocolUSB/USBPacket.h

@@ -2,8 +2,8 @@
 // //       /\ /|       @File         USBPacket.h
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-3
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -14,9 +14,10 @@
 #include "../BaseHelper//CommonHelper.h"
 #include "../BaseEnums/ProtocolEnums.h"
 #include "../EdgePulse.h"
+#include "ProtocolUSBEnums.h"
 
 #include "SYNC.h"
-#include "ProtocolUSBEnums.h"
+
 
 namespace Protocol
 {
@@ -24,52 +25,77 @@ namespace Protocol
     {
     public:
         USBPacket();
-        USBPacket(Protocol::TwoLevelEdgePulse* pidNode, int32_t& leftOverSize, SYNC sync, bool polarity);
+        USBPacket(Protocol::TwoLevelEdgePulse* pid_node, int32_t& left_over_size, const SYNC& sync, bool polarity,
+                  int32_t max_data_length);
 
-        Enums::USBPacketType Type() const { return type; }
+        USBEnums::USBPacketType Type() const { return packet_type; }
         uint8_t PID() const { return pid; }
         void SetPID(uint8_t value) { pid = value; }
-        bool LastNRBZDataBit() const { return lastNRBZDataBit; }
+        bool LastNRBZDataBit() const { return last_NRBZ_data_bit; }
         uint8_t RealPID() const { return static_cast<uint8_t>(pid & 0xF); }
         //const std::type_info& PIDType() const { return pidType; }
         //int PIDEndIndex() const { return pidEndIndex; }
         bool Polarity() const { return polarity; }
-        const SYNC PacketSYNC() const { return packetSYNC; }
+        const SYNC PacketSYNC() const { return packet_SYNC; }
         const std::vector<uint8_t>& Address() const { return address; }
-        uint8_t EndPoint() const { return endPoint; }
+        uint8_t EndPoint() const { return end_point; }
         const std::vector<uint8_t>& Datas() const { return datas; }
-        uint8_t CRC5() const { return crc5; }
-        bool IsValid() const { return isValid; }
-        bool IsCRCChecked() const { return isCRCChecked; }
+        uint16_t CRC16() const { return crc16; }
+        // //CRC数据有效位
+        uint8_t CRCSignNum() const { return crc_sign_num; }
+        bool IsValid() const { return is_valid; }
+        bool IsCRCChecked() const { return is_crc_checked; }
+        USBEnums::EventInfoTitles PacketTitle;
+        int32_t GetEndIndex() const { return to_extracted_next_data_start_index; }
+        int32_t GetStartIndex() const { return packet_SYNC.NodePtr->StartIndex; }
 
     private:
-        Enums::USBPacketType type = Enums::USBPacketType::NoDefine;
+        USBEnums::USBPacketType packet_type = USBEnums::USBPacketType::NO_DEFINE;
         uint8_t pid;
-        bool lastNRBZDataBit;
-        //std::type_info& pidType;
-        //int pidEndIndex;
+        bool last_NRBZ_data_bit;
+
         bool polarity;
-        SYNC packetSYNC;
+        SYNC packet_SYNC;
         std::vector<uint8_t> address;
-        uint8_t endPoint;
+        uint8_t end_point;
         std::vector<uint8_t> datas;
-        uint8_t crc5;
-        bool isValid;
-        bool isCRCChecked;
+        //CRC数据有效位
+        uint8_t crc_sign_num;
+        uint16_t crc16;
+        bool is_valid;
+        bool is_crc_checked;
+        //待提取下个时域位标
+        int32_t to_extracted_next_data_start_index;
+        //待nrzi解码下个时域位标
+        int32_t to_NRZI_decode_next_data_start_index;
+        //最大可能数据时域长度
+        int32_t max_possible_data_length;
+        static bool CheckNibblesInverse(uint8_t value);
+
+        bool GetPID(Protocol::TwoLevelEdgePulse* & pid_node);
 
-        bool CheckNibblesInverse(uint8_t value);
+        //bool DecodeNextByte(const Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, uint8_t& outData);
 
-        bool GetPID(Protocol::TwoLevelEdgePulse* pidNode, int32_t& leftOverSize);
+        bool GetNRZIData(Protocol::TwoLevelEdgePulse* & node, int32_t need_bit_count, int32_t start_index,
+                         std::vector<bool>& out_data);
 
-        bool DecodeNextByte(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, uint8_t& outData);
+        bool DecodeNextByteByDataField(Protocol::TwoLevelEdgePulse* & node, uint8_t& out_data);
+        void NRBZToNormalData(const Protocol::TwoLevelEdgePulse* node, int32_t need_bit_count, std::vector<bool> nrzi_data,
+                              uint8_t& out_data);
+        bool DecodeNextByte(Protocol::TwoLevelEdgePulse* & node, int32_t start_index, uint8_t& out_data);
+        bool DecodeTokenBytes(Protocol::TwoLevelEdgePulse* & node, USBEnums::TokenPackageType type);
+        void DecodeFields(Protocol::TwoLevelEdgePulse* & node);
 
-        void DecodeFields(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, const SYNC& sync);
+        void DecodeFieldsByToken(Protocol::TwoLevelEdgePulse* & node);
+        void DecodeFieldsByData(Protocol::TwoLevelEdgePulse* & node);
 
-        void DecodeFieldsByToken(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, const SYNC& sync);
-        void DecodeFieldsByData(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, const SYNC sync);
+        //void DecodeFieldsByHandShake(Protocol::TwoLevelEdgePulse* node, SYNC sync);
 
-        void DecodeFieldsByHandShake(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, SYNC sync);
+        void DecodeFieldsBySpecial(Protocol::TwoLevelEdgePulse* & node);
 
-        void DecodeFieldsBySpecial(Protocol::TwoLevelEdgePulse* node, int32_t& leftOverSize, SYNC sync);
+        bool IsTokenPackageType() const;
+        bool IsSpecialPacketType() const;
+        bool IsHandshakePackageType(USBEnums::HandshakePackageType& type) const;
+        bool IsDataPackageType();
     };
 }

+ 2 - 2
ProtocolUSB/UsbDecodeEvent.cpp

@@ -2,8 +2,8 @@
 // //       /\ /|       @File         UsbDecodeEvent.cpp
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 57 - 2
ProtocolUSB/UsbDecodeEvent.h

@@ -2,12 +2,13 @@
 // //       /\ /|       @File         UsbDecodeEvent.h
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #pragma once
+#include "USBPacket.h"
 #include "../DecodeEvent.h"
 
 namespace Protocol
@@ -15,5 +16,59 @@ namespace Protocol
     struct UsbDecodeEvent : Protocol::DecodeBaseEvent
     {
     public:
+        USBEnums::EventInfoTitles PacketTitle;
+        int32_t Address;
+        int32_t FrameId;
+        int16_t Port;
+        int16_t EndPoint;
+        int16_t CrcSignNum;
+        uint16_t CrcData;
+        uint64_t DataCount;
+        const uint8_t* DecodeDatasPtr;
+
+        UsbDecodeEvent(const USBPacket& packet): FrameId(-1), Port(-1), EndPoint(-1), CrcSignNum(0),
+                                                 CrcData(0), DataCount(0), DecodeDatasPtr(nullptr)
+        {
+            PacketTitle = packet.PacketTitle;
+            const std::vector<uint8_t>& address = packet.Address();
+            EndIndex = packet.GetEndIndex();
+            StartIndex = packet.GetStartIndex();
+            if (!address.empty())
+            {
+                int32_t size = static_cast<int>(address.size());
+                if (size > 4) size = 4;
+                for (int i = 0; i < size; i++)
+                {
+                    Address = address[i] << (i * 8);
+                }
+            }
+            else
+            {
+                Address = -1;
+            }
+
+            EndPoint = packet.EndPoint();
+            if (packet.Datas().empty())
+            {
+                FrameId = -1;
+                DecodeDatasPtr = nullptr;
+                DataCount = 0;
+                CrcData = packet.CRC16();
+                CrcSignNum = packet.CRCSignNum();
+                return;
+            }
+            std::vector<uint8_t> datas = packet.Datas();
+            if (PacketTitle == USBEnums::EventInfoTitles::SOF && datas.size() == 2)
+            {
+                FrameId = datas[0] + datas[1] * 8;
+            }
+            DecodeDatasPtr = packet.Datas().data();
+            DataCount = packet.Datas().size();
+            CrcData = packet.CRC16();
+            CrcSignNum = packet.CRCSignNum();
+        }
+
+    private:
+
     };
 }

+ 6 - 2
ProtocolUSB/UsbDecodeOptions.h

@@ -3,17 +3,21 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-17
-// //      /  \\        @Modified      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
 #pragma once
 
+#include "ProtocolUSBEnums.h"
+
 namespace Protocol
 {
-
     struct UsbDecodeOptions
     {
         SignType SignType; //信号类型 差分、单端
+        double SamplingFrequency;//信号采样率
+        USBEnums::USBSpeed USBSpeed;//USB 速度
+        bool AutoClock;//自动时钟 自适应采样率 速度
     };
 }

+ 6 - 6
ProtocolUSB/UsbDecodeResult.cpp

@@ -2,8 +2,8 @@
 // //       /\ /|       @File         UsbDecodeResult.cpp
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -11,10 +11,10 @@
 
 namespace Protocol
 {
-    void UsbDecodeResult::Add(const UsbDecodeResultCell* cell)
-    {
-        DecodeResultCells.push_back(*cell);
-    }
+    // void UsbDecodeResult::Add(const UsbDecodeResultCell* cell)
+    // {
+    //     DecodeResultCells.push_back(*cell);
+    // }
 
     // void UsbDecodeResult::ClearData()
     // {

+ 64 - 14
ProtocolUSB/UsbDecodeResult.h

@@ -2,8 +2,8 @@
 // //       /\ /|       @File         UsbDecodeResult.h
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
-// //       /  |        @Creation      2024-1-4
-// //      /  \\        @Modified      2024-1-15
+// //       /  |        @Creation      2024-05-17
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 
@@ -11,31 +11,81 @@
 #include <utility>
 
 #include "ProtocolUSBEnums.h"
+#include "UsbDecodeEvent.h"
 #include "../DecodeResult.h"
 #include "USBPacket.h"
 #include "../DecodeEvent.h"
 
 namespace Protocol
 {
-    class UsbDecodeResultCell : Protocol::DecodeResultCell
+    class UsbDecodeResultCell : DecodeResultCell
     {
     public:
-        USBPacket GetUsbPacket() { return usbPacket; }
 
-        UsbDecodeResultCell(USBPacket packet)
-        {
-            usbPacket = std::move(packet);
-        }
 
     private:
-        USBPacket usbPacket;
+
     };
 
-    struct UsbDecodeResult : Protocol::DecodeResult
+    struct UsbDecodeResult //: DecodeResult
     {
-        void Add(const UsbDecodeResultCell* cell);
- 
-        std::vector<UsbDecodeResultCell> DecodeResultCells;
-        //std::vector<UsbDecodeEvent> DecodeEventCells; //TODO
+        bool DecodeResultNeedUpdate = false;
+        bool DecodeEventNeedUpdate = false;
+        UsbDecodeResultCell* DecodeResultCellsPtr; //解码数据结果指针
+        UsbDecodeEvent* DecodeEventsPtr; //解码结果事件指针
+        uint64_t DecodeResultCount; //结果数量
+        uint64_t DecodeEventCount; //事件数量
+        //std::vector<UsbDecodeResultCell> DecodeResultCells;
+        //std::vector<UsbDecodeEvent> DecodeEventCells;  
+        UsbDecodeResult(): DecodeResultCellsPtr(nullptr), DecodeEventsPtr(nullptr), DecodeResultCount(0), DecodeEventCount(0)
+        {
+            //ProtocolType = SerialProtocolType::USB;
+            //DecodeResultCells = {};
+        }
+        UsbDecodeResult(const UsbDecodeResult& result)
+        {
+            DecodeResultNeedUpdate = result.DecodeResultNeedUpdate;
+            DecodeEventNeedUpdate = result.DecodeEventNeedUpdate;
+            DecodeResultCellsPtr = result.DecodeResultCellsPtr;
+            DecodeEventsPtr = result.DecodeEventsPtr;
+
+            DecodeResultCount = result.DecodeResultCount;
+            DecodeEventCount = result.DecodeEventCount;
+        }
+        ~UsbDecodeResult() = default;
+
+        UsbDecodeResult(UsbDecodeResult&& other) noexcept
+            : DecodeResultNeedUpdate(other.DecodeResultNeedUpdate),
+              DecodeEventNeedUpdate(other.DecodeEventNeedUpdate),
+              DecodeResultCellsPtr(other.DecodeResultCellsPtr),
+              DecodeEventsPtr(other.DecodeEventsPtr),
+              DecodeResultCount(other.DecodeResultCount),
+              DecodeEventCount(other.DecodeEventCount)
+        {
+        }
+        UsbDecodeResult& operator=(const UsbDecodeResult& other)
+        {
+            if (this == &other) return *this;
+            DecodeResultNeedUpdate = other.DecodeResultNeedUpdate;
+            DecodeEventNeedUpdate = other.DecodeEventNeedUpdate;
+            DecodeResultCellsPtr = other.DecodeResultCellsPtr;
+            DecodeEventsPtr = other.DecodeEventsPtr;
+            DecodeResultCount = other.DecodeResultCount;
+            DecodeEventCount = other.DecodeEventCount;
+            return *this;
+        }
+        UsbDecodeResult& operator=(UsbDecodeResult&& other) noexcept
+        {
+            if (this == &other) return *this;
+            DecodeResultNeedUpdate = other.DecodeResultNeedUpdate;
+            DecodeEventNeedUpdate = other.DecodeEventNeedUpdate;
+            DecodeResultCellsPtr = other.DecodeResultCellsPtr;
+            DecodeEventsPtr = other.DecodeEventsPtr;
+            DecodeResultCount = other.DecodeResultCount;
+            DecodeEventCount = other.DecodeEventCount;
+            return *this;
+        }
+        //void Add(const UsbDecodeResultCell* cell);
     };
+
 }

+ 1 - 1
QuantizeParams.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
QuantizeParams.h

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************
 

+ 1 - 1
dllmain.cpp

@@ -3,7 +3,7 @@
 // //       \ V/        @Brief
 // //       | "")       @Author        lijinwen, ghz005@uni-trend.com.cn
 // //       /  |        @Creation      2024-05-16
-// //      /  \\        @Modified      2024-05-16
+// //      /  \\        @Modified      2024-05-30
 // //    *(__\_\
 // // ******************************************************************