Alicres.SerialPort 1.0.0

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

Alicres.SerialPort

NuGet Version NuGet Downloads License: MIT

一个功能完整、易于使用的 .NET 串口通讯库,提供异步操作、事件驱动、自动重连等高级功能。

✨ 特性

  • 🚀 异步操作: 完全支持异步/等待模式
  • 📡 事件驱动: 基于事件的数据接收和状态变化通知
  • 🔄 自动重连: 内置智能重连机制
  • 🎯 多端口管理: 支持同时管理多个串口连接
  • 🛡️ 异常处理: 完善的异常处理和错误恢复
  • 📊 状态监控: 实时连接状态和数据统计
  • 🔧 依赖注入: 原生支持 .NET 依赖注入
  • 📝 详细日志: 集成 Microsoft.Extensions.Logging

📦 安装

Package Manager

Install-Package Alicres.SerialPort

.NET CLI

dotnet add package Alicres.SerialPort

PackageReference

<PackageReference Include="Alicres.SerialPort" Version="1.0.0" />

🚀 快速开始

基本使用

using Alicres.SerialPort.Models;
using Alicres.SerialPort.Services;
using Microsoft.Extensions.Logging;

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

// 配置串口
var configuration = new SerialPortConfiguration
{
    PortName = "COM1",
    BaudRate = 9600,
    DataBits = 8,
    EnableAutoReconnect = true
};

// 创建串口服务
using var serialPort = new SerialPortService(configuration, logger);

// 订阅数据接收事件
serialPort.DataReceived += (sender, e) =>
{
    Console.WriteLine($"接收到数据: {e.Data.ToText()}");
};

// 打开串口
if (await serialPort.OpenAsync())
{
    Console.WriteLine("串口打开成功");
    
    // 发送数据
    await serialPort.SendTextAsync("Hello, Serial Port!");
    
    // 等待一段时间接收数据
    await Task.Delay(5000);
}

依赖注入使用

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Alicres.SerialPort.Extensions;
using Alicres.SerialPort.Interfaces;

// 配置服务
var services = new ServiceCollection();
services.AddLogging(builder => builder.AddConsole());
services.AddAlicresSerialPort();

var serviceProvider = services.BuildServiceProvider();

// 获取串口管理器
var serialPortManager = serviceProvider.GetRequiredService<ISerialPortManager>();

// 创建串口配置
var config = SerialPortConfiguration.CreateDefault("COM1");
config.BaudRate = 115200;
config.EnableAutoReconnect = true;

// 创建并添加串口
var serialPort = serialPortManager.CreateSerialPort(config);

// 订阅全局事件
serialPortManager.DataReceived += (sender, e) =>
{
    Console.WriteLine($"[{e.Data.PortName}] 接收: {e.Data.ToText()}");
};

// 打开所有串口
await serialPortManager.OpenAllAsync();

多端口管理

// 创建多个串口配置
var configs = new[]
{
    SerialPortConfiguration.CreateDefault("COM1"),
    SerialPortConfiguration.CreateDefault("COM2"),
    SerialPortConfiguration.CreateDefault("COM3")
};

// 批量创建串口
foreach (var config in configs)
{
    config.BaudRate = 115200;
    config.EnableAutoReconnect = true;
    serialPortManager.CreateSerialPort(config);
}

// 批量打开
var openedCount = await serialPortManager.OpenAllAsync();
Console.WriteLine($"成功打开 {openedCount} 个串口");

// 广播数据
var broadcastCount = await serialPortManager.BroadcastTextAsync("广播消息");
Console.WriteLine($"成功向 {broadcastCount} 个串口发送数据");

📚 API 文档

核心接口

ISerialPortService

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

public interface ISerialPortService : IDisposable
{
    // 属性
    SerialPortConfiguration Configuration { get; }
    SerialPortStatus Status { get; }
    bool IsConnected { get; }
    
    // 事件
    event EventHandler<SerialPortDataReceivedEventArgs>? DataReceived;
    event EventHandler<SerialPortStatusChangedEventArgs>? StatusChanged;
    event EventHandler<SerialPortErrorEventArgs>? ErrorOccurred;
    
