DeviceCommons 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package DeviceCommons --version 1.0.0
                    
NuGet\Install-Package DeviceCommons -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DeviceCommons" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DeviceCommons" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="DeviceCommons" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DeviceCommons --version 1.0.0
                    
#r "nuget: DeviceCommons, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DeviceCommons@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DeviceCommons&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=DeviceCommons&version=1.0.0
                    
Install as a Cake Tool

DeviceCommons

介绍

DeviceCommons 是一个专为 IoT 场景设计的高性能设备消息处理库,提供完整的序列化/反序列化解决方案。支持多种数据类型、压缩加密、CRC校验,以及灵活的扩展结构,特别适合资源受限的嵌入式设备和高效的后端数据处理。

消息整体结构

DeviceCommons 采用分层结构设计,完整的设备消息由以下部分组成:

+-----------------------------------------------+
|                 设备消息 (DeviceMessage)        |
| +-------------------------------------------+ |
| |               消息头 (Header)              | |
| +-------------------------------------------+ |
| |              主设备 (MainDevice)           | |
| | +---------------------------------------+ | |
| | |          设备信息 (DeviceInfo)         | | |
| | | +-----------------------------------+ | | |
| | | |             读数集合              | | | |
| | | | +-------------------------------+ | | | |
| | | | |            读数数组            | | | | |
| | | | | +---------------------------+ | | | | |
| | | | | |          状态数组          | | | | | |
| | | | | | +-----------------------+ | | | | | |
| | | | | | |       状态值           | | | | | | |
| | | | | | +-----------------------+ | | | | | |
| | | | | +---------------------------+ | | | | |
| | | | +-------------------------------+ | | | |
| | | +-----------------------------------+ | | |
| | +---------------------------------------+ | |
| +-------------------------------------------+ |
| |             子设备集合 (ChildDevices)      | |
| | +---------------------------------------+ | |
| | |            子设备信息数组              | | |
| | | +-----------------------------------+ | | |
| | | |          设备信息 (DeviceInfo)     | | | |
| | | |          (与主设备结构相同)         | | | |
| | | +-----------------------------------+ | | |
| | +---------------------------------------+ | |
| +-------------------------------------------+ |
+-----------------------------------------------+
详细组件说明

1. 消息头 (DeviceMessageHeader)

消息头包含协议的元数据信息:

字段 类型 长度 描述
Header byte[] 2字节 固定头标识 (0xC0, 0xBF)
Version byte 1字节 协议版本号
Mark byte 1字节 标志位组合字段
└ TimeStampFormat 位0 1位 时间戳格式 (0:毫秒, 1:秒)
└ ValueType 位1 1位 值类型格式 (0:标准, 1:扩展)
└ Reserve1 位2 1位 保留位1
└ Reserve2 位3 1位 保留位2
└ CRCType 位4-7 4位 CRC校验类型 (0:无,1:CRC8,2:CRC16,3:CRC32)

2. 设备信息 (DeviceMessageInfo)

设备信息描述单个设备的基本属性和数据:

字段 类型 长度 描述
Length byte 1字节 设备ID长度
DIDBytes byte[] 变长 设备ID的字节表示
DID string 变长 设备ID字符串
DeviceType byte 1字节 设备类型标识
Reading DeviceMessageInfoReadings 变长 设备读数集合

3. 读数集合 (DeviceMessageInfoReadings)

读数集合包含设备的多个读数记录:

字段 类型 长度 描述
Count byte 1字节 读数数量
ReadingArray DeviceMessageInfoReading[] 变长 读数数组

4. 单个读数 (DeviceMessageInfoReading)

单个读数表示设备在特定时间点的数据记录:

字段 类型 长度 描述
Offset byte[] 2字节 时间偏移量 (大端序)
TimeOffset short 2字节 时间偏移量 (数值形式)
State DeviceMessageInfoReadingStates 变长 状态数据集合

5. 状态集合 (DeviceMessageInfoReadingStates)

状态集合包含单个读数中的多个状态值:

字段 类型 长度 描述
Count byte 1字节 状态数量
StateArray DeviceMessageInfoReadingState[] 变长 状态数组

6. 单个状态 (DeviceMessageInfoReadingState)

单个状态表示设备的一个特定测量值或状态:

字段 类型 长度 描述
SID byte 1字节 状态标识符
Type byte 1字节 值类型标识
ValueType StateValueTypeEnum 1字节 值类型枚举
Value byte[] 变长 值的字节表示
ValueText object 变长 值的对象表示
Metadata string 变长 元数据 (可选)
  1. 子设备集合 (DeviceMessageChild)

