DeviceCommons 2.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package DeviceCommons --version 2.2.0
                    
NuGet\Install-Package DeviceCommons -Version 2.2.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="2.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DeviceCommons" Version="2.2.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 2.2.0
                    
#r "nuget: DeviceCommons, 2.2.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@2.2.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=2.2.0
                    
Install as a Cake Addin
#tool nuget:?package=DeviceCommons&version=2.2.0
                    
Install as a Cake Tool

DeviceCommons

.NET C++ License Build Status

专为物联网(IoT)场景设计的高性能设备消息处理库,提供完整的序列化/反序列化解决方案。

🚀 项目简介

DeviceCommons 是一个现代化的设备消息处理库,专门为物联网设备开发者、嵌入式系统工程师和后端数据处理开发者设计。它提供了高效、安全、可扩展的消息序列化和反序列化功能,支持跨平台部署和多种编程语言。

核心优势

  • 🏎️ 极致性能:最小化内存分配,优化的序列化算法
  • 🔒 数据安全:内置AES加密和CRC校验机制
  • 📦 智能压缩:Gzip压缩减少传输体积
  • 🔄 平滑升级:V1/V2协议共存,无缝迁移
  • 🌐 跨平台支持:C#/.NET与C++双语言实现
  • 🧩 高度可扩展:支持自定义序列化器和协议扩展
  • 现代化设计:异步API、依赖注入、链式调用

📋 功能特性

🔧 核心功能

  • 高性能序列化/反序列化:优化的二进制格式,支持多种数据类型
  • AES加密支持:双模式设计(快速模式/安全模式),支持密钥缓存
  • 数据压缩:智能Gzip压缩,自动优化传输效率
  • CRC校验:支持CRC16/CRC32,确保数据完整性
  • 协议版本管理:V1/V2协议兼容,支持平滑升级

🛠️ 技术特性

  • 依赖注入支持:完整的.NET DI集成
  • 异步API:支持高并发场景
  • 内存优化:ArrayPool缓冲区复用,Span<T>零拷贝技术
  • 类型安全:强类型API设计,编译时错误检查
  • 链式构建:流畅的构建器模式

📊 数据类型支持

  • 基础类型:String、Binary、Int32/16、UInt16、Float32、Double、Bool
  • 时间戳:高精度时间戳支持
  • 复杂结构:设备、读数、状态的嵌套结构
  • 自定义类型:可扩展的状态工厂系统

🚀 快速开始

安装要求

  • .NET 6.0+ 或更高版本
  • C++17 编译器(可选,用于C++版本)
  • CMake 3.15+(可选,用于C++构建)

基本使用

1. 创建和序列化消息
using DeviceCommons.DeviceMessages.Builders;
using DeviceCommons.DeviceMessages.Enums;

// 创建设备消息
var message = DeviceMessageBuilder.Create()
    .WithHeader(version: 0x02, crcType: CRCTypeEnum.CRC32)
    .WithMainDevice("DEVICE001", 0x01, config =>
    {
        config.AddReading(100, reading =>
        {
            reading.AddState(1, "temperature", 25.5f);
            reading.AddState(2, "humidity", 60.2f);
            reading.AddState(3, "online", true);
        });
    })
    .Build();

// 序列化为十六进制字符串
var hex = DeviceMessageBuilder.Create()
    .WithMainDevice("DEVICE001", 0x01, config => { ... })
    .BuildHex();
2. 解析消息
using DeviceCommons.DeviceMessages.Serialization;

// 解析十六进制消息
var parser = DeviceMessageSerializerProvider.MessagePar;
var parsedMessage = parser.Parser(hex);

// 访问设备数据
Console.WriteLine($"设备ID: {parsedMessage.MainDevice.DID}");
Console.WriteLine($"设备类型: {parsedMessage.MainDevice.DeviceType}");

// 遍历读数和状态
foreach (var reading in parsedMessage.MainDevice.Readings)
{
    Console.WriteLine($"时间偏移: {reading.TimeOffset}");
    foreach (var state in reading.States)
    {
        Console.WriteLine($"  状态ID: {state.SID}, 值: {state.Value}");
    }
}

