From b0a6dcc03575841862a89e25d14cc5d74f5cd883 Mon Sep 17 00:00:00 2001 From: zhougf Date: Mon, 30 Dec 2024 19:49:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0HSL=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E5=B7=A5=E5=85=B7=E7=B1=BB=EF=BC=8C=E5=9C=A8?= =?UTF-8?q?IWCS=E5=86=99=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HHWMS.Web/Areas/Api/ApiController.cs | 4 +- HHWMS.Web/Areas/Api/IWCSController.cs | 128 ++++++++- HHWMS.Web/HHWMS.Web.csproj | 1 + HHWMS.Web/Program.cs | 2 +- HHWMS.Web/Support/PLC/IPlcDevice.cs | 34 +++ HHWMS.Web/Support/PLC/MitsubishiPlc.cs | 366 ++++++++++++++++++++++++ HHWMS.Web/Support/PLC/ModbusPlc.cs | 367 +++++++++++++++++++++++++ HHWMS.Web/Support/PLC/PlcFactory.cs | 33 +++ HHWMS.Web/Support/PLC/SiemensPlc.cs | 356 ++++++++++++++++++++++++ HHWMS.Web/Support/PLCHelper.cs | 94 +++++++ 10 files changed, 1381 insertions(+), 4 deletions(-) create mode 100644 HHWMS.Web/Support/PLC/IPlcDevice.cs create mode 100644 HHWMS.Web/Support/PLC/MitsubishiPlc.cs create mode 100644 HHWMS.Web/Support/PLC/ModbusPlc.cs create mode 100644 HHWMS.Web/Support/PLC/PlcFactory.cs create mode 100644 HHWMS.Web/Support/PLC/SiemensPlc.cs create mode 100644 HHWMS.Web/Support/PLCHelper.cs diff --git a/HHWMS.Web/Areas/Api/ApiController.cs b/HHWMS.Web/Areas/Api/ApiController.cs index ab9a85e..6deea44 100644 --- a/HHWMS.Web/Areas/Api/ApiController.cs +++ b/HHWMS.Web/Areas/Api/ApiController.cs @@ -6,12 +6,12 @@ namespace HHWMS.Web { public abstract class ApiController : BaseApiController { - protected JsonResult ApiResult(object data = null, string msg = "success") + protected JsonResult ApiResult(object data = null, string msg = "操作成功!") { return new JsonResult(new ApiJsonResult { Data = data, Success = true, Status = true, Msg = msg }); } - protected JsonResult ApiResultError(object data = null, string msg = "faield") + protected JsonResult ApiResultError(object data = null, string msg = "操作失败!") { return new JsonResult(new ApiJsonResult { Data = data, Success = false, Status = false, Msg = msg }); } diff --git a/HHWMS.Web/Areas/Api/IWCSController.cs b/HHWMS.Web/Areas/Api/IWCSController.cs index fd76db2..553ef85 100644 --- a/HHWMS.Web/Areas/Api/IWCSController.cs +++ b/HHWMS.Web/Areas/Api/IWCSController.cs @@ -4,10 +4,15 @@ using System.Linq; using System.Threading.Tasks; using AutoMapper; using HHWMS.Web.Models; +using HHWMS.Web.Support; +using HHWMS.Web.Support.PLC; +using HslCommunication; +using HslCommunication.Profinet.Siemens; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WalkingTec.Mvvm.Core; using Microsoft.Extensions.Caching.Memory; +using HslCommunication.Core; namespace HHWMS.Web { @@ -25,12 +30,14 @@ namespace HHWMS.Web private readonly IMapper _mapper; private readonly IMemoryCache _cache; private const int DEBOUNCE_INTERVAL_MS = 1000; // 防抖间隔1秒 + private readonly PLCHelper _plcHelper; - public IWCSController(IUnitWork unitWork, IMapper mapper, IMemoryCache cache) + public IWCSController(IUnitWork unitWork, IMapper mapper, IMemoryCache cache, PLCHelper plcHelper) { _unitWork = unitWork; _mapper = mapper; _cache = cache; + _plcHelper = plcHelper; } /// @@ -101,6 +108,14 @@ namespace HHWMS.Web private async Task ProcessRequestIn(WcsRequest request) { // TODO: 实现具体的入库处理逻辑 + var t = 0; + var plc = new SiemensS7Net( SiemensPLCS.S1200, "10.211.55.4" ); + var read = await plc.ReadInt32Async( "V2634" ); + if (read.IsSuccess) + { + t = read.Content; + } + var write = await plc.WriteAsync( "V2634", t + 1 ); await Task.Delay(1000); // 模拟异步处理 } @@ -159,5 +174,116 @@ namespace HHWMS.Web return ApiResult(new { LocationCode = location.Code }); } + /// + /// PLC通信测试接口 + /// + /// 通信参数 + [HttpPost] + public async Task CommunicateWithPLC(PlcCommunicationRequest request) + { + if (request == null) + { + return ApiResultError("请求参数不能为空"); + } + + try + { + // 连接PLC + if (!_plcHelper.Connect(PlcType.Siemens, request.IpAddress)) + { + return ApiResultError(msg:"PLC连接失败"); + } + + try + { + // 根据操作类型执行不同的读写操作 + switch (request.OperationType) + { + case "ReadInt32": + var value = _plcHelper.ReadInt32(request.Address); + return ApiResult(new { Value = value }); + + case "WriteInt16": + if (!short.TryParse(request.Value, out short shortValue)) + { + return ApiResultError(msg: "无效的数值"); + } + var writeResult = _plcHelper.WriteInt16(request.Address, shortValue); + return ApiResult(new { Success = writeResult }); + + case "ReadBool": + var boolValue = _plcHelper.ReadBool(request.Address); + return ApiResult(new { Value = boolValue }); + + case "WriteBool": + if (!bool.TryParse(request.Value, out bool boolWriteValue)) + { + return ApiResultError("无效的布尔值"); + } + var boolWriteResult = _plcHelper.WriteBool(request.Address, boolWriteValue); + return ApiResult(new { Success = boolWriteResult }); + + case "ReadString": + if (!ushort.TryParse(request.StringLength, out ushort length)) + { + return ApiResultError("无效的字符串长度"); + } + var stringValue = _plcHelper.ReadString(request.Address, length); + return ApiResult(new { Value = stringValue }); + + case "WriteString": + if (!ushort.TryParse(request.StringLength, out ushort writeLength)) + { + return ApiResultError("无效的字符串长度"); + } + var stringWriteResult = _plcHelper.WriteString(request.Address, request.Value, writeLength); + return ApiResult(new { Success = stringWriteResult }); + + default: + return ApiResultError("不支持的操作类型"); + } + } + finally + { + // 确保操作完成后断开连接 + _plcHelper.Disconnect(); + } + } + catch (Exception ex) + { + return ApiResultError($"PLC操作失败: {ex.Message}"); + } + } + + /// + /// PLC通信请求参数类 + /// + public class PlcCommunicationRequest + { + /// + /// PLC的IP地址 + /// + public string IpAddress { get; set; } + + /// + /// 操作类型(ReadInt16, WriteInt16, ReadBool, WriteBool, ReadString, WriteString) + /// + public string OperationType { get; set; } + + /// + /// PLC地址(例如"DB1.0") + /// + public string Address { get; set; } + + /// + /// 要写入的值(用于写操作) + /// + public string Value { get; set; } + + /// + /// 字符串长度(用于字符串操作) + /// + public string StringLength { get; set; } + } } } diff --git a/HHWMS.Web/HHWMS.Web.csproj b/HHWMS.Web/HHWMS.Web.csproj index 377d3ad..8b88b7a 100644 --- a/HHWMS.Web/HHWMS.Web.csproj +++ b/HHWMS.Web/HHWMS.Web.csproj @@ -22,6 +22,7 @@ + diff --git a/HHWMS.Web/Program.cs b/HHWMS.Web/Program.cs index ffda785..cd31ee5 100644 --- a/HHWMS.Web/Program.cs +++ b/HHWMS.Web/Program.cs @@ -63,7 +63,7 @@ builder.Services.AddSignalR() .AddMessagePackProtocol(); builder.Services.AddSingleton(); - +builder.Services.AddSingleton(); var app = builder.Build(); IOptionsMonitor config = app.Services.GetRequiredService>(); diff --git a/HHWMS.Web/Support/PLC/IPlcDevice.cs b/HHWMS.Web/Support/PLC/IPlcDevice.cs new file mode 100644 index 0000000..83a38b3 --- /dev/null +++ b/HHWMS.Web/Support/PLC/IPlcDevice.cs @@ -0,0 +1,34 @@ +using System; +using HslCommunication; + +namespace HHWMS.Web.Support.PLC +{ + public interface IPlcDevice : IDisposable + { + bool Connect(string ipAddress, byte rack = 0, byte slot = 1); + void Disconnect(); + bool IsConnected { get; } + + // 基本类型读写 + short ReadInt16(string address); + bool WriteInt16(string address, short value); + int ReadInt32(string address); + bool WriteInt32(string address, int value); + long ReadInt64(string address); + bool WriteInt64(string address, long value); + float ReadFloat(string address); + bool WriteFloat(string address, float value); + double ReadDouble(string address); + bool WriteDouble(string address, double value); + bool ReadBool(string address); + bool WriteBool(string address, bool value); + string ReadString(string address, ushort length); + bool WriteString(string address, string value, ushort length); + + // 批量读写 + short[] ReadInt16Array(string address, ushort length); + bool WriteInt16Array(string address, short[] values); + bool[] ReadBoolArray(string address, ushort length); + bool WriteBoolArray(string address, bool[] values); + } +} \ No newline at end of file diff --git a/HHWMS.Web/Support/PLC/MitsubishiPlc.cs b/HHWMS.Web/Support/PLC/MitsubishiPlc.cs new file mode 100644 index 0000000..391f65e --- /dev/null +++ b/HHWMS.Web/Support/PLC/MitsubishiPlc.cs @@ -0,0 +1,366 @@ +using System; +using HslCommunication; +using HslCommunication.Profinet.Melsec; +using Microsoft.Extensions.Logging; + +namespace HHWMS.Web.Support.PLC +{ + public class MitsubishiPlc : IPlcDevice + { + private readonly ILogger _logger; + private MelsecMcNet? _plc; + private bool _isConnected; + + public MitsubishiPlc(ILogger logger) + { + _logger = logger; + } + + public bool Connect(string ipAddress, byte rack = 0, byte slot = 1) + { + try + { + _plc = new MelsecMcNet(ipAddress, 6001) + { + ConnectTimeOut = 5000 // 连接超时时间 + }; + + OperateResult connect = _plc.ConnectServer(); + _isConnected = connect.IsSuccess; + + if (_isConnected) + { + _logger.LogInformation($"三菱PLC连接成功: {ipAddress}"); + } + else + { + _logger.LogError($"三菱PLC连接失败: {ipAddress}, 错误信息: {connect.Message}"); + } + + return _isConnected; + } + catch (Exception ex) + { + _logger.LogError($"三菱PLC连接异常: {ex.Message}"); + return false; + } + } + + public void Disconnect() + { + if (_isConnected && _plc != null) + { + _plc.ConnectClose(); + _isConnected = false; + _logger.LogInformation("三菱PLC连接已断开"); + } + } + + #region 基本类型读写 + public short ReadInt16(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt16(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int16成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int16失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt16(string address, short value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int16成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int16失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public int ReadInt32(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt32(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int32成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int32失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt32(string address, int value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int32成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int32失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public long ReadInt64(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt64(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int64成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int64失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt64(string address, long value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int64成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int64失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public float ReadFloat(string address) + { + CheckConnection(); + + var result = _plc!.ReadFloat(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Float成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Float失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteFloat(string address, float value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Float成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Float失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public double ReadDouble(string address) + { + CheckConnection(); + + var result = _plc!.ReadDouble(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Double成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Double失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteDouble(string address, double value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Double成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Double失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public bool ReadBool(string address) + { + CheckConnection(); + + var result = _plc!.ReadBool(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Bool成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Bool失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteBool(string address, bool value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Bool成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Bool失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public string ReadString(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadString(ConvertAddress(address), length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取String成功: 地址={address}, 长度={length}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取String失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteString(string address, string value, ushort length) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入String成功: 地址={address}, 长度={length}, 值={value}"); + return true; + } + + _logger.LogError($"写入String失败: 地址={address}, 长度={length}, 值={value}, 错误={result.Message}"); + return false; + } + #endregion + + #region 批量读写 + public short[] ReadInt16Array(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadInt16(ConvertAddress(address), length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int16数组成功: 地址={address}, 长度={length}"); + return result.Content; + } + + var error = $"读取Int16数组失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt16Array(string address, short[] values) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), values); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int16数组成功: 地址={address}, 长度={values.Length}"); + return true; + } + + _logger.LogError($"写入Int16数组失败: 地址={address}, 长度={values.Length}, 错误={result.Message}"); + return false; + } + + public bool[] ReadBoolArray(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadBool(ConvertAddress(address), length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Bool数组成功: 地址={address}, 长度={length}"); + return result.Content; + } + + var error = $"读取Bool数组失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteBoolArray(string address, bool[] values) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), values); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Bool数组成功: 地址={address}, 长度={values.Length}"); + return true; + } + + _logger.LogError($"写入Bool数组失败: 地址={address}, 长度={values.Length}, 错误={result.Message}"); + return false; + } + #endregion + + private void CheckConnection() + { + if (!_isConnected || _plc == null) + { + throw new InvalidOperationException("三菱PLC未连接"); + } + } + + private string ConvertAddress(string address) + { + // 三菱PLC地址转换逻辑 + // 例如:将"D100"保持不变,但可以在这里添加其他转换规则 + return address; + } + + public void Dispose() + { + Disconnect(); + _plc?.Dispose(); + GC.SuppressFinalize(this); + } + + public bool IsConnected => _isConnected; + } +} \ No newline at end of file diff --git a/HHWMS.Web/Support/PLC/ModbusPlc.cs b/HHWMS.Web/Support/PLC/ModbusPlc.cs new file mode 100644 index 0000000..6f7b608 --- /dev/null +++ b/HHWMS.Web/Support/PLC/ModbusPlc.cs @@ -0,0 +1,367 @@ +using System; +using HslCommunication; +using HslCommunication.ModBus; +using Microsoft.Extensions.Logging; + +namespace HHWMS.Web.Support.PLC +{ + public class ModbusPlc : IPlcDevice + { + private readonly ILogger _logger; + private ModbusTcpNet? _plc; + private bool _isConnected; + + public ModbusPlc(ILogger logger) + { + _logger = logger; + } + + public bool Connect(string ipAddress, byte rack = 0, byte slot = 1) + { + try + { + _plc = new ModbusTcpNet(ipAddress) + { + Station = 1, + ReceiveTimeOut = 5000 + }; + + OperateResult connect = _plc.ConnectServer(); + _isConnected = connect.IsSuccess; + + if (_isConnected) + { + _logger.LogInformation($"Modbus设备连接成功: {ipAddress}"); + } + else + { + _logger.LogError($"Modbus设备连接失败: {ipAddress}, 错误信息: {connect.Message}"); + } + + return _isConnected; + } + catch (Exception ex) + { + _logger.LogError($"Modbus设备连接异常: {ex.Message}"); + return false; + } + } + + public void Disconnect() + { + if (_isConnected && _plc != null) + { + _plc.ConnectClose(); + _isConnected = false; + _logger.LogInformation("Modbus设备连接已断开"); + } + } + + #region 基本类型读写 + public short ReadInt16(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt16(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int16成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int16失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt16(string address, short value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int16成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int16失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public int ReadInt32(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt32(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int32成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int32失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt32(string address, int value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int32成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int32失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public long ReadInt64(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt64(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int64成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int64失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt64(string address, long value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int64成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int64失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public float ReadFloat(string address) + { + CheckConnection(); + + var result = _plc!.ReadFloat(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Float成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Float失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteFloat(string address, float value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Float成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Float失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public double ReadDouble(string address) + { + CheckConnection(); + + var result = _plc!.ReadDouble(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Double成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Double失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteDouble(string address, double value) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Double成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Double失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public bool ReadBool(string address) + { + CheckConnection(); + + var result = _plc!.ReadCoil(ConvertAddress(address)); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Bool成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Bool失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteBool(string address, bool value) + { + CheckConnection(); + + var result = _plc!.WriteCoil(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Bool成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Bool失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public string ReadString(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadString(ConvertAddress(address), length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取String成功: 地址={address}, 长度={length}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取String失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteString(string address, string value, ushort length) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入String成功: 地址={address}, 长度={length}, 值={value}"); + return true; + } + + _logger.LogError($"写入String失败: 地址={address}, 长度={length}, 值={value}, 错误={result.Message}"); + return false; + } + #endregion + + #region 批量读写 + public short[] ReadInt16Array(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadInt16(ConvertAddress(address), length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int16数组成功: 地址={address}, 长度={length}"); + return result.Content; + } + + var error = $"读取Int16数组失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt16Array(string address, short[] values) + { + CheckConnection(); + + var result = _plc!.Write(ConvertAddress(address), values); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int16数组成功: 地址={address}, 长度={values.Length}"); + return true; + } + + _logger.LogError($"写入Int16数组失败: 地址={address}, 长度={values.Length}, 错误={result.Message}"); + return false; + } + + public bool[] ReadBoolArray(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadCoil(ConvertAddress(address), length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Bool数组成功: 地址={address}, 长度={length}"); + return result.Content; + } + + var error = $"读取Bool数组失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteBoolArray(string address, bool[] values) + { + CheckConnection(); + + var result = _plc!.WriteCoil(ConvertAddress(address), values); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Bool数组成功: 地址={address}, 长度={values.Length}"); + return true; + } + + _logger.LogError($"写入Bool数组失败: 地址={address}, 长度={values.Length}, 错误={result.Message}"); + return false; + } + #endregion + + private void CheckConnection() + { + if (!_isConnected || _plc == null) + { + throw new InvalidOperationException("Modbus设备未连接"); + } + } + + private string ConvertAddress(string address) + { + // Modbus地址转换逻辑 + // 例如:将"4X100"转换为"100" + return address.TrimStart('4', 'X'); + } + + public void Dispose() + { + Disconnect(); + _plc?.Dispose(); + GC.SuppressFinalize(this); + } + + public bool IsConnected => _isConnected; + } +} \ No newline at end of file diff --git a/HHWMS.Web/Support/PLC/PlcFactory.cs b/HHWMS.Web/Support/PLC/PlcFactory.cs new file mode 100644 index 0000000..2c6f403 --- /dev/null +++ b/HHWMS.Web/Support/PLC/PlcFactory.cs @@ -0,0 +1,33 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace HHWMS.Web.Support.PLC +{ + public enum PlcType + { + Siemens, + Modbus, + Mitsubishi + } + + public class PlcFactory + { + private readonly ILoggerFactory _loggerFactory; + + public PlcFactory(ILoggerFactory loggerFactory) + { + _loggerFactory = loggerFactory; + } + + public IPlcDevice CreatePlc(PlcType plcType) + { + return plcType switch + { + PlcType.Siemens => new SiemensPlc(_loggerFactory.CreateLogger()), + PlcType.Modbus => new ModbusPlc(_loggerFactory.CreateLogger()), + PlcType.Mitsubishi => new MitsubishiPlc(_loggerFactory.CreateLogger()), + _ => throw new ArgumentException("不支持的PLC类型", nameof(plcType)) + }; + } + } +} \ No newline at end of file diff --git a/HHWMS.Web/Support/PLC/SiemensPlc.cs b/HHWMS.Web/Support/PLC/SiemensPlc.cs new file mode 100644 index 0000000..fb30401 --- /dev/null +++ b/HHWMS.Web/Support/PLC/SiemensPlc.cs @@ -0,0 +1,356 @@ +using System; +using HslCommunication; +using HslCommunication.Profinet.Siemens; +using Microsoft.Extensions.Logging; + +namespace HHWMS.Web.Support.PLC +{ + public class SiemensPlc : IPlcDevice + { + private readonly ILogger _logger; + private SiemensS7Net? _plc; + private bool _isConnected; + + public SiemensPlc(ILogger logger) + { + _logger = logger; + } + + public bool Connect(string ipAddress, byte rack = 0, byte slot = 1) + { + try + { + _plc = new SiemensS7Net(SiemensPLCS.S1200, ipAddress) + { + Rack = rack, + Slot = slot + }; + + OperateResult connect = _plc.ConnectServer(); + _isConnected = connect.IsSuccess; + + if (_isConnected) + { + _logger.LogInformation($"西门子PLC连接成功: {ipAddress}"); + } + else + { + _logger.LogError($"西门子PLC连接失败: {ipAddress}, 错误信息: {connect.Message}"); + } + + return _isConnected; + } + catch (Exception ex) + { + _logger.LogError($"西门子PLC连接异常: {ex.Message}"); + return false; + } + } + + public void Disconnect() + { + if (_isConnected && _plc != null) + { + _plc.ConnectClose(); + _isConnected = false; + _logger.LogInformation("西门子PLC连接已断开"); + } + } + + public short ReadInt16(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt16(address); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int16成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int16失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt16(string address, short value) + { + CheckConnection(); + + var result = _plc!.Write(address, value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int16成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int16失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public bool ReadBool(string address) + { + CheckConnection(); + + var result = _plc!.ReadBool(address); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Bool成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Bool失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteBool(string address, bool value) + { + CheckConnection(); + + var result = _plc!.Write(address, value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Bool成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Bool失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public string ReadString(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadString(address, length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取String成功: 地址={address}, 长度={length}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取String失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteString(string address, string value, ushort length) + { + CheckConnection(); + + var result = _plc!.Write(address, value, length); + if (result.IsSuccess) + { + _logger.LogDebug($"写入String成功: 地址={address}, 长度={length}, 值={value}"); + return true; + } + + _logger.LogError($"写入String失败: 地址={address}, 长度={length}, 值={value}, 错误={result.Message}"); + return false; + } + + public int ReadInt32(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt32(address); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int32成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int32失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt32(string address, int value) + { + CheckConnection(); + + var result = _plc!.Write(address, value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int32成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int32失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public long ReadInt64(string address) + { + CheckConnection(); + + var result = _plc!.ReadInt64(address); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int64成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Int64失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt64(string address, long value) + { + CheckConnection(); + + var result = _plc!.Write(address, value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int64成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Int64失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public float ReadFloat(string address) + { + CheckConnection(); + + var result = _plc!.ReadFloat(address); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Float成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Float失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteFloat(string address, float value) + { + CheckConnection(); + + var result = _plc!.Write(address, value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Float成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Float失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public double ReadDouble(string address) + { + CheckConnection(); + + var result = _plc!.ReadDouble(address); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Double成功: 地址={address}, 值={result.Content}"); + return result.Content; + } + + var error = $"读取Double失败: 地址={address}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteDouble(string address, double value) + { + CheckConnection(); + + var result = _plc!.Write(address, value); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Double成功: 地址={address}, 值={value}"); + return true; + } + + _logger.LogError($"写入Double失败: 地址={address}, 值={value}, 错误={result.Message}"); + return false; + } + + public short[] ReadInt16Array(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadInt16(address, length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Int16数组成功: 地址={address}, 长度={length}"); + return result.Content; + } + + var error = $"读取Int16数组失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteInt16Array(string address, short[] values) + { + CheckConnection(); + + var result = _plc!.Write(address, values); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Int16数组成功: 地址={address}, 长度={values.Length}"); + return true; + } + + _logger.LogError($"写入Int16数组失败: 地址={address}, 长度={values.Length}, 错误={result.Message}"); + return false; + } + + public bool[] ReadBoolArray(string address, ushort length) + { + CheckConnection(); + + var result = _plc!.ReadBool(address, length); + if (result.IsSuccess) + { + _logger.LogDebug($"读取Bool数组成功: 地址={address}, 长度={length}"); + return result.Content; + } + + var error = $"读取Bool数组失败: 地址={address}, 长度={length}, 错误={result.Message}"; + _logger.LogError(error); + throw new InvalidOperationException(error); + } + + public bool WriteBoolArray(string address, bool[] values) + { + CheckConnection(); + + var result = _plc!.Write(address, values); + if (result.IsSuccess) + { + _logger.LogDebug($"写入Bool数组成功: 地址={address}, 长度={values.Length}"); + return true; + } + + _logger.LogError($"写入Bool数组失败: 地址={address}, 长度={values.Length}, 错误={result.Message}"); + return false; + } + + private void CheckConnection() + { + if (!_isConnected || _plc == null) + { + throw new InvalidOperationException("PLC未连接"); + } + } + + public void Dispose() + { + Disconnect(); + _plc?.Dispose(); + GC.SuppressFinalize(this); + } + + public bool IsConnected => _isConnected; + } +} \ No newline at end of file diff --git a/HHWMS.Web/Support/PLCHelper.cs b/HHWMS.Web/Support/PLCHelper.cs new file mode 100644 index 0000000..5ce89eb --- /dev/null +++ b/HHWMS.Web/Support/PLCHelper.cs @@ -0,0 +1,94 @@ +using System; +using HHWMS.Web.Support.PLC; +using Microsoft.Extensions.Logging; + +namespace HHWMS.Web.Support +{ + public class PLCHelper : IDisposable + { + private readonly PlcFactory _plcFactory; + private IPlcDevice? _currentPlc; + + public PLCHelper(ILoggerFactory loggerFactory) + { + _plcFactory = new PlcFactory(loggerFactory); + } + + public bool Connect(PlcType plcType, string ipAddress, byte rack = 0, byte slot = 1) + { + _currentPlc?.Dispose(); + _currentPlc = _plcFactory.CreatePlc(plcType); + return _currentPlc.Connect(ipAddress, rack, slot); + } + + #region 基本类型读写 + public short ReadInt16(string address) => + _currentPlc?.ReadInt16(address) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteInt16(string address, short value) => + _currentPlc?.WriteInt16(address, value) ?? throw new InvalidOperationException("PLC未连接"); + + public int ReadInt32(string address) => + _currentPlc?.ReadInt32(address) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteInt32(string address, int value) => + _currentPlc?.WriteInt32(address, value) ?? throw new InvalidOperationException("PLC未连接"); + + public long ReadInt64(string address) => + _currentPlc?.ReadInt64(address) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteInt64(string address, long value) => + _currentPlc?.WriteInt64(address, value) ?? throw new InvalidOperationException("PLC未连接"); + + public float ReadFloat(string address) => + _currentPlc?.ReadFloat(address) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteFloat(string address, float value) => + _currentPlc?.WriteFloat(address, value) ?? throw new InvalidOperationException("PLC未连接"); + + public double ReadDouble(string address) => + _currentPlc?.ReadDouble(address) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteDouble(string address, double value) => + _currentPlc?.WriteDouble(address, value) ?? throw new InvalidOperationException("PLC未连接"); + + public bool ReadBool(string address) => + _currentPlc?.ReadBool(address) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteBool(string address, bool value) => + _currentPlc?.WriteBool(address, value) ?? throw new InvalidOperationException("PLC未连接"); + + public string ReadString(string address, ushort length) => + _currentPlc?.ReadString(address, length) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteString(string address, string value, ushort length) => + _currentPlc?.WriteString(address, value, length) ?? throw new InvalidOperationException("PLC未连接"); + #endregion + + #region 批量读写 + public short[] ReadInt16Array(string address, ushort length) => + _currentPlc?.ReadInt16Array(address, length) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteInt16Array(string address, short[] values) => + _currentPlc?.WriteInt16Array(address, values) ?? throw new InvalidOperationException("PLC未连接"); + + public bool[] ReadBoolArray(string address, ushort length) => + _currentPlc?.ReadBoolArray(address, length) ?? throw new InvalidOperationException("PLC未连接"); + + public bool WriteBoolArray(string address, bool[] values) => + _currentPlc?.WriteBoolArray(address, values) ?? throw new InvalidOperationException("PLC未连接"); + #endregion + + public void Disconnect() + { + _currentPlc?.Disconnect(); + } + + public void Dispose() + { + _currentPlc?.Dispose(); + } + + public bool IsConnected => _currentPlc?.IsConnected ?? false; + } +} \ No newline at end of file