JCoder.HCP4Net 3.2613.1

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

JCoder.HCP4Net

目录

[TOC]

一.架构说明

JCoder.HCP4Net
语言 C#
协议 MIT
.Net框架 .Net Standard2.1; .Net Framework 4.7.2; .Net 6; .Net 8; .Net 10;
简述 HCP = Host Communication Protocol.(用于上位机通讯协议的类库,定义协议抽象、消息实体、协议适配器,以及可扩展的工业自动化模块层;具体平台客户端与传输实现见 JCoder.HCP4Net.LinuxOS / JCoder.HCP4Net.WinOS。)

1.1 引用类库

引用类库 版本
- -

1.2 相关类库

| 相关类库 | 说明 | | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | JCoder.HCP4Net.LinuxOS | 面向Linux系统的上位机通讯协议客户端类库(Modbus RTU/TCP、Siemens S7、OPC UA)。 | | JCoder.HCP4Net.WinOS | 面向Windows系统的上位机通讯协议客户端类库(Modbus RTU/TCP、Siemens S7、OPC UA)。 |

获取方式

  1. 版本要求:>=3.2612.1
  2. 以版本3.2612.1 为例
获取方式 描述
Package Manager Install-Package JCoder.HCP4Net -Version 3.2612.1
.Net CLI dotnet add package JCoder.HCP4Net --version 3.2612.1
PackageReference <PackageReference Include="JCoder.HCP4Net" Version="3.2612.1 " />
Paket CLI paket add JCoder.HCP4Net --version 3.2612.1
Script&Interactive #r "nuget: JCoder.HCP4Net, 3.2612.1 "
Cake // Install JCoder.HCP4Net as a Cake Addin<br/>#addin nuget:?package=JCoder.HCP4Net&version=3.2612.1 <br/><br/>// Install JCoder.HCP4Net as a Cake Tool<br/>#tool nuget:?package=JCoder.HCP4Net&version=3.2612.1

使用说明

本类库定义协议抽象、消息实体与协议适配器(IHCPAdapter),并在其之上提供可扩展的工业自动化模块层(IIotModule);两者都不包含具体的传输层实现。 实际连接设备时,请根据运行平台引用 JCoder.HCP4Net.LinuxOS 或 JCoder.HCP4Net.WinOS——串口 / TCP 链路实现(SerialCommLink、TcpCommLink)与链路工厂注册都在平台库中,核心库只依赖 ICommLink 抽象,因此保持跨平台中立。

分层关系:

层次 位置 职责
模块层 核心库 设备建模:通道、量程换算、数据处理、轮询、状态机、型号工厂
协议层 核心库 报文编解码:请求实体 ↔ 字节流(IHCPAdapter、ModbusRtu 等)
链路层 平台库 物理收发:串口 / TCP 的打开、发送、帧接收、超时(ICommLink 的实现)

1. 使用 Modbus RTU 适配器手动组包/解析



// 构造 Modbus RTU 适配器
var _adapter = new HCPModbusAdapter();

// 1) 组包:读保持寄存器(功能码 0x03,从站 0x01,起始地址 0x0000,读 10 个寄存器)
var _request = new HCPModbusRequestMessageForRead
{
    SlaveAddress = 0x01,
    FunctionCode = (byte)ModbusFunctionCode.ReadHoldingRegisters,
    Address = 0x0000,
    Qty = 10,
};
byte[] _requestBytes = _adapter.ToRequestBytes(_request);

// 2) 解析响应:把设备返回的字节流解析为强类型响应实体
// byte[] _responseBytes = ...; // 从串口/TCP收到的原始帧
// HCPModbusResponseMessage _response = _adapter.ToResponse<HCPModbusResponseMessage>(_responseBytes);
// ushort[] _values = _response.Content as ushort[];

2. 使用 Modbus RTU 适配器写单个线圈



var _adapter = new HCPModbusAdapter();

// 写单个线圈(功能码 0x05):把从站 0x01 地址 0x0002 的线圈置为 ON
var _coilRequest = new HCPModbusRequestMessageForWriteSingleCoil
{
    SlaveAddress = 0x01,
    Address = 0x0002,
    Status = true,
};
byte[] _bytes = _adapter.ToRequestBytes(_coilRequest);

3. 反向解析请求帧(用于服务端/报文回放)



var _adapter = new HCPModbusAdapter();

