hy.utils 1.0.0

dotnet add package hy.utils --version 1.0.0
                    
NuGet\Install-Package hy.utils -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="hy.utils" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="hy.utils" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="hy.utils" />
                    
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 hy.utils --version 1.0.0
                    
#r "nuget: hy.utils, 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 hy.utils@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=hy.utils&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=hy.utils&version=1.0.0
                    
Install as a Cake Tool

hy.utils

基于 TouchSocket 封装的轻量级、插件化通信工具库,支持串口、TCP(客户端/服务端)及 UDP 通信,内置高度灵活的动态协议解析引擎。

🌟 核心特性

  • 协议动态化:通过 JSON 配置即可实现私有协议的流式分包与自动解析。
  • 通信全覆盖:统一封装了串口 (Serial)、UDP、TCP Client 及 TCP Server。
  • 灵活校验:内置 CKS8、XOR8、CRC16-MODBUS、CRC16-IBM 等算法,支持自定义多项式。
  • 插件化架构:完美继承 TouchSocket 插件系统,逻辑解耦。
  • 高性能:采用 ReadOnlySpan<byte> 与零拷贝思想处理原始二进制流。

📦 安装说明

本库支持通过 NuGet 安装:

# 安装包
dotnet add package hy.utils

🏗️ 依赖注入 (DI) 注册

Startup.csApp.axaml.cs 中注册为单例服务,以便在整个应用中复用连接:

using Microsoft.Extensions.DependencyInjection;
using hy.utils.Serial;
using hy.utils.Udp;
using hy.utils.Tcp;

public void ConfigureServices(IServiceCollection services)
{
    // 注册核心服务
    services.AddSingleton<SerialPortService>();
    services.AddSingleton<UdpService>();
    services.AddSingleton<TcpClientService>();
    services.AddSingleton<TcpServerService>();
}

🧩 插件用法 (Plugin)

本库基于 TouchSocket 的插件机制。你可以通过实现特定接口来处理接收到的数据。

自定义插件实现

using TouchSocket.Core;
using TouchSocket.Sockets;
using TouchSocket.SerialPorts;
using hy.utils.Protocol;

public class MyDataPlugin : PluginBase, ISerialReceivedPlugin, ITcpReceivedPlugin, IUdpReceivedPlugin
{
    // 处理串口数据
    public Task OnSerialReceived(ISerialPortSession client, ReceivedDataEventArgs e) 
        => HandleData("Serial", e);

    // 处理 TCP 数据
    public Task OnTcpReceived(ITcpClientBase client, ReceivedDataEventArgs e) 
        => HandleData("TCP", e);

    // 处理 UDP 数据 (注意接口略有不同)
    public Task OnUdpReceived(IUdpSession client, UdpReceivedDataEventArgs e)
    {
        if (e.RequestInfo is Adapter.DataClass dynamicInfo)
        {
            // 处理解析后的数据
            var value = dynamicInfo.BodyValues["Temp"];
        }
        return Task.CompletedTask;
    }

    private Task HandleData(string source, ReceivedDataEventArgs e)
    {
        if (e.RequestInfo is Adapter.DataClass dynamicInfo)
        {
            // 访问 JSON 中定义的字段
            Console.WriteLine($"收到{source}数据: {dynamicInfo.BodyValues["Temp"]}");
        }
        return Task.CompletedTask;
    }
}

在启动时挂载插件

await serialService.GetOrCreateServiceAsync(
    "COM1", 
    "Serial_1", 
    adapterFactory: () => new Adapter(config),
    configurePlugins: pluginManager => 
    {
        pluginManager.Add<MyDataPlugin>(); // 挂载你的业务插件
    }
);

🛠️ 快速上手

1. 动态协议配置 (protocol.json)

定义一个带有 4 字节固定头,包含长度字段和 CRC16 校验的协议:

{
  "protocolName": "MyProtocol",
  "headerLength": 4,
  "endianness": "BigEndian",
  "headerFields": [
    { "name": "Start", "type": "byte", "offset": 0, "length": 1 },
    { "name": "ID", "type": "byte", "offset": 1, "length": 1 },
    { "name": "Len", "type": "ushort", "offset": 2, "length": 2 }
  ],
  "bodyLengthField": {
    "fieldName": "Len",
    "additionalLength": 2, 
    "includesHeader": false
  },
  "checksum": {
    "type": "CRC16",
    "length": 2,
    "skipHeader": false
  },
  "bodyFields": [
    { "name": "Temp", "type": "float", "offset": 0, "length": 4 },
    { "name": "Status", "type": "byte", "offset": 4, "length": 1 }
  ]
}

2. 初始化服务 (以串口为例)

using hy.utils.Protocol;
using hy.utils.Serial;

// 加载配置
var config = ProtocolLoader.LoadFromFile("protocol.json");

// 创建/获取单例服务
var serialService = await SerialPortService.GetOrCreateServiceAsync(
    "COM1", 
    "Serial_1", 
    adapterFactory: () => new Adapter(config)
);

// 发送数据
await serialService.SendAsync("Serial_1", new byte[] { 0xAA, 0x01, ... });

📡 模块说明

协议适配器 (Protocol)

  • Adapter: 用于串口和 TCP,基于固定包头逻辑实现流式切包。
  • UdpAdapter: 针对 UDP 无连接特性优化的解析器。
  • DataClass: 解析后的结果容器,通过 HeaderValuesBodyValues 字典访问字段。

串口服务 (Serial)

  • 支持热插拔检测、自动重连。
  • 通过 SerialPortService 管理多个命名串口实例。

TCP 服务 (Tcp)

  • TcpClientService: 管理多个客户端连接,支持断线重连。
  • TcpServerService: 监听端口,管理多客户端接入。支持 BroadcastAsync(广播)或 SendToLastClientAsync(发往最后活动客户端)。

UDP 服务 (Udp)

  • UdpService: 支持单播、广播发送。

🔢 校验支持

checksum 配置中指定 type

  • SUM8: 字节求和取低8位。
  • XOR8: 字节异或。
  • CRC16: 默认 MODBUS。
  • CRC16IBM: IBM 标准。
  • 自定义: 通过设置 poly, init, xorOut, refIn, refOut 实现任意 16 位 CRC 算法。

📝 开发规范

  • 所有字段类型支持:byte, ushort, uint, int, float, double, byte[]
  • 建议使用 依赖注入 (DI) 注册 Service 为单例。
  • 接收数据时,请在插件中处理 e.RequestInfo 并将其转换为 Adapter.DataClass

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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.

Version Downloads Last Updated
1.0.0 120 1/15/2026