57 lines
1.8 KiB
C#
57 lines
1.8 KiB
C#
using Cowain.Base.Models;
|
|
using Newtonsoft.Json;
|
|
using Plugin.Cowain.Driver.Abstractions;
|
|
using Plugin.Cowain.Driver.Attributes;
|
|
using Plugin.Cowain.Driver.Models;
|
|
using Plugin.Cowain.Driver.Models.Enum;
|
|
|
|
namespace Plugin.Cowain.Wcs.Actions;
|
|
|
|
[Action("Heart", "心跳反馈")]
|
|
public class HeartAction : IVariableAction
|
|
{
|
|
private class ParamData
|
|
{
|
|
/// <summary>
|
|
/// PLC名称
|
|
/// </summary>
|
|
public string PlcName { get; set; } = string.Empty;
|
|
/// <summary>
|
|
/// 反馈命令地址
|
|
/// </summary>
|
|
public string RetAddress { get; set; } = string.Empty;
|
|
|
|
}
|
|
|
|
private readonly IDeviceMonitor _deviceMonitor;
|
|
public HeartAction(IDeviceMonitor deviceMonitor)
|
|
{
|
|
_deviceMonitor = deviceMonitor;
|
|
}
|
|
|
|
public async Task<ResultModel> ExecuteAsync(VariableAction variableAction, CancellationToken cancellationToken)
|
|
{
|
|
var _param = JsonConvert.DeserializeObject<ParamData>(variableAction.Param);
|
|
if (_param == null)
|
|
{
|
|
return ResultModel.Error("参数解析失败");
|
|
}
|
|
var driver = _deviceMonitor.GetDriver(_param.PlcName);
|
|
if (!driver.IsSuccess)
|
|
{
|
|
return ResultModel.Error($"未找到名称为 {_param.PlcName} 的Driver");
|
|
}
|
|
var plc = driver.Data;
|
|
// 解析变量值为 short 类型
|
|
if (!short.TryParse(variableAction.Variable.Value, out short shortValue))
|
|
{
|
|
return ResultModel.Error($"无法将变量值 '{variableAction.Variable.Value}' 转换为 short 类型");
|
|
}
|
|
var writeRet = await plc.WriteAsync<short>(_param.RetAddress, DataTypeEnum.Int16, shortValue);
|
|
if (!writeRet.IsSuccess) return ResultModel.Error($"写变量失败:{_param.PlcName}->{_param.RetAddress}");
|
|
|
|
return ResultModel.Success();
|
|
|
|
}
|
|
}
|