Liam.SerialPort 1.1.0

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

Liam.SerialPort

现代化串口通讯功能库,支持跨平台串口设备发现、连接管理、数据收发、热插拔检测和自动重连等功能。

功能特性

🔍 设备发现与管理

  • 自动设备发现:支持Windows、Linux、macOS跨平台串口设备枚举
  • 热插拔检测:实时监控串口设备的插入和拔出
  • 设备信息获取:获取详细的设备信息(制造商、产品ID、序列号等)
  • 设备状态监控:实时监测设备可用性和使用状态

🔗 连接管理

  • 智能连接管理:支持连接建立、维护和断开
  • 自动重连机制:连接断开时的智能重连策略
  • 连接状态监控:实时监测连接状态变化
  • 连接统计信息:提供详细的连接统计和性能指标

📡 数据通讯

  • 同步/异步API:支持同步和异步数据收发
  • 多种数据格式:支持字节数组、字符串、十六进制等格式
  • 流式数据处理:支持大数据量的流式处理
  • 数据缓冲管理:智能的发送和接收缓冲区管理

⚡ 高级功能

  • 超时控制:完善的读写操作超时处理
  • 错误处理:完整的异常管理和错误恢复机制
  • 事件驱动:基于事件的数据接收和状态变化通知
  • 依赖注入:完整的DI容器支持
  • 服务池:支持串口服务池管理

安装

NuGet包管理器

Install-Package Liam.SerialPort

.NET CLI

dotnet add package Liam.SerialPort

PackageReference

<PackageReference Include="Liam.SerialPort" Version="1.1.0" />

快速开始

1. 基础使用

using Liam.SerialPort.Extensions;
using Liam.SerialPort.Interfaces;
using Liam.SerialPort.Models;
using Liam.SerialPort.Services;
using Microsoft.Extensions.Logging;

// 创建日志记录器
using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());

// 创建串口服务
var discovery = new SerialPortDiscovery(loggerFactory.CreateLogger<SerialPortDiscovery>());
var connection = new SerialPortConnection(loggerFactory.CreateLogger<SerialPortConnection>());
var dataHandler = new SerialPortDataHandler(loggerFactory.CreateLogger<SerialPortDataHandler>());
var serialPortService = new SerialPortService(
    loggerFactory.CreateLogger<SerialPortService>(),
    discovery, connection, dataHandler);

// 获取可用串口
var ports = await serialPortService.GetAvailablePortsAsync();
foreach (var port in ports)
{
    Console.WriteLine($"发现串口:{port.DisplayName}");
}

// 连接串口
var settings = SerialPortExtensions.CreateSettings(115200);
var success = await serialPortService.ConnectAsync("COM1", settings);

if (success)
{
    // 发送数据
    await serialPortService.SendAsync("Hello, Serial Port!");
    
    // 发送十六进制数据
    await serialPortService.SendHexAsync("48 65 6C 6C 6F");
    
    // 断开连接
    await serialPortService.DisconnectAsync();
}

2. 依赖注入使用

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Liam.SerialPort.Extensions;

// 配置服务
var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        services.AddSerialPort();
        // 或使用服务池
        // services.AddSerialPortPool(poolSize: 5);
    })
    .Build();

// 获取串口服务
var serialPortService = host.Services.GetRequiredService<ISerialPortService>();

// 使用服务...

3. 集成Liam.Logging增强日志功能

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Liam.SerialPort.Extensions;

// 使用Liam.Logging增强日志功能
var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        // 方案一:使用预配置的Liam.Logging集成
        services.AddSerialPortWithLiamLogging(options =>
        {
            options.MinLogLevel = LogLevel.Debug;
            options.EnableConsoleLogging = true;
            options.EnableFileLogging = true;
            options.LogFilePath = "logs/serialport-{Date}.log";
            options.EnableStructuredLogging = true;
            options.EnableAsyncLogging = true;
            options.EnableLogRotation = true;
            options.MaxFileSize = 10 * 1024 * 1024; // 10MB
            options.MaxFiles = 5;
        });

        // 方案二:标准日志配置(如果不需要Liam.Logging)
        // services.AddSerialPort();
        // services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug));
    })
    .Build();

// 检查Liam.Logging是否可用
if (LiamLoggingExtensions.IsLiamLoggingAvailable())
{
    Console.WriteLine("使用Liam.Logging增强日志功能");
}
else
{
    Console.WriteLine("使用标准Microsoft.Extensions.Logging");
}

var serialPortService = host.Services.GetRequiredService<ISerialPortService>();
// 使用服务...

4. 事件处理

// 订阅事件
serialPortService.StatusChanged += (sender, e) =>
{
    Console.WriteLine($"连接状态变化:{e.OldStatus} -> {e.NewStatus}");
};

serialPortService.DataReceived += (sender, e) =>
{
    Console.WriteLine($"接收到数据:{e.DataAsString}");
    Console.WriteLine($"十六进制:{e.DataAsHex}");
};