// byte[] _rawFrame = ...; // 收到的 Modbus RTU 请求原始字节
// IHCPRequestMessage _req = _adapter.ToRequest(_rawFrame);
// if (_req is HCPModbusRequestMessageForRead _read)
// {
//     // _read.SlaveAddress / _read.FunctionCode / _read.Address / _read.Qty
// }

4. 模块层:按型号创建 IO 板并读写通道

模块层把「设备」建模为**通道(ChannelDefinition)**的集合,业务层只按编码读写工程值,不接触寄存器地址与字节序。

// 注册内置型号(程序启动时调用一次)
BuiltInModules.RegisterAll();

// 按型号 + 链路配置创建模块(RS485 串口,站号 1)
using IIotModule io = ModuleFactory.Default.Create(
    model: "IO",
    id: "IO-1",
    linkConfig: new SerialLinkConfig("COM3", 9600),
    slaveId: 1,
    name: "1号工位",
    parameters: new Dictionary<string, string>
    {
        ["InputCount"] = "16",
        ["OutputCount"] = "16",
    });

// 订阅通道变化(已按死区过滤,避免抖动刷屏)
io.ValueChanged += (s, e) => Console.WriteLine($"{e.ModuleId}.{e.Channel.Code} = {e.NewValue.Value}");

io.Connect();          // 打开串口链路
io.Refresh();          // 批量采集全部输入(地址连续的点自动合并为一次往返)

bool x1 = io.Read("X1").ToBoolean();   // 读缓存,不发起通讯,适合高频刷新
io.Write("Y1", true);                  // 写数字量输出

5. 模块层:电机模块(自动换算脉冲 ↔ 机械量)

电机位置在寄存器里是脉冲数,而工艺要求的是 mm / °。StepMotorModule 按运动学参数自动换算,业务层直接以机械量读写:

using IIotModule motor = ModuleFactory.Default.Create(
    "STEP_MOTOR", "M-1", new SerialLinkConfig("COM4", 115200), slaveId: 1,
    parameters: new Dictionary<string, string>
    {
        ["PulsesPerRevolution"] = "3200",  // 每转脉冲数
        ["LeadMm"] = "10",                 // 丝杆导程 10mm
        ["GearRatio"] = "1",               // 减速比
        ["ActualPositionAddress"] = "5",   // 位置反馈寄存器(-1 表示开环无反馈)
    });

var m = (StepMotorModule)motor;
m.Connect();
m.MoveTo(25.0, velocity: 10.0);          // 移动到 25mm,速度 10mm/s(内部换算为脉冲)
double now = m.Read(StepMotorModule.ActualPositionCode).Value;  // 反馈即为 mm
m.MoveBy(5.0);                           // 相对当前位置再走 5mm
m.Stop();

6. 模块层:RS485 / RS232 通用仪表(配置驱动,无需写代码)

现场仪表型号繁杂,GenericRs485Module 的通道表由参数 ChannelMap 驱动,接入新型号只需填一份配置。 字段顺序为 编码,名称,数据区,地址,寄存器数,换算,单位,方向,下限,上限,死区(换算参数内部用 / 分隔,避免与字段的 , 冲突):

string map = string.Join("\n",
    "PV,   当前温度, IR,   0, 1, Fix1,               ℃,    In,    -50, 400, 0.2",
    "SV,   设定温度, HR,   0, 1, Fix1,               ℃,    InOut, -50, 400",
    "RUN,  输出中,   HR,   8, 1, Bit:0,              ,     In",
    "FLOW, 瞬时流量, IR,  10, 2, Float,              m³/h, In,    0,   999",
    "LOAD, 负载率,   IR,  20, 1, Range:6400/32000/0/100, %, In");

using IIotModule tc = ModuleFactory.Default.Create(
    "RS485_GENERIC", "TC-1", new SerialLinkConfig("COM5", 9600), slaveId: 2,
    parameters: new Dictionary<string, string> { ["ChannelMap"] = map });

tc.Connect();
tc.Refresh();
double temp = tc.Read("PV").Value;

7. 数据处理单位:滤波、限幅、报警

Scaling(IScaling)负责协议层换算(原始值 ↔ 工程值);Processing(IChannelProcessor)负责信号层处理(滤波、限幅、报警),两者都是工业自动化的基本数据处理单位。处理顺序为「换算 → 处理 → 死区过滤 → 缓存/事件」。

// 为某模块的所有通道套用默认处理,再对个别通道单独覆盖
var registry = ModuleBase.DefaultProcessingRegistry;

