Files
WMS/HHWMS.Web/Areas/Api/IWCSController.cs

290 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Concurrent;
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
{
/// <summary>
/// 提供给WCS调用接口
/// 调用方向 WCS --> WMS
/// </summary>
[Public]
[ActionDescription("HHWMS.WCSApi")]
[ApiController]
[Route("api/[controller]/[action]"), ApiExplorerSettings(GroupName = "User")]
public class IWCSController : ApiController
{
private readonly IUnitWork _unitWork;
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, PLCHelper plcHelper)
{
_unitWork = unitWork;
_mapper = mapper;
_cache = cache;
_plcHelper = plcHelper;
}
/// <summary>
/// 防抖处理装饰器
/// </summary>
private async Task<IActionResult> WithDebounce(string key, Func<Task<IActionResult>> action)
{
try
{
// 使用key作为请求标识
string requestKey = $"Debounce_{key}";
// 检查是否存在处理中的相同请求
if (_cache.TryGetValue(requestKey, out DateTime lastRequestTime))
{
var timeSinceLastRequest = DateTime.Now - lastRequestTime;
if (timeSinceLastRequest.TotalMilliseconds < DEBOUNCE_INTERVAL_MS)
{
var remainingSeconds = Math.Ceiling((DEBOUNCE_INTERVAL_MS - timeSinceLastRequest.TotalMilliseconds) / 1000);
return ApiResultError($"请求过于频繁,请等待{remainingSeconds}秒后重试");
}
}
// 添加或更新缓存(设置防抖间隔时间)
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMilliseconds(DEBOUNCE_INTERVAL_MS));
_cache.Set(requestKey, DateTime.Now, cacheEntryOptions);
try
{
// 执行实际的业务逻辑
return await action();
}
catch (Exception ex)
{
// 处理失败时移除缓存,允许重试
_cache.Remove(requestKey);
throw;
}
}
catch (Exception ex)
{
return ApiResultError($"处理请求时发生错误: {ex.Message}");
}
}
/// <summary>
/// 请求入库(带防抖)
/// </summary>
[HttpPost]
public Task<IActionResult> RequestIn(WcsRequest request)
{
if (request == null || string.IsNullOrEmpty(request.PalletNo))
{
return Task.FromResult<IActionResult>(ApiResultError("请求参数无效"));
}
return WithDebounce($"RequestIn_{request.PalletNo}", async () =>
{
await ProcessRequestIn(request);
return ApiResult(new { Message = "入库请求处理成功" });
});
}
/// <summary>
/// 处理入库请求的具体业务逻辑
/// </summary>
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); // 模拟异步处理
}
/// <summary>
/// 状态返回(带防抖)
/// </summary>
[HttpPost]
public Task<IActionResult> TaskStatusResult(WcsRequest request)
{
if (request == null || string.IsNullOrEmpty(request.PalletNo))
{
return Task.FromResult<IActionResult>(ApiResultError("请求参数无效"));
}
return WithDebounce($"TaskStatus_{request.PalletNo}", () => Task.FromResult<IActionResult>(ApiResult()));
}
/// <summary>
/// 请求空闲库位(带防抖)
/// </summary>
[HttpPost]
public Task<IActionResult> RequestLocation(WcsRequest request)
{
if (string.IsNullOrEmpty(request?.PalletNo))
{
return Task.FromResult<IActionResult>(ApiResultError("容器编码不能为空"));
}
return WithDebounce($"RequestLocation_{request.PalletNo}", () =>
{
var vm = Wtm.CreateVM<LocationVM>();
var code = vm.GetLocation(request);
if (code.Status)
{
UpdateLocationAndContainer(code.Data.LocationCode, request.PalletNo);
return Task.FromResult<IActionResult>(ApiResult(code.Data));
}
return Task.FromResult<IActionResult>(ApiResultError("没有符合条件的可用库位"));
});
}
private IActionResult UpdateLocationAndContainer(string locationCode, string palletNo)
{
var location = _unitWork.Find<Location>(x => x.Code == locationCode).FirstOrDefault();
location.ContainerCode = palletNo;
location.Status = LocationStatus.任务锁;
_unitWork.Update(location);
var container = _unitWork.Find<Container>(x => x.Code == palletNo).FirstOrDefault();
if (container != null)
{
container.LocationCode = location.Code;
_unitWork.Update(container);
}
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; }
}
}
}