serialPortService.ErrorOccurred += (sender, e) =>
{
    Console.WriteLine($"发生错误:{e.ErrorType} - {e.Message}");
};

serialPortService.DeviceChanged += (sender, e) =>
{
    Console.WriteLine($"设备变化:{e.ChangeType} - {e.DeviceInfo.PortName}");
};

API文档

核心接口

ISerialPortService

主要的串口服务接口,提供完整的串口通讯功能。

主要方法:

  • GetAvailablePortsAsync() - 获取可用串口列表
  • ConnectAsync() - 连接串口
  • DisconnectAsync() - 断开连接
  • SendAsync() - 发送数据
  • SendAndReceiveAsync() - 发送数据并等待响应
ISerialPortDiscovery

串口设备发现接口,提供设备枚举和热插拔检测。

主要方法:

  • GetAvailablePortsAsync() - 获取可用设备
  • StartMonitoringAsync() - 开始设备监控
  • StopMonitoringAsync() - 停止设备监控
ISerialPortConnection

串口连接管理接口,提供连接的建立、维护和断开。

主要方法:

  • ConnectAsync() - 建立连接
  • DisconnectAsync() - 断开连接
  • ReconnectAsync() - 重新连接
  • TestConnectionAsync() - 测试连接
ISerialPortDataHandler

串口数据处理接口,提供数据的发送、接收和缓冲管理。

主要方法:

  • SendAsync() - 发送数据
  • ReadAsync() - 读取数据
  • SendAndReceiveAsync() - 发送并接收
  • ClearReceiveBuffer() - 清空缓冲区

主要类

SerialPortSettings

串口配置设置类,包含所有串口参数配置。

主要属性:

public class SerialPortSettings
{
    public int BaudRate { get; set; } = 9600;           // 波特率
    public int DataBits { get; set; } = 8;              // 数据位
    public StopBits StopBits { get; set; }              // 停止位
    public Parity Parity { get; set; }                  // 校验位
    public Handshake Handshake { get; set; }            // 流控制
    public int ReadTimeout { get; set; } = 5000;        // 读取超时
    public int WriteTimeout { get; set; } = 5000;       // 写入超时
    public bool AutoReconnect { get; set; } = true;     // 自动重连
    // ... 更多属性
}
SerialPortInfo

串口设备信息类,包含设备的详细信息。

主要属性:

public class SerialPortInfo
{
    public string PortName { get; set; }                // 串口名称
    public string Description { get; set; }             // 设备描述
    public string Manufacturer { get; set; }            // 制造商
    public string ProductId { get; set; }               // 产品ID
    public string VendorId { get; set; }                // 供应商ID
    public bool IsAvailable { get; set; }               // 是否可用
    public bool IsUsbDevice { get; }                    // 是否USB设备
    // ... 更多属性
}

扩展方法

SerialPortExtensions

提供便捷的扩展方法。

主要方法:

  • SendHexAsync() - 发送十六进制数据
  • SendLineAsync() - 发送带换行符的数据
  • WaitForDataAsync() - 等待特定数据
  • ToHexString() - 转换为十六进制字符串
  • CreateHighSpeedSettings() - 创建高速设置

使用示例

设备发现和监控

// 获取所有可用串口
var ports = await serialPortService.GetAvailablePortsAsync();
foreach (var port in ports)
{
    Console.WriteLine($"串口:{port.PortName}");
    Console.WriteLine($"描述:{port.Description}");
    Console.WriteLine($"制造商:{port.Manufacturer}");
    Console.WriteLine($"是否USB设备:{port.IsUsbDevice}");
    Console.WriteLine("---");
}

// 监控设备变化
serialPortService.DeviceChanged += (sender, e) =>
{
    switch (e.ChangeType)
    {
        case DeviceChangeType.Inserted:
            Console.WriteLine($"设备插入:{e.DeviceInfo.PortName}");
            break;
        case DeviceChangeType.Removed:
            Console.WriteLine($"设备移除:{e.DeviceInfo.PortName}");
            break;
    }
};

高级数据处理

// 发送十六进制命令
await serialPortService.SendHexAsync("01 03 00 00 00 01 84 0A");

// 等待特定响应
var received = await serialPortService.WaitForDataAsync(
    new byte[] { 0x01, 0x03 }, 
    TimeSpan.FromSeconds(5));

// 批量发送数据
var commands = new[] { "CMD1", "CMD2", "CMD3" };
await serialPortService.SendBatchAsync(commands, TimeSpan.FromMilliseconds(100));

// 发送并等待响应
var response = await serialPortService.SendAndReceiveAsync(
    "AT+VERSION", 
    TimeSpan.FromSeconds(3));
Console.WriteLine($"设备版本:{response}");

错误处理和重连

// 配置自动重连
var settings = new SerialPortSettings
{
    BaudRate = 115200,
    AutoReconnect = true,
    AutoReconnectInterval = 5000,
    MaxAutoReconnectAttempts = 10
};