子设备集合包含多个子设备信息:

字段 类型 长度 描述
Count byte 1字节 子设备数量
ChildArray DeviceMessageInfo[] 变长 子设备数组

值类型支持

DeviceCommons 支持多种数据类型:

值类型 枚举值 长度 描述
Float32 1 4字节 单精度浮点数
Int32 2 4字节 32位整数
String 3 变长 字符串 (长度前缀:1字节)
Bool 4 1字节 布尔值
UInt16 6 2字节 16位无符号整数
Int16 7 2字节 16位有符号整数
Timestamp 8 8字节 时间戳 (64位)
Binary 9 变长 二进制数据 (长度前缀:2字节)
Double 10 8字节 双精度浮点数
消息序列化格式

二进制格式布局

+---------------------------------------------------+
| 消息头 (4字节)                                     |
| +-----------------------------------------------+ |
| | 固定头 (0xC0, 0xBF) (2字节)                   | |
| | 版本号 (1字节)                                | |
| | 标志位 (1字节)                                | |
| +-----------------------------------------------+ |
| 主设备数据 (变长)                                 |
| +-----------------------------------------------+ |
| | 设备ID长度 (1字节)                            | |
| | 设备ID (变长)                                 | |
| | 设备类型 (1字节)                              | |
| | 读数集合 (变长)                               | |
| | +-------------------------------------------+ | |
| | | 读数数量 (1字节)                          | | |
| | | 读数数组 (变长)                           | | |
| | | +---------------------------------------+ | | |
| | | | 时间偏移 (2字节)                       | | | |
| | | | 状态集合 (变长)                        | | | |
| | | | +-----------------------------------+ | | | |
| | | | | 状态数量 (1字节)                   | | | | |
| | | | | 状态数组 (变长)                    | | | | |
| | | | | +-------------------------------+ | | | | |
| | | | | | 状态ID (1字节)                 | | | | | |
| | | | | | 值类型 (1字节)                 | | | | | |
| | | | | | 值数据 (变长)                  | | | | | |
| | | | | +-------------------------------+ | | | | |
| | | | +-----------------------------------+ | | | |
| | | +---------------------------------------+ | | |
| | +-------------------------------------------+ | |
| +-----------------------------------------------+ |
| 子设备集合 (变长)                                 |
| +-----------------------------------------------+ |
| | 子设备数量 (1字节)                            | |
| | 子设备数组 (变长)                             | |
| | +-------------------------------------------+ | |
| | | 设备信息 (与主设备结构相同)                | | |
| | +-------------------------------------------+ | |
| +-----------------------------------------------+ |
| CRC校验码 (变长,取决于CRC类型)                   |
+---------------------------------------------------+
十六进制字符串格式

当使用十六进制字符串格式时,消息可以包含压缩和加密信息:

[加密状态],[压缩状态]|[十六进制数据]

示例:

dec,raw|C0BF01054D61696E...  // 未加密未压缩
enc,gzip|1F8B080000000000... // 加密并压缩
软件架构

DeviceCommons 采用分层架构设计:

1.核心层 (Core)

  • 基础数据类型定义 (Enums)
  • 消息模型 (Models)
  • 工具类和扩展方法

2.序列化层 (Serialization)

  • 解析器体系 (Parsers)
  • 序列化器体系 (Serializers)
  • 支持版本化管理

3.安全层 (Security)

  • CRC 校验计算
  • AES 加密/解密
  • 可扩展的加密接口

4.工具层 (Utilities)

  • 内存池和对象池
  • 压缩/解压缩
  • 十六进制转换

5.构建层 (Builders)

  • 流畅接口构建复杂消息
  • 工厂模式创建特定类型对象
安装教程

1. 通过 NuGet 安装

dotnet add package DeviceCommons

2. 手动编译安装

git clone https://gitee.com/ruan-yong/device-commons.git
cd DeviceCommons
dotnet build

3. 项目引用

  • 在您的项目中添加对 DeviceCommons.dll 的引用
使用说明

1. 基本用法

// 创建简单的设备消息
var message = DeviceMessageBuilder.Create()
    .WithHeader(version: 0x01, crcType: CRCTypeEnum.CRC16)
    .WithMainDevice("device-001", 0x01, config =>
    {
        config.AddReading(100, reading =>
        {
            reading.AddState(1, 25.5f, StateValueTypeEnum.Float32);
            reading.AddState(2, "正常运行", StateValueTypeEnum.String);
            reading.AddState(3, true, StateValueTypeEnum.Bool);
        });
    })
    .Build();

