设备基础命令
This commit is contained in:
81
DeviceCommand/Base/EnovaDataReporter.cs
Normal file
81
DeviceCommand/Base/EnovaDataReporter.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Model.Model;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
|
||||
public class EnovaDataReporter : IEnovaDataReporter
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
// 显式实现/自动属性,方便外部随时更新配置
|
||||
public string TargetUrl { get; set; } = "http://127.0.0.1:8080/api/channel/state";
|
||||
public int TimeoutMilliseconds { get; set; } = 5000;
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数注入 HttpClient(符合 Prism 依赖注入规范)
|
||||
/// </summary>
|
||||
public EnovaDataReporter(HttpClient httpClient)
|
||||
{
|
||||
// 如果容器没有注入,则给个默认的单例/实例防空
|
||||
_httpClient = httpClient ?? new HttpClient();
|
||||
}
|
||||
|
||||
public async Task<EnovaReportResponse> ReportChannelStateAsync(List<EnovaChannelReportData> dataList, CancellationToken ct = default)
|
||||
{
|
||||
if (dataList == null || dataList.Count == 0)
|
||||
{
|
||||
return new EnovaReportResponse { Success = false, ErrorInfo = "上报数据集合为空" };
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(TargetUrl))
|
||||
{
|
||||
return new EnovaReportResponse { Success = false, ErrorInfo = "目标上报 URL 未配置" };
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 序列化为标准 JSON 字符串
|
||||
string jsonPayload = JsonConvert.SerializeObject(dataList);
|
||||
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
|
||||
|
||||
// 2. 绑定联动超时控制
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (TimeoutMilliseconds > 0)
|
||||
{
|
||||
cts.CancelAfter(TimeoutMilliseconds);
|
||||
}
|
||||
|
||||
HttpResponseMessage response = await _httpClient.PostAsync(TargetUrl, content, cts.Token);
|
||||
|
||||
// 4. 解析返回值
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
var result = JsonConvert.DeserializeObject<EnovaReportResponse>(responseContent);
|
||||
return result ?? new EnovaReportResponse { Success = true }; // 防止对方返回空Body [cite: 261]
|
||||
}
|
||||
else
|
||||
{
|
||||
return new EnovaReportResponse
|
||||
{
|
||||
Success = false,
|
||||
ErrorInfo = $"服务器响应错误代码: {(int)response.StatusCode} {response.ReasonPhrase}"
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 完美承接你上位机原有的异常日志记录器逻辑
|
||||
// Logger.LoggerHelper.ErrorWithNotify($"Enova3 数据上传失败: {ex.Message}");
|
||||
return new EnovaReportResponse { Success = false, ErrorInfo = $"网络异常: {ex.Message}" };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
16
DeviceCommand/Base/IBaseInterface.cs
Normal file
16
DeviceCommand/Base/IBaseInterface.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using NModbus;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public interface IBaseInterface
|
||||
{
|
||||
public bool IsConnected { get; }
|
||||
public Task<bool> ConnectAsync(CancellationToken ct = default);
|
||||
public void Close();
|
||||
}
|
||||
}
|
||||
31
DeviceCommand/Base/IEnovaDataReporter.cs
Normal file
31
DeviceCommand/Base/IEnovaDataReporter.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Model.Model;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
/// <summary>
|
||||
/// Enova3 上位机数据上报核心接口
|
||||
/// </summary>
|
||||
public interface IEnovaDataReporter
|
||||
{
|
||||
/// <summary>
|
||||
/// 客户平台接收数据的目标 HTTP URL
|
||||
/// </summary>
|
||||
string TargetUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 请求超时时间(毫秒)
|
||||
/// </summary>
|
||||
int TimeoutMilliseconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 异步推送通道的实时状态数据到客户平台
|
||||
/// </summary>
|
||||
/// <param name="dataList">包含各通道状态的采集数据集合</param>
|
||||
/// <param name="ct">取消令牌</param>
|
||||
/// <returns>平台服务器的响应状态</returns>
|
||||
Task<EnovaReportResponse> ReportChannelStateAsync(List<EnovaChannelReportData> dataList, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
19
DeviceCommand/Base/IModbusDevice.cs
Normal file
19
DeviceCommand/Base/IModbusDevice.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using NModbus;
|
||||
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public interface IModbusDevice : IBaseInterface,IDisposable
|
||||
{
|
||||
IModbusMaster Modbus { get; }
|
||||
|
||||
Task WriteSingleRegisterAsync(byte slaveAddress, ushort registerAddress, ushort value, CancellationToken ct = default);
|
||||
Task WriteMultipleRegistersAsync(byte slaveAddress, ushort startAddress, ushort[] values, CancellationToken ct = default);
|
||||
Task<ushort[]> ReadHoldingRegistersAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default);
|
||||
|
||||
Task WriteSingleCoilAsync(byte slaveAddress, ushort coilAddress, bool value, CancellationToken ct = default);
|
||||
Task<bool[]> ReadCoilsAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default);
|
||||
|
||||
Task<ushort[]> ReadInputRegistersAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
22
DeviceCommand/Base/IS7Device.cs
Normal file
22
DeviceCommand/Base/IS7Device.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using S7.Net;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public interface IS7Device : IBaseInterface, IDisposable
|
||||
{
|
||||
// 暴露出 S7.Net 原生的 Plc 对象,方便外部进行复杂扩展
|
||||
Plc PlcContext { get; }
|
||||
|
||||
// 核心读写接口(支持直接传物理地址,如 "DB1.DBD0" 或 "M0.0")
|
||||
Task WriteAsync(string address, object value, CancellationToken ct = default);
|
||||
Task<object> ReadAsync(string address, CancellationToken ct = default);
|
||||
Task<T> ReadAsync<T>(string address, CancellationToken ct = default);
|
||||
|
||||
// 批量读取/写入原始字节(常用于大块数据交互)
|
||||
Task<byte[]> ReadBytesAsync(DataType dataType, int db, int startByteAdr, int count, CancellationToken ct = default);
|
||||
Task WriteBytesAsync(DataType dataType, int db, int startByteAdr, byte[] value, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
13
DeviceCommand/Base/ISerialPort.cs
Normal file
13
DeviceCommand/Base/ISerialPort.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public interface ISerialPort : IBaseInterface,IDisposable
|
||||
{
|
||||
Task SendAsync(string data, CancellationToken ct = default);
|
||||
Task<string> ReadAsync(string delimiter = "\n", CancellationToken ct = default);
|
||||
Task<string> WriteReadAsync(string command, string delimiter = "\n", CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
15
DeviceCommand/Base/ITcp.cs
Normal file
15
DeviceCommand/Base/ITcp.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public interface ITcp : IBaseInterface,IDisposable
|
||||
{
|
||||
Task SendAsync(byte[] buffer, CancellationToken ct = default);
|
||||
Task SendAsync(string str, CancellationToken ct = default);
|
||||
Task<byte[]> ReadAsync(int length, CancellationToken ct = default);
|
||||
Task<string> ReadAsync(string delimiter = "\n", CancellationToken ct = default);
|
||||
Task<string> WriteReadAsync(string command, string delimiter = "\n", CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
164
DeviceCommand/Base/ModbusRtu.cs
Normal file
164
DeviceCommand/Base/ModbusRtu.cs
Normal file
@@ -0,0 +1,164 @@
|
||||
using NModbus;
|
||||
using NModbus.Serial;
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public class ModbusRtu : IModbusDevice
|
||||
{
|
||||
public string PortName { get; private set; } = "COM1";
|
||||
public int BaudRate { get; private set; } = 9600;
|
||||
public int DataBits { get; private set; } = 8;
|
||||
public StopBits StopBits { get; private set; } = StopBits.One;
|
||||
public Parity Parity { get; private set; } = Parity.None;
|
||||
public int ReadTimeout { get; private set; } = 3000;
|
||||
public int WriteTimeout { get; private set; } = 3000;
|
||||
|
||||
private SerialPort _serialPort;
|
||||
public IModbusMaster Modbus { get; private set; }
|
||||
public bool IsConnected => _serialPort?.IsOpen ?? false;
|
||||
|
||||
protected readonly SemaphoreSlim _commLock = new(1, 1);
|
||||
|
||||
public ModbusRtu()
|
||||
{
|
||||
_serialPort = new SerialPort();
|
||||
}
|
||||
|
||||
public void ConfigureDevice(string portName, int baudRate, int dataBits = 8, StopBits stopBits = StopBits.One, Parity parity = Parity.None, int readTimeout = 3000, int writeTimeout = 3000)
|
||||
{
|
||||
PortName = portName;
|
||||
BaudRate = baudRate;
|
||||
DataBits = dataBits;
|
||||
StopBits = stopBits;
|
||||
Parity = parity;
|
||||
ReadTimeout = readTimeout;
|
||||
WriteTimeout = writeTimeout;
|
||||
}
|
||||
|
||||
public virtual async Task<bool> ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_serialPort.IsOpen)
|
||||
_serialPort.Close();
|
||||
|
||||
_serialPort.PortName = PortName;
|
||||
_serialPort.BaudRate = BaudRate;
|
||||
_serialPort.DataBits = DataBits;
|
||||
_serialPort.StopBits = StopBits;
|
||||
_serialPort.Parity = Parity;
|
||||
_serialPort.ReadTimeout = ReadTimeout;
|
||||
_serialPort.WriteTimeout = WriteTimeout;
|
||||
_serialPort.Open();
|
||||
|
||||
Modbus = new ModbusFactory().CreateRtuMaster(_serialPort);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Close()
|
||||
{
|
||||
if (_serialPort.IsOpen)
|
||||
_serialPort.Close();
|
||||
}
|
||||
|
||||
public async Task WriteSingleRegisterAsync(byte slaveAddress, ushort registerAddress, ushort value, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await Modbus.WriteSingleRegisterAsync(slaveAddress, registerAddress, value)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(WriteTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteMultipleRegistersAsync(byte slaveAddress, ushort startAddress, ushort[] values, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await Modbus.WriteMultipleRegistersAsync(slaveAddress, startAddress, values)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(WriteTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ushort[]> ReadHoldingRegistersAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Modbus.ReadHoldingRegistersAsync(slaveAddress, startAddress, numberOfPoints)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReadTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteSingleCoilAsync(byte slaveAddress, ushort coilAddress, bool value, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await Modbus.WriteSingleCoilAsync(slaveAddress, coilAddress, value)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(WriteTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool[]> ReadCoilsAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Modbus.ReadCoilsAsync(slaveAddress, startAddress, numberOfPoints)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReadTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ushort[]> ReadInputRegistersAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Modbus.ReadInputRegistersAsync(slaveAddress, startAddress, numberOfPoints)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReadTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_serialPort?.Dispose();
|
||||
_commLock?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
158
DeviceCommand/Base/ModbusTcp.cs
Normal file
158
DeviceCommand/Base/ModbusTcp.cs
Normal file
@@ -0,0 +1,158 @@
|
||||
using NModbus;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public class ModbusTcp : IModbusDevice
|
||||
{
|
||||
public string IPAddress { get; private set; } = "127.0.0.1";
|
||||
public int Port { get; private set; } = 502;
|
||||
public int SendTimeout { get; private set; } = 3000;
|
||||
public int ReceiveTimeout { get; private set; } = 3000;
|
||||
|
||||
private TcpClient _tcpClient;
|
||||
public IModbusMaster Modbus { get; private set; }
|
||||
public bool IsConnected => _tcpClient?.Connected ?? false;
|
||||
|
||||
protected readonly SemaphoreSlim _commLock = new(1, 1);
|
||||
|
||||
public ModbusTcp()
|
||||
{
|
||||
_tcpClient = new TcpClient();
|
||||
}
|
||||
|
||||
public void ConfigureDevice(string ipAddress, int port, int sendTimeout = 3000, int receiveTimeout = 3000)
|
||||
{
|
||||
IPAddress = ipAddress;
|
||||
Port = port;
|
||||
SendTimeout = sendTimeout;
|
||||
ReceiveTimeout = receiveTimeout;
|
||||
}
|
||||
|
||||
public virtual async Task<bool> ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_tcpClient.Connected)
|
||||
{
|
||||
var remoteEndPoint = (IPEndPoint)_tcpClient.Client.RemoteEndPoint!;
|
||||
if (remoteEndPoint.Address.MapToIPv4().ToString() == IPAddress && remoteEndPoint.Port == Port)
|
||||
return true;
|
||||
}
|
||||
|
||||
_tcpClient.Close();
|
||||
_tcpClient.Dispose();
|
||||
_tcpClient = new TcpClient();
|
||||
|
||||
await _tcpClient.ConnectAsync(IPAddress, Port, ct);
|
||||
Modbus = new ModbusFactory().CreateMaster(_tcpClient);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Close()
|
||||
{
|
||||
if (_tcpClient.Connected) _tcpClient.Close();
|
||||
}
|
||||
|
||||
public async Task WriteSingleRegisterAsync(byte slaveAddress, ushort registerAddress, ushort value, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
// 修复:FromMinutes 改为 FromMilliseconds
|
||||
await Modbus.WriteSingleRegisterAsync(slaveAddress, registerAddress, value)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(SendTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteMultipleRegistersAsync(byte slaveAddress, ushort startAddress, ushort[] values, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await Modbus.WriteMultipleRegistersAsync(slaveAddress, startAddress, values)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(SendTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ushort[]> ReadHoldingRegistersAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Modbus.ReadHoldingRegistersAsync(slaveAddress, startAddress, numberOfPoints)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReceiveTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteSingleCoilAsync(byte slaveAddress, ushort coilAddress, bool value, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await Modbus.WriteSingleCoilAsync(slaveAddress, coilAddress, value)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(SendTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool[]> ReadCoilsAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Modbus.ReadCoilsAsync(slaveAddress, startAddress, numberOfPoints)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReceiveTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ushort[]> ReadInputRegistersAsync(byte slaveAddress, ushort startAddress, ushort numberOfPoints, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Modbus.ReadInputRegistersAsync(slaveAddress, startAddress, numberOfPoints)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReceiveTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_tcpClient?.Dispose();
|
||||
_commLock?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
169
DeviceCommand/Base/S7Device.cs
Normal file
169
DeviceCommand/Base/S7Device.cs
Normal file
@@ -0,0 +1,169 @@
|
||||
using S7.Net;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public class S7Device : IS7Device
|
||||
{
|
||||
// 保持和你一致的连接参数命名属性
|
||||
public string IPAddress { get; private set; } = "127.0.0.1";
|
||||
public CpuType CpuType { get; private set; } = CpuType.S71200;
|
||||
public short Rack { get; private set; } = 0;
|
||||
public short Slot { get; private set; } = 1;
|
||||
public int SendTimeout { get; private set; } = 3000;
|
||||
public int ReceiveTimeout { get; private set; } = 3000;
|
||||
|
||||
private Plc _plc;
|
||||
public Plc PlcContext => _plc;
|
||||
|
||||
// S7.Net 的 Plc.IsConnected 属性内部会通过 Socket 状态进行判断
|
||||
public bool IsConnected => _plc?.IsConnected ?? false;
|
||||
|
||||
// 统一线程锁
|
||||
protected readonly SemaphoreSlim _commLock = new(1, 1);
|
||||
|
||||
public S7Device()
|
||||
{
|
||||
// 初始化默认配置
|
||||
_plc = new Plc(CpuType, IPAddress, Rack, Slot);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设备参数配置(符合你的命名风格)
|
||||
/// </summary>
|
||||
public void ConfigureDevice(string ipAddress, CpuType cpuType, short rack = 0, short slot = 1, int sendTimeout = 3000, int receiveTimeout = 3000)
|
||||
{
|
||||
IPAddress = ipAddress;
|
||||
CpuType = cpuType;
|
||||
Rack = rack;
|
||||
Slot = slot;
|
||||
SendTimeout = sendTimeout;
|
||||
ReceiveTimeout = receiveTimeout;
|
||||
}
|
||||
|
||||
public virtual async Task<bool> ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
// 如果已经连接,检查当前的 IP 和 CPU 类型是否一致,一致则直接复用
|
||||
if (_plc != null && _plc.IsConnected)
|
||||
{
|
||||
if (_plc.IP == IPAddress && _plc.CPU == CpuType && _plc.Rack == Rack && _plc.Slot == Slot)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 修复:释放并彻底清空旧连接实例
|
||||
if (_plc != null)
|
||||
{
|
||||
_plc.Close();
|
||||
}
|
||||
|
||||
// 重新实例化 Plc 对象并配置超时
|
||||
_plc = new Plc(CpuType, IPAddress, Rack, Slot)
|
||||
{
|
||||
ReadTimeout = ReceiveTimeout,
|
||||
WriteTimeout = SendTimeout
|
||||
};
|
||||
|
||||
// 部分版本 S7.Net 的 OpenAsync 本身不接受 CancellationToken,我们通过 WaitAsync 实现超时
|
||||
await _plc.OpenAsync().WaitAsync(TimeSpan.FromMilliseconds(SendTimeout), ct);
|
||||
return _plc.IsConnected;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Close()
|
||||
{
|
||||
if (_plc != null && _plc.IsConnected)
|
||||
_plc.Close();
|
||||
}
|
||||
|
||||
public async Task WriteAsync(string address, object value, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("PLC未连接。");
|
||||
|
||||
await _plc.WriteAsync(address, value)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(SendTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<object> ReadAsync(string address, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("PLC未连接。");
|
||||
|
||||
return await _plc.ReadAsync(address)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReceiveTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<T> ReadAsync<T>(string address, CancellationToken ct = default)
|
||||
{
|
||||
var result = await ReadAsync(address, ct);
|
||||
return (T)result;
|
||||
}
|
||||
|
||||
public async Task<byte[]> ReadBytesAsync(DataType dataType, int db, int startByteAdr, int count, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("PLC未连接。");
|
||||
|
||||
return await _plc.ReadBytesAsync(dataType, db, startByteAdr, count)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReceiveTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WriteBytesAsync(DataType dataType, int db, int startByteAdr, byte[] value, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("PLC未连接。");
|
||||
|
||||
await _plc.WriteBytesAsync(dataType, db, startByteAdr, value)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(SendTimeout), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_plc?.Close();
|
||||
_commLock?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
156
DeviceCommand/Base/Serial_Port.cs
Normal file
156
DeviceCommand/Base/Serial_Port.cs
Normal file
@@ -0,0 +1,156 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public class Serial_Port : ISerialPort
|
||||
{
|
||||
public string PortName { get; set; } = "COM1";
|
||||
public int BaudRate { get; set; } = 9600;
|
||||
public int DataBits { get; set; } = 8;
|
||||
public StopBits StopBits { get; set; } = StopBits.One;
|
||||
public Parity Parity { get; set; } = Parity.None;
|
||||
public int ReadTimeout { get; set; } = 3000;
|
||||
public int WriteTimeout { get; set; } = 3000;
|
||||
|
||||
private SerialPort _serialPort;
|
||||
public bool IsConnected => _serialPort?.IsOpen ?? false;
|
||||
protected readonly SemaphoreSlim commLock = new(1, 1);
|
||||
|
||||
public Serial_Port()
|
||||
{
|
||||
_serialPort = new SerialPort();
|
||||
}
|
||||
|
||||
public void ConfigureDevice(string portName, int baudRate, int dataBits = 8, StopBits stopBits = StopBits.One, Parity parity = Parity.None, int readTimeout = 3000, int writeTimeout = 3000)
|
||||
{
|
||||
PortName = portName;
|
||||
BaudRate = baudRate;
|
||||
DataBits = dataBits;
|
||||
StopBits = stopBits;
|
||||
Parity = parity;
|
||||
ReadTimeout = readTimeout;
|
||||
WriteTimeout = writeTimeout;
|
||||
}
|
||||
|
||||
public virtual async Task<bool> ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_serialPort.IsOpen) _serialPort.Close();
|
||||
|
||||
_serialPort.PortName = PortName;
|
||||
_serialPort.BaudRate = BaudRate;
|
||||
_serialPort.DataBits = DataBits;
|
||||
_serialPort.StopBits = StopBits;
|
||||
_serialPort.Parity = Parity;
|
||||
_serialPort.ReadTimeout = ReadTimeout;
|
||||
_serialPort.WriteTimeout = WriteTimeout;
|
||||
|
||||
_serialPort.Open();
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Close()
|
||||
{
|
||||
if (_serialPort.IsOpen) _serialPort.Close();
|
||||
}
|
||||
|
||||
// 内部无锁发送方法,供原子组合操作调用
|
||||
private async Task LoglessSendAsync(string data, CancellationToken ct)
|
||||
{
|
||||
if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。");
|
||||
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(data);
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (WriteTimeout > 0) cts.CancelAfter(WriteTimeout);
|
||||
|
||||
await _serialPort.BaseStream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
|
||||
}
|
||||
|
||||
public async Task SendAsync(string data, CancellationToken ct = default)
|
||||
{
|
||||
await commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await LoglessSendAsync(data, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// 内部无锁读取方法,利用 BaseStream 挂起线程,高性能不吃 CPU
|
||||
private async Task<string> LoglessReadAsync(string delimiter, CancellationToken ct)
|
||||
{
|
||||
if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。");
|
||||
|
||||
delimiter ??= "\n";
|
||||
var sb = new StringBuilder();
|
||||
byte[] buffer = new byte[1024];
|
||||
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (ReadTimeout > 0) cts.CancelAfter(ReadTimeout);
|
||||
|
||||
while (!cts.Token.IsCancellationRequested)
|
||||
{
|
||||
// 核心优化:利用流异步挂起,替代原先的 BytesToRead 循环延时
|
||||
int bytesRead = await _serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length, cts.Token);
|
||||
if (bytesRead == 0) continue;
|
||||
|
||||
sb.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
|
||||
|
||||
int index = sb.ToString().IndexOf(delimiter, StringComparison.Ordinal);
|
||||
if (index >= 0)
|
||||
{
|
||||
return sb.ToString(0, index).Trim();
|
||||
}
|
||||
}
|
||||
throw new TimeoutException("读取数据超时");
|
||||
}
|
||||
|
||||
public async Task<string> ReadAsync(string delimiter = "\n", CancellationToken ct = default)
|
||||
{
|
||||
await commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await LoglessReadAsync(delimiter, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// 核心优化:保证多线程环境下发送和等待回包是一个原子过程
|
||||
public async Task<string> WriteReadAsync(string command, string delimiter = "\n", CancellationToken ct = default)
|
||||
{
|
||||
await commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await LoglessSendAsync(command, ct);
|
||||
return await LoglessReadAsync(delimiter, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_serialPort?.Dispose();
|
||||
commLock?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
179
DeviceCommand/Base/TCP.cs
Normal file
179
DeviceCommand/Base/TCP.cs
Normal file
@@ -0,0 +1,179 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public class Tcp : ITcp
|
||||
{
|
||||
public string IPAddress { get; set; } = "127.0.0.1";
|
||||
public int Port { get; set; } = 502;
|
||||
public int SendTimeout { get; set; } = 3000;
|
||||
public int ReceiveTimeout { get; set; } = 3000;
|
||||
|
||||
private TcpClient _tcpClient;
|
||||
public bool IsConnected => _tcpClient?.Connected ?? false;
|
||||
protected readonly SemaphoreSlim _commLock = new(1, 1);
|
||||
|
||||
public Tcp()
|
||||
{
|
||||
_tcpClient = new TcpClient();
|
||||
}
|
||||
|
||||
public void ConfigureDevice(string ipAddress, int port, int sendTimeout = 3000, int receiveTimeout = 3000)
|
||||
{
|
||||
IPAddress = ipAddress;
|
||||
Port = port;
|
||||
SendTimeout = sendTimeout;
|
||||
ReceiveTimeout = receiveTimeout;
|
||||
}
|
||||
|
||||
public virtual async Task<bool> ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_tcpClient.Connected) return true;
|
||||
|
||||
// 修复:释放并彻底清空旧的连接实例,否则复用引发异常
|
||||
_tcpClient.Close();
|
||||
_tcpClient.Dispose();
|
||||
|
||||
_tcpClient = new TcpClient();
|
||||
await _tcpClient.ConnectAsync(IPAddress, Port, ct);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Close()
|
||||
{
|
||||
if (_tcpClient.Connected) _tcpClient.Close();
|
||||
}
|
||||
|
||||
private async Task LoglessSendAsync(byte[] buffer, CancellationToken ct)
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("TCP未连接。");
|
||||
|
||||
NetworkStream stream = _tcpClient.GetStream();
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (SendTimeout > 0) cts.CancelAfter(SendTimeout);
|
||||
|
||||
await stream.WriteAsync(buffer, 0, buffer.Length, cts.Token);
|
||||
}
|
||||
|
||||
public async Task SendAsync(byte[] buffer, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await LoglessSendAsync(buffer, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SendAsync(string str, CancellationToken ct = default)
|
||||
{
|
||||
await SendAsync(Encoding.UTF8.GetBytes(str), ct);
|
||||
}
|
||||
|
||||
public async Task<byte[]> ReadAsync(int length, CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("TCP未连接。");
|
||||
|
||||
NetworkStream stream = _tcpClient.GetStream();
|
||||
byte[] buffer = new byte[length];
|
||||
int offset = 0;
|
||||
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (ReceiveTimeout > 0) cts.CancelAfter(ReceiveTimeout);
|
||||
|
||||
while (offset < length)
|
||||
{
|
||||
int read = await stream.ReadAsync(buffer, offset, length - offset, cts.Token);
|
||||
if (read == 0) break;
|
||||
offset += read;
|
||||
}
|
||||
|
||||
return offset == 0 ? Array.Empty<byte>() : buffer[..offset];
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string> LoglessReadAsync(string delimiter, CancellationToken ct)
|
||||
{
|
||||
if (!IsConnected) throw new InvalidOperationException("TCP未连接。");
|
||||
|
||||
delimiter ??= "\n";
|
||||
var sb = new StringBuilder();
|
||||
byte[] buffer = new byte[1024];
|
||||
NetworkStream stream = _tcpClient.GetStream();
|
||||
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (ReceiveTimeout > 0) cts.CancelAfter(ReceiveTimeout);
|
||||
|
||||
while (!cts.Token.IsCancellationRequested)
|
||||
{
|
||||
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cts.Token);
|
||||
if (bytesRead == 0) throw new IOException("远程主机已关闭连接");
|
||||
|
||||
sb.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
|
||||
|
||||
int index = sb.ToString().IndexOf(delimiter, StringComparison.Ordinal);
|
||||
if (index >= 0)
|
||||
return sb.ToString(0, index).Trim();
|
||||
}
|
||||
|
||||
throw new TimeoutException("读取数据超时");
|
||||
}
|
||||
|
||||
public async Task<string> ReadAsync(string delimiter = "\n", CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
return await LoglessReadAsync(delimiter, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// 核心优化:确保发送与读取在同一组锁生命周期内
|
||||
public async Task<string> WriteReadAsync(string command, string delimiter = "\n", CancellationToken ct = default)
|
||||
{
|
||||
await _commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await LoglessSendAsync(Encoding.UTF8.GetBytes(command), ct);
|
||||
return await LoglessReadAsync(delimiter, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_tcpClient?.Dispose();
|
||||
_commLock?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user