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 { /// /// 提供给WCS调用接口 /// 调用方向 WCS --> WMS /// [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; } /// /// 防抖处理装饰器 /// private async Task WithDebounce(string key, Func> 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}"); } } /// /// 请求入库(带防抖) /// [HttpPost] public Task RequestIn(WcsRequest request) { if (request == null || string.IsNullOrEmpty(request.PalletNo)) { return Task.FromResult(ApiResultError("请求参数无效")); } return WithDebounce($"RequestIn_{request.PalletNo}", async () => { await ProcessRequestIn(request); return ApiResult(new { Message = "入库请求处理成功" }); }); } /// /// 处理入库请求的具体业务逻辑 /// 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); // 模拟异步处理 } /// /// 状态返回(带防抖) /// [HttpPost] public Task TaskStatusResult(WcsRequest request) { if (request == null || string.IsNullOrEmpty(request.PalletNo)) { return Task.FromResult(ApiResultError("请求参数无效")); } return WithDebounce($"TaskStatus_{request.PalletNo}", () => Task.FromResult(ApiResult())); } /// /// 请求空闲库位(带防抖) /// [HttpPost] public Task RequestLocation(WcsRequest request) { if (string.IsNullOrEmpty(request?.PalletNo)) { return Task.FromResult(ApiResultError("容器编码不能为空")); } return WithDebounce($"RequestLocation_{request.PalletNo}", () => { var vm = Wtm.CreateVM(); var code = vm.GetLocation(request); if (code.Status) { UpdateLocationAndContainer(code.Data.LocationCode, request.PalletNo); return Task.FromResult(ApiResult(code.Data)); } return Task.FromResult(ApiResultError("没有符合条件的可用库位")); }); } private IActionResult UpdateLocationAndContainer(string locationCode, string palletNo) { var location = _unitWork.Find(x => x.Code == locationCode).FirstOrDefault(); location.ContainerCode = palletNo; location.Status = LocationStatus.任务锁; _unitWork.Update(location); var container = _unitWork.Find(x => x.Code == palletNo).FirstOrDefault(); if (container != null) { container.LocationCode = location.Code; _unitWork.Update(container); } 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; } } } }