添加HSL,并创建工具类,在IWCS写测试

This commit is contained in:
Mac mini git server 2024-12-30 19:49:29 +08:00
parent 2c178b1810
commit b0a6dcc035
10 changed files with 1381 additions and 4 deletions

View File

@ -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<object> { 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<object> { Data = data, Success = false, Status = false, Msg = msg });
}

View File

@ -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;
}
/// <summary>
@ -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 });
}
/// <summary>
/// PLC通信测试接口
/// </summary>
/// <param name="request">通信参数</param>
[HttpPost]
public async Task<IActionResult> 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}");
}
}
/// <summary>
/// PLC通信请求参数类
/// </summary>
public class PlcCommunicationRequest
{
/// <summary>
/// PLC的IP地址
/// </summary>
public string IpAddress { get; set; }
/// <summary>
/// 操作类型(ReadInt16, WriteInt16, ReadBool, WriteBool, ReadString, WriteString)
/// </summary>
public string OperationType { get; set; }
/// <summary>
/// PLC地址(例如"DB1.0")
/// </summary>
public string Address { get; set; }
/// <summary>
/// 要写入的值(用于写操作)
/// </summary>
public string Value { get; set; }
/// <summary>
/// 字符串长度(用于字符串操作)
/// </summary>
public string StringLength { get; set; }
}
}
}

View File

@ -22,6 +22,7 @@
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
<PackageReference Include="EfCore.SchemaCompare" Version="6.0.0" />
<PackageReference Include="HslCommunication" Version="7.0.1" />
<PackageReference Include="IoTClient" Version="1.0.40" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="6.0.27" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.11">

View File

@ -63,7 +63,7 @@ builder.Services.AddSignalR()
.AddMessagePackProtocol();
builder.Services.AddSingleton<StockTicker>();
builder.Services.AddSingleton<PLCHelper>();
var app = builder.Build();
IOptionsMonitor<Configs> config = app.Services.GetRequiredService<IOptionsMonitor<Configs>>();

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<SiemensPlc>()),
PlcType.Modbus => new ModbusPlc(_loggerFactory.CreateLogger<ModbusPlc>()),
PlcType.Mitsubishi => new MitsubishiPlc(_loggerFactory.CreateLogger<MitsubishiPlc>()),
_ => throw new ArgumentException("不支持的PLC类型", nameof(plcType))
};
}
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}