    // 方法
    Task<bool> OpenAsync(CancellationToken cancellationToken = default);
    Task<bool> CloseAsync(CancellationToken cancellationToken = default);
    Task<int> SendAsync(byte[] data, CancellationToken cancellationToken = default);
    Task<int> SendTextAsync(string text, Encoding? encoding = null, CancellationToken cancellationToken = default);
    // ... 更多方法
}
ISerialPortManager

串口管理器接口,用于管理多个串口连接。

public interface ISerialPortManager : IDisposable
{
    // 属性
    IReadOnlyDictionary<string, ISerialPortService> SerialPorts { get; }
    
    // 事件
    event EventHandler<SerialPortAddedEventArgs>? SerialPortAdded;
    event EventHandler<SerialPortRemovedEventArgs>? SerialPortRemoved;
    // ... 全局事件
    
    // 方法
    ISerialPortService CreateSerialPort(SerialPortConfiguration configuration);
    Task<int> OpenAllAsync(CancellationToken cancellationToken = default);
    Task<int> BroadcastAsync(byte[] data, CancellationToken cancellationToken = default);
    // ... 更多方法
}

配置选项

SerialPortConfiguration

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

public class SerialPortConfiguration
{
    public string PortName { get; set; }           // 端口名称
    public int BaudRate { get; set; }              // 波特率
    public int DataBits { get; set; }              // 数据位
    public StopBits StopBits { get; set; }         // 停止位
    public Parity Parity { get; set; }             // 校验位
    public bool EnableAutoReconnect { get; set; }  // 自动重连
    // ... 更多配置项
}

🔧 高级功能

自动重连

var config = new SerialPortConfiguration
{
    PortName = "COM1",
    EnableAutoReconnect = true,
    ReconnectInterval = 3000,      // 重连间隔 3 秒
    MaxReconnectAttempts = 5       // 最大重连次数
};

数据格式转换

// 接收数据事件处理
serialPort.DataReceived += (sender, e) =>
{
    var data = e.Data;
    
    // 转换为文本
    var text = data.ToText(Encoding.UTF8);
    
    // 转换为十六进制
    var hex = data.ToHexString(" ", true);
    
    Console.WriteLine($"文本: {text}");
    Console.WriteLine($"十六进制: {hex}");
};

// 从十六进制字符串发送数据
var hexData = SerialPortData.FromHexString("48 65 6C 6C 6F", "COM1");
await serialPort.SendAsync(hexData.RawData);

状态监控

// 监控连接状态变化
serialPort.StatusChanged += (sender, e) =>
{
    Console.WriteLine($"状态变化: {e.PreviousState} -> {e.CurrentState}");
};

// 获取详细状态信息
var status = serialPort.Status;
Console.WriteLine($"连接状态: {status.ConnectionState}");
Console.WriteLine($"发送字节数: {status.BytesSent}");
Console.WriteLine($"接收字节数: {status.BytesReceived}");
Console.WriteLine($"重连次数: {status.ReconnectAttempts}");

🛠️ 错误处理

库提供了完善的异常处理机制:

try
{
    await serialPort.OpenAsync();
}
catch (SerialPortConnectionException ex)
{
    Console.WriteLine($"连接失败: {ex.Message}");
}
catch (SerialPortConfigurationException ex)
{
    Console.WriteLine($"配置错误: {ex.Message}");
}
catch (SerialPortDataException ex)
{
    Console.WriteLine($"数据传输错误: {ex.Message}");
}

📋 系统要求

  • .NET 8.0 或更高版本
  • Windows、Linux、macOS(支持 System.IO.Ports 的平台)

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

本项目采用 MIT 许可证

🔗 相关链接

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 (1)

Showing the top 1 NuGet packages that depend on Alicres.SerialPort:

Package Downloads
Alicres.Protocol

A comprehensive communication protocol library for .NET, supporting multiple transport layers including Serial Port, TCP, and UDP with extensible protocol parsing framework.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 400 6/12/2025
1.0.1 345 6/11/2025
1.0.0 340 6/11/2025