🔐 加密和压缩

AES加密配置

快速模式(性能优先)
// 构建器配置
var encryptedMessage = DeviceMessageBuilder.Create()
    .WithFastAesEncryption("your-secret-password")
    .WithMainDevice("SecureDevice", 0x01, config => { ... })
    .BuildHex(encrypt: true);

// 依赖注入配置
services.AddDeviceCommons()
       .WithFastAesEncryption("your-secret-password");
安全模式(安全优先)
// 构建器配置
var secureMessage = DeviceMessageBuilder.Create()
    .WithSecureAesEncryption("your-secret-password")
    .WithMainDevice("SecureDevice", 0x01, config => { ... })
    .BuildHex(encrypt: true);

// 依赖注入配置
services.AddDeviceCommons()
       .WithSecureAesEncryption("your-secret-password");
AES模式对比
模式 PBKDF2迭代次数 密钥缓存 适用场景 性能
快速模式 1,000次 ✅ 启用 开发测试、高频通信 高性能
安全模式 60,000次 ❌ 禁用 生产环境、敏感数据 高安全性

数据压缩

// 启用Gzip压缩
var compressedMessage = DeviceMessageBuilder.Create()
    .WithGZipCompression()
    .WithMainDevice("Device", 0x01, config => { ... })
    .BuildHex(compress: true);

// 依赖注入配置
services.AddDeviceCommons()
       .WithDefaultGZipCompression();

🏗️ 依赖注入集成

基本注册

using DeviceCommons;
using Microsoft.Extensions.DependencyInjection;

// 注册DeviceCommons服务
services.AddDeviceCommons();

// 带配置注册
services.AddDeviceCommons()
       .WithFastAesEncryption("encryption-password")
       .WithDefaultGZipCompression();

服务使用

public class DeviceService
{
    private readonly IDeviceMessageBuilder _builder;
    private readonly IDeviceCommonsConfigurationService _config;

    public DeviceService(
        IDeviceMessageBuilder builder,
        IDeviceCommonsConfigurationService config)
    {
        _builder = builder;
        _config = config;
    }

    public async Task<string> CreateEncryptedMessage()
    {
        return _builder
            .WithMainDevice("ServiceDevice", 0x01, config =>
            {
                config.AddReading(0, reading =>
                {
                    reading.AddState(1, "service_data", DateTime.Now.ToString());
                });
            })
            .BuildHex(encrypt: _config.IsEncryptionEnabled);
    }
}

配置选项

// 获取当前配置
var options = serviceProvider
    .GetRequiredService<IOptions<DeviceCommonsOptions>>().Value;

Console.WriteLine($"加密模式: {options.AesEncryptionMode}");
Console.WriteLine($"启用加密: {options.EnableDefaultAesEncryption}");
Console.WriteLine($"启用压缩: {options.EnableDefaultGZipCompression}");

🎯 高级特性

自定义状态工厂

// 创建自定义状态工厂
public class CustomStateFactory : IStateFactory
{
    public IDeviceMessageInfoReadingState CreateState(byte sid, object value, StateValueTypeEnum type)
    {
        // 自定义状态创建逻辑
        return new CustomDeviceState(sid, value, type);
    }
}

// 注册自定义工厂
services.AddDeviceCommons()
       .AddStateFactory<CustomStateFactory>(deviceType: 0x10);

异步API

// 异步构建
var message = await DeviceMessageBuilder.Create()
    .WithMainDevice("AsyncDevice", 0x01, config => { ... })
    .BuildHexAsync(compress: true, encrypt: true);

// 异步解析
var parser = DeviceMessageSerializerProvider.MessagePar;
var parsedMessage = await parser.ParserAsync(hex);

性能监控

// 启用性能统计
var stats = new PerformanceStats();

// 运行性能测试
dotnet run                    # 标准性能测试
dotnet run high              # 高强度测试
dotnet run stress            # 压力测试
dotnet run aes               # AES性能对比

🌐 跨平台支持

C++版本