// 错误处理
serialPortService.ErrorOccurred += (sender, e) =>
{
    Console.WriteLine($"错误类型:{e.ErrorType}");
    Console.WriteLine($"错误消息:{e.Message}");
    
    if (e.IsFatal)
    {
        Console.WriteLine("致命错误,需要重新连接");
    }
};

// 状态监控
serialPortService.StatusChanged += (sender, e) =>
{
    Console.WriteLine($"状态变化:{e.OldStatus} -> {e.NewStatus}");
    
    if (e.NewStatus == ConnectionStatus.Connected)
    {
        Console.WriteLine("连接已建立");
    }
    else if (e.NewStatus == ConnectionStatus.Reconnecting)
    {
        Console.WriteLine("正在尝试重连...");
    }
};

性能优化

// 高性能设置
var highSpeedSettings = SerialPortExtensions.CreateHighSpeedSettings();
highSpeedSettings.ReceiveBufferSize = 16384;  // 16KB接收缓冲区
highSpeedSettings.SendBufferSize = 8192;      // 8KB发送缓冲区

// 使用服务池(适用于多串口应用)
services.AddSerialPortPool(poolSize: 10);

var pool = serviceProvider.GetRequiredService<ISerialPortServicePool>();
var service = await pool.GetServiceAsync();
try
{
    // 使用串口服务
    await service.ConnectAsync("COM1", settings);
    // ... 数据处理
}
finally
{
    await pool.ReturnServiceAsync(service);
}

日志集成

Liam.Logging集成

Liam.SerialPort v1.1.0开始支持与Liam.Logging的深度集成,提供更强大的日志功能:

功能特性
  • 结构化日志:支持JSON格式的结构化日志记录
  • 多输出目标:同时输出到控制台、文件、数据库等
  • 异步日志:真正的异步I/O,不阻塞主线程
  • 日志轮转:自动按大小或时间轮转日志文件
  • 性能监控:内置性能指标监控
  • 可选依赖:如果不需要可以完全禁用
使用方式

方案一:使用预配置集成

services.AddSerialPortWithLiamLogging(options =>
{
    options.MinLogLevel = LogLevel.Debug;
    options.EnableFileLogging = true;
    options.LogFilePath = "logs/serialport-{Date}.log";
    options.EnableLogRotation = true;
    options.MaxFileSize = 10 * 1024 * 1024; // 10MB
});

方案二:自定义Liam.Logging配置

services.AddSerialPort();
services.AddLiamLogging(config =>
{
    config.MinLevel = LogLevel.Trace;
    config.EnableStructuredLogging = true;
    config.AddFileProvider(fileConfig =>
    {
        fileConfig.FilePath = "logs/serialport-detailed-{Date}.log";
        fileConfig.EnableLogRotation = true;
    });
});

方案三:标准日志(无Liam.Logging)

services.AddSerialPort();
services.AddLogging(builder =>
{
    builder.AddConsole().SetMinimumLevel(LogLevel.Information);
});
日志级别说明
级别 用途 示例内容
Trace 详细调试信息 数据包内容、内部状态变化
Debug 调试信息 数据收发、连接状态
Information 一般信息 连接建立、设备发现
Warning 警告信息 重连尝试、设备断开
Error 错误信息 连接失败、数据传输错误
Critical 严重错误 致命错误、系统异常
性能影响
  • 标准日志:最小性能影响
  • Liam.Logging(异步):几乎无性能影响
  • Liam.Logging(同步):轻微性能影响
  • 文件日志:I/O操作会有一定影响

平台支持

  • Windows:支持COM端口,通过WMI获取详细设备信息
  • Linux:支持/dev/ttyUSB、/dev/ttyACM等设备
  • macOS:支持/dev/tty.usbserial等设备

技术规范

  • .NET版本:.NET 8.0
  • 语言版本:C# 12 (latest)
  • 依赖项
    • System.IO.Ports 8.0.0
    • Microsoft.Extensions.DependencyInjection.Abstractions 8.0.1
    • Microsoft.Extensions.Logging.Abstractions 8.0.1
    • Microsoft.Extensions.Options 8.0.2
    • Liam.Logging 1.1.0(可选,用于增强日志功能)

性能特性

  • 异步优先:所有I/O操作都支持异步
  • 内存优化:智能缓冲区管理,避免内存泄漏
  • 线程安全:所有公共API都是线程安全的
  • 资源管理:实现IDisposable和IAsyncDisposable模式

版本历史

版本 发布日期 主要变更
1.1.0 2025-06-15 新增Liam.Logging集成支持,提供增强的日志功能
1.0.0 2025-06-15 初始版本,包含完整的串口通讯功能

许可证

本项目采用MIT许可证 - 查看 LICENSE 文件了解详情。

贡献

欢迎提交Issue和Pull Request来帮助改进这个项目。

支持

如果您在使用过程中遇到问题,请:

  1. 查看本文档的常见问题部分
  2. 在GitHub上提交Issue
  3. 参考示例代码和单元测试

Liam.SerialPort - 让串口通讯更简单、更可靠!

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.

Version Downloads Last Updated
1.1.0 134 6/15/2025
1.0.0 132 6/15/2025