registry.SetDefault("M-1", ChannelProcessingPipeline.Of(
    new MedianFilterProcessor(3),                       // 中值滤波,去电机启停脉冲干扰
    new ClampProcessor(0, 100)));                        // 限幅兜底

registry.Set("TC-1", "PV", ChannelProcessingPipeline.Of(
    new MovingAverageProcessor(4),                       // 滑动平均,平滑温度波动
    new AlarmProcessor(AlarmLimitMode.High, highLimit: 80, hysteresis: 5)));  // 超 80 报警,回差 5

数据处理单位无状态或有状态均可,ModuleBase.Connect() 会在连接成功后自动 ResetProcessing(),避免断线期样本污染滤波器窗口。

8. 链路层:核心库经注册表创建传输实现(平台库自动注册)

核心库不引用 System.IO.Ports。引用平台库后,HCPLinkProvider 会经模块初始化器自动注册 Serial / Tcp 链路工厂,CommLinkPool 据此按 LinkConfig 创建链路,同一 Key 的链路自动复用(一条 RS485 总线挂多个站号时不会重复打开串口)。若代码只触达核心库类型、未加载平台程序集,可显式调用一次:

// Windows
JCoder.HCP4Net.WinOS.HCPLinkProvider.Register();
// Linux
JCoder.HCP4Net.LinuxOS.HCPLinkProvider.Register();

主要类与接口