// 序列化为字节数组
var bytes = message.BuildBytes();

// 序列化为十六进制字符串(带压缩和加密)
var hexString = message.BuildHex(compress: true, encrypt: true);

2. 高级功能

// 使用AES加密
var message = DeviceMessageBuilder.Create()
    .WithAesEncryption("your-secret-password")
    .WithMainDevice("secure-device", 0x01)
    .BuildHex(compress: true, encrypt: true);

// 自定义加密算法
var message = DeviceMessageBuilder.Create()
    .WithEncryptFunc(myEncryptFunction)
    .WithDecryptFunc(myDecryptFunction)
    .WithMainDevice("custom-crypto-device", 0x01)
    .BuildHex(encrypt: true);

// 注册自定义设备类型处理
StateFactoryRegistry.RegisterFactory(0x99, () => new CustomStateFactory());

3. 解析消息

// 从字节数组解析
var parser = new DeviceMessageParser();
var message = parser.Parser(bytes);

// 从十六进制字符串解析(支持自动解压和解密)
var message = parser.Parser(hexString);

// 访问解析后的数据
var deviceId = message.MainDevice.DID;
var temperature = message.MainDevice.Reading.ReadingArray[0].State.StateArray[0].ValueText;
典型消息示例

简单温度传感器消息

var message = DeviceMessageBuilder.Create()
    .WithHeader(version: 0x01, crcType: CRCTypeEnum.CRC16)
    .WithMainDevice("temp-sensor-001", 0x20, config =>
    {
        config.AddReading(0, reading =>
        {
            reading.AddState(1, 25.3f, StateValueTypeEnum.Float32); // 温度
            reading.AddState(2, 45.0f, StateValueTypeEnum.Float32); // 湿度
            reading.AddState(3, true, StateValueTypeEnum.Bool);     // 在线状态
        });
    })
    .Build();

复杂多设备消息

var message = DeviceMessageBuilder.Create()
    .WithHeader(version: 0x01, crcType: CRCTypeEnum.CRC32)
    .WithMainDevice("gateway-001", 0x10, config =>
    {
        config.AddReading(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), reading =>
        {
            reading.AddState(1, "正常运行", StateValueTypeEnum.String);
            reading.AddState(2, 85.5f, StateValueTypeEnum.Float32); // CPU使用率
        });
    })
    .WithChildDevice("sensor-001", 0x20, config =>
    {
        config.AddReading(100, reading =>
        {
            reading.AddState(1, 23.5f, StateValueTypeEnum.Float32); // 温度
            reading.AddState(2, 1024.5f, StateValueTypeEnum.Float32); // 气压
        });
    })
    .WithChildDevice("sensor-002", 0x20, config =>
    {
        config.AddReading(100, reading =>
        {
            reading.AddState(1, 65.2f, StateValueTypeEnum.Float32); // 湿度
            reading.AddState(2, 120.0f, StateValueTypeEnum.Float32); // 光照
        });
    })
    .Build();
扩展性设计

DeviceCommons 的消息结构设计具有良好的扩展性:

  1. 版本兼容:通过版本号字段支持协议演进
  2. 保留字段:预留位和保留字段用于未来扩展
  3. 设备类型注册:通过工厂模式支持自定义设备类型处理
  4. 值类型扩展:值类型枚举可扩展新的数据类型
  5. 元数据支持:状态值可包含额外的元数据信息
贡献指南:
  • 遵循现有的代码风格和命名约定
  • 添加适当的单元测试
  • 更新相关文档
  • 确保所有测试通过
特技
  1. 🌟 高性能设计: 使用 ArrayPool 和 MemoryPool 优化内存使用,减少GC压力
  2. 🔒 多重安全: 支持CRC校验、AES加密和自定义加密算法
  3. 📦 智能压缩: 自动判断何时使用压缩优化数据传输
  4. 🔧 灵活扩展: 通过工厂模式支持自定义设备类型处理
  5. 异步支持: 所有操作都提供异步版本,适合高并发场景
  6. 🌐 多格式支持: 支持二进制、十六进制字符串多种数据格式
  7. 🧩 模块化设计: 各组件解耦,可按需使用部分功能

性能基准

操作类型 数据大小 平均耗时 内存分配
简单消息序列化
复杂消息序列化
带压缩序列化
消息解析
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.