# DeviceCommons **Repository Path**: ruan-yong/device-commons ## Basic Information - **Project Name**: DeviceCommons - **Description**: 这是一个用于高效序列化/反序列化 IoT 设备消息的高性能 .NET 工具库,支持压缩、加密、CRC 校验及灵活的扩展结构。 - **Primary Language**: C# - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2025-08-25 - **Last Updated**: 2025-08-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: IOT, 通讯协议 ## README # DeviceCommons 项目完整WIKI文档 ## 📋 目录 1. [项目概述](#项目概述) 2. [快速入门](#快速入门) 3. [依赖注入(DI)支持](#依赖注入di支持) 4. [核心架构](#核心架构) 5. [消息构建](#消息构建) 6. [序列化与反序列化](#序列化与反序列化) 7. [安全特性](#安全特性) 8. [C++ 集成](#c-集成) 9. [API 参考](#api-参考) 10. [扩展性设计](#扩展性设计) 11. [异步功能](#异步功能) --- ## 项目概述 **DeviceCommons** 是一个专为物联网(IoT)场景设计的高性能设备消息处理库,提供完整的序列化/反序列化解决方案。支持多种数据类型、压缩加密、CRC校验,以及灵活的扩展结构,特别适合资源受限的嵌入式设备和高效的后端数据处理。 ### 主要特性 - 🚀 **高性能**: 优化的二进制序列化,最小化内存分配 - 🔒 **安全可靠**: 内置CRC校验、AES加密支持 - 📦 **智能压缩**: 支持Gzip压缩,减少传输体积 - 🔄 **版本兼容**: V1/V2协议共存,平滑升级 - 🌐 **跨平台**: C#/.NET与C++双语言支持 - 🔧 **高扩展性**: 支持自定义序列化器、工厂和协议扩展 - ⚡ **异步支持**: 完整的异步API,支持高并发场景 - 💉 **依赖注入(DI)**: 全面支持.NET依赖注入,提供现代化的服务架构 ### 技术架构 ```mermaid graph TB subgraph "C# 主库 (Full Stack)" DM[DeviceMessages] DH[DataHandling] EX[Exceptions] SC[Security] end subgraph "C++ 核心库 (Optimized)" CB[DeviceMessageBuilder.h] CP[DeviceMessageParserV2.h] CU[UnifiedDemo.cpp] end subgraph "跨平台构建系统" CM[CMake] BS[Build Scripts] end DM --> V1[V1 Protocol] DM --> V2[V2 Protocol] DH --> Compression[智能压缩] SC --> AES[AES加密] SC --> CRC[CRC校验] CB --> V2 CP --> V2 CM --> CB CM --> CP ``` ### 项目最新更新 #### C++ 库完全重构 (V2协议支持) - ✅ **协议升级**: 完整支持V2版本协议,与C#版本保持100%兼容 - ✅ **项目瘦身**: 文件数量减少53.3% (15→7个文件),存储空间节省~3MB - ✅ **代码整合**: 5个重复演示程序合并为1个统一交互式程序 - ✅ **跨平台支持**: 支持Windows、Linux、macOS通过CMake构建 - ✅ **编码优化**: 解决所有Unicode字符编码问题,确保跨编译器兼容 ## 快速入门 ### 环境要求 - **C# 版本**: .NET 6.0 或更高版本 - **C++ 版本**: C++17 标准,支持 CMake 3.15+ - **平台支持**: Windows、Linux、macOS ### 基本使用示例 #### C# 版本 ```csharp using DeviceCommons.DeviceMessages.Builders; // 构建设备消息 var message = DeviceMessageBuilder.Create() .WithHeader(version: 0x02, crcType: CRCTypeEnum.CRC16) .WithMainDevice("device-001", 0x01) .AddReading(100, reading => { reading.AddState(1, 25.5f, StateValueTypeEnum.Float32); reading.AddState(2, "正常运行", StateValueTypeEnum.String); }) .BuildHex(); // 解析消息 var parser = new DeviceMessageParser(); var deviceMessage = parser.Parser(message); ``` #### C++ 版本 ```cpp #include "DeviceMessageBuilder.h" using namespace DeviceCommons; // 构建设备消息 auto builder = DeviceMessageBuilder::create() .withCRC(CRCType::CRC16) .withMainDevice("device-001", 0x01); // 添加读数和状态 std::vector states = { State::makeFloat32(1, 25.5f), State::makeString(2, "正常运行") }; auto message = builder .addReading(100, states) .buildHex(); ``` ## 依赖注入(DI)支持 **DeviceCommons v2.0** 现已全面支持.NET依赖注入,提供了更现代化、可扩展的服务架构。 ### 🚀 快速开始 #### 基本注册 ```csharp using DeviceCommons; using Microsoft.Extensions.DependencyInjection; // 注册DeviceCommons服务 services.AddDeviceCommons(); // 或使用配置选项 services.AddDeviceCommons(options => { options.DefaultEncryptionPassword = "your-secure-password"; options.EnableDefaultAesEncryption = true; }); ``` #### 服务注入和使用 ```csharp public class DeviceService { private readonly IDeviceMessageBuilder _builder; private readonly IDeviceMessageParser _parser; public DeviceService(IDeviceMessageBuilder builder, IDeviceMessageParser parser) { _builder = builder; _parser = parser; } public string CreateMessage() { return _builder .WithHeader() .WithMainDevice("DEVICE001", 0x01) .AddReading(0, 1, 25.5f) .BuildHex(); } } ``` ### 🔧 高级配置 #### AES加密支持 ```csharp services.AddDeviceCommons() .WithAesEncryption("your-encryption-password"); ``` #### 自定义状态工厂 ```csharp // 方式一:泛型注册 services.AddDeviceCommons() .AddStateFactory(deviceType: 0x99); // 方式二:构建器模式 services.ConfigureStateFactories(builder => { builder.AddFactory(0x01); builder.AddFactory(0x02); builder.AddFactory(0x03, provider => new PressureStateFactory()); }); ``` ### 📚 更多信息 详细的DI使用指南请参考:[DI使用指南](DI_USAGE_GUIDE.md) ### 🔄 向后兼容性 DI支持完全向后兼容,现有代码无需任何修改: ```csharp // 传统方式仍然有效 var builder = DeviceMessageBuilder.Create(); var message = builder.WithHeader().Build(); // 静态工厂注册仍然有效 StateFactoryRegistry.RegisterFactory(0x55, () => new CustomFactory()); ``` ## 核心架构 ### 消息模型 DeviceCommons 采用分层的消息模型设计: ```mermaid classDiagram class DeviceMessage { +DeviceMessageHeader Header +DeviceMessageInfo MainDevice +DeviceMessageChild ChildDevice } class DeviceMessageInfo { +byte Length +byte[] DIDBytes +string DID +byte DeviceType +DeviceMessageInfoReadings Reading } class DeviceMessageInfoReading { +short TimeOffset +DeviceMessageInfoReadingStates State } class DeviceMessageInfoReadingState { +byte SID +byte Type +StateValueTypeEnum ValueType +byte[] Value +object ValueText } DeviceMessage --> DeviceMessageInfo DeviceMessageInfo --> DeviceMessageInfoReading DeviceMessageInfoReading --> DeviceMessageInfoReadingState ``` ### 消息头结构 | 字段 | 类型 | 长度 | 描述 | |------|------|------|------| | 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校验类型 | ### 支持的值类型 | 值类型 | 枚举值 | C#类型 | 长度 | 描述 | |--------|--------|--------|------|------| | Float32 | 1 | float | 4字节 | 单精度浮点数 | | Int32 | 2 | int | 4字节 | 32位整数 | | String | 3 | string | 变长 | 字符串(UTF-8编码) | | Bool | 4 | bool | 1字节 | 布尔值 | | UInt16 | 6 | ushort | 2字节 | 16位无符号整数 | | Int16 | 7 | short | 2字节 | 16位有符号整数 | | Timestamp | 8 | long | 8字节 | 时间戳(64位) | | Binary | 9 | byte[] | 变长 | 二进制数据 | | Double | 10 | double | 8字节 | 双精度浮点数 | ### 序列化机制 #### V1版本序列化实现 - **固定长度字段**: 消息头、设备类型等 - **变长字段**: 设备ID、字符串值等使用长度前缀 - **大端序**: 多字节数值采用大端序排列 #### V2版本序列化实现 - **扩展枚举类型**: 新增Reserve1、Reserve2保留位 - **向后兼容性**: 完全兼容V1格式的消息解析 - **优化的字段标记**: 改进的头部字段组织 ### 解析引擎 ```mermaid sequenceDiagram participant Client as "客户端" participant Parser as "DeviceMessageParser" participant HeaderPar as "DeviceMessageHeaderParser" participant Process as "IProcessVersion" Client->>Parser : Parser(bytes) Parser->>Parser : 验证输入长度 Parser->>HeaderPar : Parser(headerBytes) HeaderPar-->>Parser : 返回消息头 Parser->>Parser : 验证协议头 (0xC0, 0xBF) Parser->>Parser : 计算CRC并校验 alt CRC校验失败 Parser->>Parser : 抛出InvalidMessageException else CRC校验成功 Parser->>Parser : 根据Version选择ProcessVersionData Parser->>Process : Parser(Model, data) Process-->>Parser : 完成主设备和子设备解析 end Parser-->>Client : 返回IDeviceMessage ``` ## 消息构建 ### 基础构建示例 ```csharp var message = DeviceMessageBuilder.Create() .WithHeader( version: 0x02, crcType: CRCTypeEnum.CRC16, timeFormat: TimeStampFormatEnum.MS, valueType: HeaderValueTypeEnum.Standard) .WithMainDevice("main-device", 0x01) .AddReading(1000, reading => { reading.AddState(1, 25.5f, StateValueTypeEnum.Float32); reading.AddState(2, 1023, StateValueTypeEnum.Int32); reading.AddState(3, "运行正常", StateValueTypeEnum.String); reading.AddState(4, true, StateValueTypeEnum.Bool); }) .WithChildDevice("child-001", 0x02, child => { child.AddReading(500, childReading => { childReading.AddState(1, 18.3f, StateValueTypeEnum.Float32); }); }) .Build(); ``` ### 构建器API核心方法 ```csharp public interface IDeviceMessageBuilder { // 头部配置 IDeviceMessageBuilder WithHeader(byte version = 0x02, CRCTypeEnum crcType = CRCTypeEnum.CRC16); // 设备配置 IDeviceMessageBuilder WithMainDevice(string did, byte deviceType); IDeviceMessageBuilder WithChildDevice(string did, byte deviceType, Action config); // 读数添加 IDeviceMessageBuilder AddReading(short timeOffset, Action config); // 构建方法 DeviceMessage Build(); byte[] BuildBytes(); string BuildHex(bool compress = false, bool encrypt = false); // 异步方法 Task BuildBytesAsync(CancellationToken cancellationToken = default); Task BuildHexAsync(bool compress = false, bool encrypt = false); } ``` --- *续:本文档分为多个部分,请查看后续文档了解更多详细信息。*