类型 名称 类型 说明
接口 IHCPClient 接口 上位机通讯客户端抽象(连接/断开、发送请求、事件、自动重连、心跳)。
接口 IHCPAdapter 接口 协议适配器:请求实体 ↔ 字节流、响应字节流 → 响应实体。
接口 IHCPConfig 接口 通讯配置标记接口。
接口 IHCPRequestMessage / IHCPResponseMessage 接口 请求/响应消息抽象,均继承 IHCPMessage。
类 HCPModbusAdapter 类 Modbus RTU 协议适配器(CRC-16 校验,功能码 0x01~0x10)。
类 HCPModbusTcpAdapter 类 Modbus TCP 协议适配器(MBAP 报文头)。
类 HCPSiemensAdapter 类 西门子 S7 协议适配器(TPKT/COTP/S7)。
类 HCPOpcUaAdapter 类 OPC UA 协议适配器(HEL/ACK、OPN/MSG)。
类 HCPModbusRequestMessageForRead 类 Modbus RTU 读请求(SlaveAddress/FunctionCode/Address/Qty)。
类 HCPModbusRequestMessageForWriteSingleCoil 类 Modbus RTU 写单线圈请求(Status)。
类 HCPModbusRequestMessageForWriteSingleRegister 类 Modbus RTU 写单寄存器请求(Value)。
类 HCPModbusResponseMessage 类 Modbus RTU 响应实体(Data/FunctionCode/Content)。
类 HCPModbusTcpRequestMessageForRead 类 Modbus TCP 读请求(UnitId/TransactionId/Address/Qty)。
类 HCPSiemensRequestMessage 类 西门子 S7 读/写请求(Rack/Slot/MemoryArea/DbNumber/StartByteAddress)。
类 HCPOpcUaRequestMessage 类 OPC UA 请求消息(MessageType/ServiceType/Body)。
类 HCPSerialPortConfig 类 串口配置(PortName/BaudRate/DataBits/Parity/StopBits)。
类 ChecksumUtility 类 校验工具(CalculateCRC16)。
枚举 ModbusFunctionCode 枚举 Modbus 功能码(ReadCoils/ReadHoldingRegisters/WriteSingleRegister 等)。
枚举 ModbusExceptionCode 枚举 Modbus 异常码。
枚举 SiemensS7MemoryArea / SiemensS7TransportSize / SiemensS7FunctionCode 枚举 西门子 S7 相关枚举。
枚举 OpcUaMessageType / OpcUaServiceType / OpcUaDataTypeId 枚举 OPC UA 相关枚举。
模块层(工业自动化设备建模)
类型 名称 说明
接口 IIotHardware / IIotModule 自动化硬件身份契约与模块统一契约(生命周期 + 通道读写 + 事件)。
接口 ICommLink 物理链路抽象(打开/关闭、发一帧收一帧),实现位于平台库。
接口 ICommLinkFactory 链路工厂抽象,由平台库实现并注册。
接口 IScaling 协议层数据处理单位:寄存器原始值 ↔ 工程值。
接口 IChannelProcessor 信号层数据处理单位:滤波、限幅、报警等。
类 ModuleBase 模块基类:生命周期、通道注册、值缓存、死区过滤、状态机。
类 ModbusModuleBase MODBUS 从站模块基类:地址映射、批量读取块合并、换算。
类 ChannelDefinition / ChannelDefinitionBuilder 通道定义(工业自动化最基本的数据处理单位)与其流式构建器。
类 HCPChannelValue 通道运行时值:工程值 + 质量戳 + 时间戳。
类 ModuleFactory / ModuleRegistration / ModuleCreationContext 型号注册工厂:新增设备型号无需改动上层代码。
类 BuiltInModules 内置型号注册入口。
类 CommLinkPool / CommLinkFactoryRegistry 链路引用计数池与链路工厂注册表。
类 LinkConfig / SerialLinkConfig / TcpLinkConfig 链路配置(Key 决定链路是否可共享)。
类 ModbusRtu / ModbusCrc / ModbusAddress MODBUS RTU 帧编解码、CRC 校验与地址模型。
类 ChannelProcessingPipeline / ChannelProcessingRegistry 处理管线与按「模块 + 通道」的处理配置注册表。
类 DIO16Module IO 板:16路数字量输入 / 输出(DIO16)。
类 StepMotorModule 电机:通用步进 / 电机驱动器,自动换算脉冲 ↔ mm/°(STEP_MOTOR)。
类 ServoDriveModuleBase 伺服驱动器可扩展基类(CiA 402 标准操作,地址由子类提供)。
类 GenericRs485Module / ChannelMapEntry RS485 / RS232 通用仪表:通道表由参数驱动(RS485_GENERIC)。
类 MotionKinematics / KinematicsScaling 运动学数据处理单位:机械量 ↔ 脉冲数(丝杆 / 同步带 / 旋转轴)。
类 LinearScaling / RawScaling / BitExtractScaling / ThermocoupleScaling / LookupTableScaling 换算策略:线性、透传、按位提取、热电偶、查表插值。
类 SingleScaling / DoubleScaling IEEE 754 浮点换算(字序可配置,占 2 / 4 寄存器)。
类 MedianFilterProcessor / MovingAverageProcessor 中值滤波(去脉冲干扰)、滑动平均 / 指数平滑。
类 ClampProcessor / AlarmProcessor 限幅、报警判定(带回差,降级质量戳而非改值)。
类 ProtocolException 及其派生 通讯异常体系:LinkException / ResponseTimeoutException / FrameFormatException / DeviceException / ChannelAccessException。
枚举 HCPModuleCategory 模块类别(IoBoard / AnalogInput / ServoDrive / MotorDrive / PowerSupply / Sensor / Plc 等)。
枚举 HCPModuleState 模块状态机(Created / Connecting / Connected / Faulted / Disconnecting / Disposed)。
枚举 HCPChannelQuality 通道质量戳(Good / Bad / Uncertain / Stale / NotConnected,可组合)。
枚举 HCPChannelDirection / HCPChannelKind / HCPChannelDataType 通道方向、物理类型、工程值数据类型。
枚举 HCPWordOrder 多寄存器字序(BigEndian / LittleEndian / 两种字节交换)。
枚举 HCPAccessPriority 通道访问优先级。
枚举 AlarmLimitMode 报警限模式(None / High / Low / Both)。
枚举 MotionOperationMode 运动控制操作模式(位置 / 速度 / 扭矩 / 回零 / 插补)。
枚举 HCPSerialParity / HCPSerialStopBits 串口校验位与停止位(数值与 System.IO.Ports 一致,平台库可直接强转)。

参考

  1. 参考JCoder.HCP4Net
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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 is compatible.  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. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
.NET Framework net472 is compatible.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.7.2

  • .NETStandard 2.1

    • No dependencies.
  • net10.0

    • No dependencies.
  • net6.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on JCoder.HCP4Net:

Package Downloads
JCoder.HCP4Net.WinOS

HCP = Host Communication Protocol.(用于上位机通讯协议的客户端类库,面向Windows系统)

JCoder.HCP4Net.LinuxOS

HCP = Host Communication Protocol.(用于上位机通讯协议的客户端类库,面向Linux系统)

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.2613.1 148 11/2/2026
3.2612.1 179 9/13/2026

Please contact Jackie by QQ 1378071853 or E-mail JackieLaw-dev@outlook.com;