#include "DeviceMessageBuilder.h"
#include "DeviceMessageParserV2.h"

// C++构建消息
auto builder = DeviceMessageBuilder::Create()
    .WithHeader(0x02, CRCType::CRC32)
    .WithMainDevice("CPP_DEVICE", 0x01);

auto message = builder.Build();
auto hex = builder.BuildHex();

构建C++版本

# Windows
build.bat

# Linux/macOS  
build.sh

# 手动构建
mkdir build && cd build
cmake ..
cmake --build . --config Release

📊 性能基准

序列化性能

操作类型 平均耗时 吞吐量 内存使用
构建消息 ~0.1ms 10,000 ops/sec <1KB
序列化 ~0.5ms 2,000 ops/sec <2KB
解析消息 ~0.8ms 1,250 ops/sec <2KB

AES加密性能

加密模式 首次加密 缓存加密 性能提升
快速模式 ~2ms ~0.1ms 20x
安全模式 ~120ms ~120ms 1x

压缩效果

数据类型 原始大小 压缩后 压缩比
文本数据 1KB ~300B 70%
重复数据 5KB ~200B 96%
随机数据 10KB ~9.8KB 2%

🧪 测试和调试

运行测试

# 运行所有单元测试
dotnet test

# 运行特定测试
dotnet test TestProject1/Configuration/AesModeConfigurationTests.cs
dotnet test TestProject1/Builders/BuilderAesModeConfigurationTests.cs

# 性能测试
dotnet run demo              # 功能演示
dotnet run table             # 表格显示测试
dotnet run config            # 配置功能测试
dotnet run builder           # 构建器测试

调试工具

# 生成测试报告
dotnet run record

# 验证表格对齐
dotnet run verify

# 性能修复验证
dotnet run fix

📚 API参考

核心接口

  • IDeviceMessageBuilder - 消息构建器接口
  • IDeviceMessageSerializer - 序列化器接口
  • IDeviceMessageParser - 解析器接口
  • IDeviceCommonsConfigurationService - 配置服务接口
  • IStateFactory - 状态工厂接口

主要类

  • DeviceMessageBuilder - 消息构建器实现
  • DeviceMessage - 设备消息模型
  • AesEncryptor - AES加密器
  • DeviceCommonsOptions - 配置选项
  • PerformanceStats - 性能统计

枚举类型

  • AesMode - AES加密模式(Fast/Secure)
  • CRCTypeEnum - CRC校验类型
  • StateValueTypeEnum - 状态值类型
  • TimeStampFormatEnum - 时间戳格式

🤝 贡献指南

开发环境设置

  1. 克隆仓库:git clone https://gitee.com/ruan-yong/device-commons.git
  2. 安装.NET 6.0+ SDK
  3. 安装C++17编译器(可选)
  4. 运行测试:dotnet test

代码规范

  • 遵循.NET编码标准
  • 使用有意义的变量和方法名
  • 添加XML文档注释
  • 编写单元测试

提交流程

  1. Fork项目
  2. 创建功能分支:git checkout -b feature/new-feature
  3. 提交更改:git commit -am 'Add new feature'
  4. 推送分支:git push origin feature/new-feature
  5. 创建Pull Request

📄 许可证

本项目采用 MIT 许可证

🆘 支持和帮助

常见问题

Q: 如何选择AES加密模式? A: 开发和测试环境建议使用快速模式,生产环境使用安全模式。

Q: 支持哪些数据类型? A: 支持字符串、二进制、整数、浮点数、布尔值、时间戳等多种类型。

Q: 如何优化序列化性能? A: 使用快速AES模式、启用压缩、合理设计数据结构。

获取帮助

  • 查看文档和示例代码
  • 运行内置的演示程序
  • 提交Issue反馈问题
  • 参与社区讨论

版本历史

  • v2.0 - 添加依赖注入支持、AES双模式、性能优化
  • v1.0 - 基础序列化功能、V1/V2协议支持

<div align="center">

DeviceCommons - 让IoT设备通信更简单、更安全、更高效

快速开始API文档示例代码贡献指南

</div>

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.