优化了示例工程

This commit is contained in:
fengjiayi
2024-09-28 23:55:19 +08:00
parent 51bdbab4d1
commit 10e5d172c6
56 changed files with 9920 additions and 455 deletions

View File

@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Data
{
public class MyData
{
public int[] Values { get; set; } = new int[] { 1, 1, 4, 5, 1, 4, 1, 9, 9, 9 };
public int Count { get; set; }
public string Tips { get; set; }
}
}

View File

@@ -1,48 +0,0 @@
using Net461DllTest.Data;
using Net461DllTest.Signal;
using Serein.Library.Attributes;
using Serein.Library.NodeFlow.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Device
{
public class PlcDevice : ChannelFlowTrigger<OrderSignal>
{
[AutoInjection]
public MyData MyData { get; set; }
public PlcDevice()
{
PlcId = 114514 + 10000000 * new Random().Next(1, 9);
}
public int PlcId { get; set; }
public void InitDevice(string ip, int port, string tips)
{
Write($"模拟设备初始化 :{Environment.NewLine}" +
$" ip :{ip}{Environment.NewLine}" +
$"port:{port}{Environment.NewLine}" +
$"tips:{tips}{Environment.NewLine}");
}
public void Write<T>(T value)
{
Console.WriteLine($"{value}");
}
public void Read<T>()
{
Console.WriteLine($"读取数据:... ");
}
public void Disconnect()
{
Console.WriteLine($"断开连接...");
}
}
}

View File

@@ -0,0 +1,18 @@
using Net461DllTest.LogicControl;
using Serein.Library.Attributes;
using Serein.Library.NodeFlow.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Device
{
[AutoRegister]
public class PrakingDevice : ChannelFlowTrigger<ParkingCommand>
{
}
}

View File

@@ -0,0 +1,70 @@
using IoTClient.Clients.PLC;
using Net461DllTest.Enums;
using Net461DllTest.Signal;
using Net461DllTest.Utils;
using Serein.Library.NodeFlow.Tool;
using System;
namespace Net461DllTest.Device
{
/// <summary>
/// 官方文档如果没有主动Open则会每次读写操作的时候自动打开自动和关闭连接这样会使读写效率大大减低。所以建议手动Open和Close。
/// </summary>
public class SiemensPlcDevice : ChannelFlowTrigger<OrderSignal>
{
public SiemensClient Client { get; set; }
public IoTClient.Common.Enums.SiemensVersion Version { get; set; }
public string IP { get; set; }
public int Port { get; set; }
public PlcState State { get; set; } = PlcState.PowerOff;
public void Init(IoTClient.Common.Enums.SiemensVersion version,string ip, int port)
{
Client = new SiemensClient(version, ip, port);
Version = version;
IP = ip;
Port = port;
}
public void ResetDevice()
{
Client?.Close();
Client = null;
}
public void Write(PlcVarInfo plcValue, object value)
{
try
{
Client.WriteToPlcValue(plcValue, value);
}
catch (Exception ex)
{
Console.WriteLine($"写入出错:{this}{plcValue}。{ex.Message}");
throw;
}
}
public object Read(PlcVarInfo plcValue)
{
try
{
return Client.ReadToPlcValue(plcValue);
}
catch (Exception ex)
{
Console.WriteLine($"读取出错:{this}{plcValue}。{ex.Message}");
throw;
}
}
public override string ToString()
{
return $"西门子Plc[{this.Version}-{this.IP}:{this.Port}]";
}
}
}

View File

@@ -0,0 +1,19 @@
using Net461DllTest.View;
using Serein.Library.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Signal
{
public enum FromValue
{
None,
[BindValue(typeof(FromWorkBenchView))]
FromWorkBenchView,
[BindValue(typeof(TestFormView))]
TestFormView,
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Enums
{
public enum PlcState
{
/// <summary>
/// 关机
/// </summary>
PowerOff,
/// <summary>
/// 正在运行
/// </summary>
Runing,
/// <summary>
/// 发生异常
/// </summary>
Error,
/// <summary>
/// 维护中
/// </summary>
Maintenance,
}
}

View File

@@ -1,131 +0,0 @@
using Net461DllTest.Data;
using Net461DllTest.Device;
using Net461DllTest.Signal;
using Net461DllTest.Web;
using Serein.Library.Api;
using Serein.Library.Attributes;
using Serein.Library.Enums;
using Serein.Library.Ex;
using Serein.Library.Framework.NodeFlow;
using Serein.Library.NodeFlow.Tool;
using Serein.Library.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Flow
{
[DynamicFlow]
public class LogicControl
{
[AutoInjection]
public PlcDevice MyPlc { get; set; }
#region 退
[NodeAction(NodeType.Init)] // Init 初始化事件,流程启动时执行
public void Init(IDynamicContext context)
{
context.Env.IOC.Register<PlcDevice>(); // 注册Plc设备
context.Env.IOC.Register<MyData>(); // 注册数据类
context.Env.IOC.Register<WebServer>(); // 注册Web服务
// // 注册控制器
context.Env.IOC.Run<IRouter>(router => {
router.RegisterController(typeof(ApiController));
});
}
[NodeAction(NodeType.Loading)] // Loading 初始化完成已注入依赖项,可以开始逻辑上的操作
public void Loading(IDynamicContext context)
{
context.Env.IOC.Run<WebServer>((web) =>
{
web.Start("http://*:8089/"); // 开启 Web 服务
});
}
[NodeAction(NodeType.Exit)] // 流程结束时自动执行
public void Exit(IDynamicContext context)
{
MyPlc.Disconnect();
MyPlc.CancelAllTasks();
}
#endregion
#region
[NodeAction(NodeType.Flipflop, "等待信号触发", ReturnType = typeof(int))]
public async Task<IFlipflopContext> WaitTask(OrderSignal order = OrderSignal.Command_1)
{
try
{
TriggerData triggerData = await MyPlc.CreateChannelWithTimeoutAsync(order, TimeSpan.FromMinutes(5), 0);
if (triggerData.Type == TriggerType.Overtime)
{
throw new FlipflopException("超时取消");
}
//int.TryParse(triggerData.Value.ToString(),out int result);
MyPlc.MyData.Count += (int)triggerData.Value;
return new FlipflopContext(FlipflopStateType.Succeed, MyPlc.MyData.Count);
}
catch (FlipflopException)
{
throw;
}
catch (Exception)
{
return new FlipflopContext(FlipflopStateType.Error);
}
}
#endregion
#region
[NodeAction(NodeType.Action, "初始化")]
public PlcDevice PlcInit(string ip = "192.168.1.1",
int port = 6688,
string tips = "测试")
{
MyPlc.InitDevice(ip, port, tips);
return MyPlc;
}
[NodeAction(NodeType.Action, "自增")]
public PlcDevice (int number = 1)
{
MyPlc.MyData.Count += number;
return MyPlc;
}
[NodeAction(NodeType.Action, "重置计数")]
public void ()
{
MyPlc.MyData.Count = 0;
}
[NodeAction(NodeType.Action, "触发信号")]
public void 1(int data)
{
MyPlc.Write($"{MyPlc.PlcId.ToString("00000")} - 信号源[光电1] - 模拟写入 : {data}{Environment.NewLine}");
}
//[NodeAction(NodeType.Action, "触发光电2")]
//public void 光电2信号触发(int data)
//{
// MyPlc.Write($"{MyPlc.PlcId.ToString("00000")} - 信号源[光电2] - 模拟写入 : {data}{Environment.NewLine}");
//}
//[NodeAction(NodeType.Action, "触发光电3")]
//public void 光电3信号触发(int data)
//{
// MyPlc.Write($"{MyPlc.PlcId.ToString("00000")} - 信号源[光电3] - 模拟写入 : {data}{Environment.NewLine}");
//}
#endregion
}
}

View File

@@ -0,0 +1,91 @@
using Net461DllTest.Device;
using Net461DllTest.Signal;
using Net461DllTest.ViewModel;
using Serein.Library.Api;
using Serein.Library.Attributes;
using Serein.Library.Enums;
using Serein.Library.Ex;
using Serein.Library.Framework.NodeFlow;
using Serein.Library.NodeFlow.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.LogicControl
{
public enum ParkingCommand
{
GetPparkingSpace,
}
[DynamicFlow]
public class ParkingLogicControl
{
[AutoInjection]
public PrakingDevice PrakingDevice { get; set; }
[NodeAction(NodeType.Init)]
public void Init(IDynamicContext context)
{
context.Env.IOC.Register<PrakingDevice>();
}
[NodeAction(NodeType.Flipflop, "等待车位调取命令",ReturnType=typeof(string))]
public async Task<IFlipflopContext> GetPparkingSpace(ParkingCommand parkingCommand = ParkingCommand.GetPparkingSpace)
{
try
{
TriggerData triggerData = await PrakingDevice.CreateChannelWithTimeoutAsync(parkingCommand, TimeSpan.FromMinutes(5), 0);
if (triggerData.Type == TriggerType.Overtime)
{
throw new FlipflopException("超时取消");
}
if(triggerData.Value is string spaceNum)
{
await Console.Out.WriteLineAsync("收到命令:调取车位,车位号"+ spaceNum);
return new FlipflopContext(FlipflopStateType.Succeed, spaceNum);
}
else
{
throw new FlipflopException("并非车位号");
}
}
catch (FlipflopException)
{
throw;
}
catch (Exception)
{
return new FlipflopContext(FlipflopStateType.Error);
}
}
[NodeAction(NodeType.Action, "手动触发模拟调取车位")]
public void Storage(string spaceNum = "101")
{
if (PrakingDevice.TriggerSignal(ParkingCommand.GetPparkingSpace, spaceNum))
{
Console.WriteLine("发送命令成功:调取车位" + spaceNum);
}
else
{
Console.WriteLine("发送命令失败:调取车位" + spaceNum);
}
}
}
}

View File

@@ -0,0 +1,191 @@
using IoTClient.Clients.PLC;
using IoTClient.Common.Enums;
using Net461DllTest.Device;
using Net461DllTest.Enums;
using Net461DllTest.Signal;
using Net461DllTest.Web;
using Serein.Library.Api;
using Serein.Library.Attributes;
using Serein.Library.Enums;
using Serein.Library.Ex;
using Serein.Library.Framework.NodeFlow;
using Serein.Library.NodeFlow.Tool;
using Serein.Library.Utils;
using Serein.Library.Web;
using System;
using System.ComponentModel;
using System.Reflection;
using System.Threading.Tasks;
namespace Net461DllTest.LogicControl
{
[DynamicFlow]
public class PlcLogicControl
{
[AutoInjection]
public SiemensPlcDevice MyPlc { get; set; }
#region 退
[NodeAction(NodeType.Init)] // Init 初始化事件,流程启动时执行
public void Init(IDynamicContext context)
{
context.Env.IOC.Register<SiemensPlcDevice>(); // 注册Plc设备
context.Env.IOC.Register<WebServer>(); // 注册Web服务
// // 注册控制器
context.Env.IOC.Run<IRouter>(router => {
router.RegisterController(typeof(ApiController));
});
}
[NodeAction(NodeType.Loading)] // Loading 初始化完成已注入依赖项,可以开始逻辑上的操作
public void Loading(IDynamicContext context)
{
context.Env.IOC.Run<WebServer>((web) =>
{
web.Start("http://*:8089/"); // 开启 Web 服务
});
}
[NodeAction(NodeType.Exit)] // 流程结束时自动执行
public void Exit(IDynamicContext context)
{
MyPlc.ResetDevice();
MyPlc.CancelAllTasks();
}
#endregion
#region
[NodeAction(NodeType.Flipflop, "等待信号触发", ReturnType = typeof(int))]
public async Task<IFlipflopContext> WaitTask(OrderSignal order = OrderSignal.Command_1)
{
try
{
TriggerData triggerData = await MyPlc.CreateChannelWithTimeoutAsync(order, TimeSpan.FromMinutes(5), 0);
if (triggerData.Type == TriggerType.Overtime)
{
throw new FlipflopException("超时取消");
}
//int.TryParse(triggerData.Value.ToString(),out int result);
return new FlipflopContext(FlipflopStateType.Succeed, triggerData.Value);
}
catch (FlipflopException)
{
throw;
}
catch (Exception)
{
return new FlipflopContext(FlipflopStateType.Error);
}
}
#endregion
#region
[NodeAction(NodeType.Action, "初始化")]
public SiemensPlcDevice PlcInit(SiemensVersion version = SiemensVersion.None,
string ip = "192.168.10.100",
int port = 102)
{
if (MyPlc.Client is null)
{
try
{
MyPlc.Init(version, ip, port);
Console.WriteLine($"西门子PLC初始化成功[{version},{ip}:{port}]");
}
catch (Exception ex)
{
Console.WriteLine($"西门子PLC[{version},{ip}:{port}]初始化异常:{ex.Message}");
}
}
else
{
Console.WriteLine( $"西门子PLC已经初始化[{version},{ip}:{port}]");
}
return MyPlc;
}
[NodeAction(NodeType.Action, "设置PLC状态")]
public SiemensPlcDevice SetState(PlcState state = PlcState.PowerOff)
{
if(MyPlc.Client != null)
{
var oldState = MyPlc.State;
MyPlc.State = state;
Console.WriteLine($"PLC状态从[{oldState}]转为[{state}]");
return MyPlc;
}
else
{
Console.WriteLine($"PLC尚未初始化");
return MyPlc;
}
}
[NodeAction(NodeType.Action, "PLC获取变量")]
public object ReadVar([BindConvertor(typeof(PlcVarEnum), typeof(PlcVarConvertor))] PlcVarInfo varInfo)
{
var result = MyPlc.Read(varInfo);
Console.WriteLine($"获取变量成功:({varInfo})\t result = {result}");
return result;
}
[NodeAction(NodeType.Action, "PLC写入变量")]
public SiemensPlcDevice WriteVar2(object value, [BindConvertor(typeof(PlcVarEnum), typeof(PlcVarConvertor))] PlcVarInfo varInfo)
{
if (MyPlc.State == PlcState.Runing)
{
if (!varInfo.IsProtected)
{
MyPlc.Write(varInfo, value);
Console.WriteLine($"PLC变量{varInfo}写入数据:{value}");
}
else
{
Console.WriteLine($"PLC变量{varInfo}当前禁止写入");
}
}
else
{
Console.WriteLine($"PLC处于非预期状态{MyPlc.State}");
}
return MyPlc;
}
/// <summary>
/// 转换器,用于将枚举转为自定义特性中的数据
/// </summary>
public class PlcVarConvertor: IEnumConvertor<PlcVarEnum, PlcVarInfo>
{
public PlcVarInfo Convertor(PlcVarEnum plcVarValue)
{
if (plcVarValue == PlcVarEnum.None)
{
throw new Exception("非预期枚举值");
}
var plcValue = EnumHelper.GetBoundValue<PlcVarEnum, PlcValueAttribute, PlcVarInfo>(plcVarValue, attr => attr.PlcInfo)
?? throw new Exception($"获取变量异常:{plcVarValue}没有标记PlcValueAttribute");
if (string.IsNullOrEmpty(plcValue.VarAddress))
{
throw new Exception($"获取变量异常:{plcVarValue},变量地址为空");
}
return plcValue;
}
}
#endregion
}
}

View File

@@ -1,6 +1,4 @@
using Net461DllTest.Data;
using Net461DllTest.Device;
using Net461DllTest.View;
using Net461DllTest.Signal;
using Net461DllTest.ViewModel;
using Serein.Library.Api;
using Serein.Library.Attributes;
@@ -9,10 +7,9 @@ using Serein.Library.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace Net461DllTest.Flow
namespace Net461DllTest.LogicControl
{
public class ViewManagement
@@ -44,14 +41,7 @@ namespace Net461DllTest.Flow
}
public enum FromId
{
None,
[BindValue(typeof(FromWorkBenchView))]
FromWorkBenchView,
[BindValue(typeof(TeseFormView))]
TeseFormView,
}
[DynamicFlow]
public class ViewLogicControl
@@ -68,9 +58,9 @@ namespace Net461DllTest.Flow
[NodeAction(NodeType.Action, "打开窗体(指定枚举值)")]
public void OpenForm(IDynamicContext context, FromId fromId = FromId.None, bool isTop = true)
public void OpenForm(IDynamicContext context, FromValue fromId = FromValue.None, bool isTop = true)
{
var fromType = EnumHelper.GetBoundValue<FromId, Type>(fromId, attr => attr.Value);
var fromType = EnumHelper.GetBoundValue<FromValue, Type>(fromId, attr => attr.Value);
if (fromType is null) return;
if (context.Env.IOC.Instantiate(fromType) is Form form)
{
@@ -79,16 +69,17 @@ namespace Net461DllTest.Flow
}
[NodeAction(NodeType.Action, "打开窗体(使用转换器)")]
public void OpenForm2([EnumTypeConvertor(typeof(FromId))] Form form, bool isTop = true)
public void OpenForm2([EnumTypeConvertor(typeof(FromValue))] Form form, bool isTop = true)
{
ViewManagement.OpenView(form, isTop);
}
[NodeAction(NodeType.Action, "关闭窗体")]
public void CloseForm(IDynamicContext context, FromId fromId = FromId.None)
public void CloseForm(IDynamicContext context, FromValue fromId = FromValue.None)
{
var fromType = EnumHelper.GetBoundValue<FromId, Type>(fromId, attr => attr.Value);
var fromType = EnumHelper.GetBoundValue<FromValue, Type>(fromId, attr => attr.Value);
if (fromType is null) return;
ViewManagement.CloseView(fromType);
}
@@ -96,5 +87,6 @@ namespace Net461DllTest.Flow
}
}

View File

@@ -39,9 +39,15 @@
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="IoTClient, Version=1.0.40.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\IoTClient.1.0.40\lib\netstandard2.0\IoTClient.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Ports, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.IO.Ports.4.6.0\lib\net461\System.IO.Ports.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
</Reference>
@@ -54,11 +60,17 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Data\MyData.cs" />
<Compile Include="Device\PlcDevice.cs" />
<Compile Include="Flow\LogicControl.cs" />
<Compile Include="Flow\ViewLogicControl.cs" />
<Compile Include="Device\SiemensPlcDevice.cs" />
<Compile Include="Device\PrakingDevice.cs" />
<Compile Include="Enums\PlcState.cs" />
<Compile Include="Enums\PlcVarEnum.cs" />
<Compile Include="LogicControl\PlcLogicControl.cs" />
<Compile Include="LogicControl\ParkingLogicControl.cs" />
<Compile Include="LogicControl\ViewLogicControl.cs" />
<Compile Include="Enums\FromValue.cs" />
<Compile Include="Signal\OrderSignal.cs" />
<Compile Include="Signal\PLCVarSignal.cs" />
<Compile Include="Utils\ToValue.cs" />
<Compile Include="ViewModel\FromWorkBenchViewModel.cs" />
<Compile Include="View\FromWorkBenchView.cs">
<SubType>Form</SubType>
@@ -66,12 +78,11 @@
<Compile Include="View\FromWorkBenchView.Designer.cs">
<DependentUpon>FromWorkBenchView.cs</DependentUpon>
</Compile>
<Compile Include="Signal\Signal.cs" />
<Compile Include="View\TeseFormView.cs">
<Compile Include="View\TestFormView.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="View\TeseFormView.Designer.cs">
<DependentUpon>TeseFormView.cs</DependentUpon>
<Compile Include="View\TestFormView.Designer.cs">
<DependentUpon>TestFormView.cs</DependentUpon>
</Compile>
<Compile Include="Web\ApiController.cs" />
</ItemGroup>
@@ -89,14 +100,15 @@
<EmbeddedResource Include="View\FromWorkBenchView.resx">
<DependentUpon>FromWorkBenchView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="View\TeseFormView.resx">
<DependentUpon>TeseFormView.cs</DependentUpon>
<EmbeddedResource Include="View\TestFormView.resx">
<DependentUpon>TestFormView.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

View File

@@ -1,18 +1,15 @@
using Serein.Library.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Serein.Library.Attributes.PLCValueAttribute;
namespace Net461DllTest.Signal
namespace Net461DllTest.Signal
{
public enum OrderSignal
{
View_1,
View_2,
Command_1,
Command_2,
Command_3,
Command_4,
Command_5,
Command_6,
Command_7,
Command_8,
Command_9,
}
}

View File

@@ -0,0 +1,64 @@
using Serein.Library.Attributes;
using System;
using static Net461DllTest.Signal.PlcValueAttribute;
namespace Net461DllTest.Signal
{
[AttributeUsage(AttributeTargets.Field)]
public class PlcValueAttribute : Attribute
{
/// <summary>
/// 变量类型
/// </summary>
public enum VarType
{
/// <summary>
/// 只读取的值
/// </summary>
ReadOnly,
/// <summary>
/// 可写入的值
/// </summary>
Writable,
}
/// <summary>
/// 变量属性
/// </summary>
public PlcVarInfo PlcInfo { get; }
public PlcValueAttribute(Type type,
string @var,
VarType varType
)
{
PlcInfo = new PlcVarInfo(type, var, varType);
}
}
public class PlcVarInfo
{
public PlcVarInfo(Type type,
string @var,
VarType varType
)
{
DataType = type;
VarAddress = @var;
Type = varType;
}
public bool IsProtected { get; }
public Type DataType { get; }
public string VarAddress { get; }
public VarType Type { get; }
public override string ToString()
{
return $"数据类型:{DataType} 地址:{VarAddress}";
}
}
}

View File

@@ -1,13 +0,0 @@
using Net461DllTest.Flow;
using Serein.Library.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Signal
{
}

View File

@@ -0,0 +1,231 @@
using IoTClient;
using IoTClient.Clients.PLC;
using IoTClient.Enums;
using Net461DllTest.Signal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Net461DllTest.Utils
{
internal static class MyPlcExtension
{
public static DataTypeEnum ToDataTypeEnum(this PlcVarInfo varInfo)
{
Type dataType = varInfo.DataType;
DataTypeEnum plcDataType;
switch (dataType)
{
case Type _ when dataType == typeof(string):
plcDataType = DataTypeEnum.String;
break;
case Type _ when dataType == typeof(char):
plcDataType = DataTypeEnum.String;
break;
case Type _ when dataType == typeof(bool):
plcDataType = DataTypeEnum.Bool;
break;
case Type _ when dataType == typeof(float):
plcDataType = DataTypeEnum.Float;
break;
case Type _ when dataType == typeof(double):
plcDataType = DataTypeEnum.Double;
break;
case Type _ when dataType == typeof(byte):
plcDataType = DataTypeEnum.Byte;
break;
case Type _ when dataType == typeof(short):
plcDataType = DataTypeEnum.Int16;
break;
case Type _ when dataType == typeof(ushort):
plcDataType = DataTypeEnum.UInt16;
break;
case Type _ when dataType == typeof(int):
plcDataType = DataTypeEnum.Int32;
break;
case Type _ when dataType == typeof(uint):
plcDataType = DataTypeEnum.UInt32;
break;
case Type _ when dataType == typeof(long):
plcDataType = DataTypeEnum.Int64;
break;
case Type _ when dataType == typeof(ulong):
plcDataType = DataTypeEnum.UInt64;
break;
default:
plcDataType = DataTypeEnum.None;
break;
}
return plcDataType;
}
/// <summary>
/// 读取设备的值
/// </summary>
/// <param name="client"></param>
/// <param name="varInfo"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static object ReadToPlcValue(this SiemensClient client,PlcVarInfo varInfo)
{
Type dataType = varInfo.DataType;
object resultvalue;
if (dataType == typeof(string))
{
var result = client.ReadString(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(char))
{
var result = client.ReadString(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(bool))
{
var result = client.ReadBoolean(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(float))
{
var result = client.ReadFloat(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(double))
{
var result = client.ReadDouble(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(byte))
{
var result = client.ReadByte(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(short))
{
var result = client.ReadInt16(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(ushort))
{
var result = client.ReadUInt16(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(int))
{
var result = client.ReadInt32(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(uint))
{
var result = client.ReadUInt32(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(long))
{
var result = client.ReadInt64(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else if (dataType == typeof(ulong))
{
var result = client.ReadUInt64(varInfo.VarAddress);
if (!result.IsSucceed) throw new Exception(result.Err);
resultvalue = result.Value;
}
else
{
resultvalue = default;
}
return resultvalue;
}
public static void WriteToPlcValue(this SiemensClient client, PlcVarInfo varInfo ,object value)
{
if(client == null) throw new ArgumentNullException("client");
Type dataType = varInfo.DataType;
Result result = null;
if (dataType == typeof(string))
{
result = client.Write(varInfo.VarAddress, value.ToString());
}
else if (dataType == typeof(char))
{
result = client.Write(varInfo.VarAddress, value.ToString());
}
else if (dataType == typeof(bool))
{
var @bool = bool.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @bool);
}
else if (dataType == typeof(float))
{
var @float = float.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @float);
}
else if (dataType == typeof(double))
{
var @double = double.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @double);
}
else if (dataType == typeof(byte))
{
var @byte = byte.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @byte);
}
else if (dataType == typeof(short))
{
var @short = short.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @short);
}
else if (dataType == typeof(ushort))
{
var @ushort = ushort.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @ushort);
}
else if (dataType == typeof(int))
{
var @int = int.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @int);
}
else if (dataType == typeof(uint))
{
var @uint = uint.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @uint);
}
else if (dataType == typeof(long))
{
var @long = long.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @long);
}
else if (dataType == typeof(ulong))
{
var @ulong = ulong.Parse(value.ToString());
result = client.Write(varInfo.VarAddress, @ulong);
}
if (result is null)
{
throw new Exception($"未定义的数据类型");
}
if(!result.IsSucceed)
{
throw new Exception(result.Err);
}
}
}
}

View File

@@ -29,33 +29,35 @@
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBoxPlcInfo = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.listBox1 = new System.Windows.Forms.ListBox();
this.textBoxSpaceNum = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(187, 22);
this.button1.Location = new System.Drawing.Point(220, 56);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(98, 23);
this.button1.Size = new System.Drawing.Size(65, 23);
this.button1.TabIndex = 0;
this.button1.Text = "查看状态";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
// textBoxPlcInfo
//
this.textBox1.Location = new System.Drawing.Point(35, 24);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(137, 21);
this.textBox1.TabIndex = 1;
this.textBoxPlcInfo.Location = new System.Drawing.Point(35, 24);
this.textBoxPlcInfo.Name = "textBoxPlcInfo";
this.textBoxPlcInfo.ReadOnly = true;
this.textBoxPlcInfo.Size = new System.Drawing.Size(250, 21);
this.textBoxPlcInfo.TabIndex = 1;
//
// button2
//
this.button2.Location = new System.Drawing.Point(178, 179);
this.button2.Location = new System.Drawing.Point(205, 181);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(107, 23);
this.button2.Size = new System.Drawing.Size(80, 23);
this.button2.TabIndex = 2;
this.button2.Text = "触发";
this.button2.UseVisualStyleBackColor = true;
@@ -70,14 +72,23 @@
this.listBox1.Size = new System.Drawing.Size(250, 88);
this.listBox1.TabIndex = 6;
//
// textBoxSpaceNum
//
this.textBoxSpaceNum.Location = new System.Drawing.Point(35, 183);
this.textBoxSpaceNum.Name = "textBoxSpaceNum";
this.textBoxSpaceNum.Size = new System.Drawing.Size(106, 21);
this.textBoxSpaceNum.TabIndex = 7;
this.textBoxSpaceNum.Text = "104";
//
// FromWorkBenchView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(341, 251);
this.Controls.Add(this.textBoxSpaceNum);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.textBoxPlcInfo);
this.Controls.Add(this.button1);
this.Name = "FromWorkBenchView";
this.Text = "Form1";
@@ -89,8 +100,9 @@
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBoxPlcInfo;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.TextBox textBoxSpaceNum;
}
}

View File

@@ -31,17 +31,21 @@ namespace Net461DllTest
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = ViewModel.GetDeviceInfo();
textBoxPlcInfo.Text = ViewModel.GetDeviceInfo();
}
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.SelectedItem is null)
{
return;
}
string type = listBox1.SelectedItem.ToString();
if (Enum.TryParse(type, out OrderSignal signal) && Enum.IsDefined(typeof(OrderSignal), signal))
if (!string.IsNullOrEmpty(type) && Enum.TryParse(type, out OrderSignal signal) && Enum.IsDefined(typeof(OrderSignal), signal))
{
Console.WriteLine($"Trigger : {type}");
ViewModel.Trigger(signal);
ViewModel.Trigger(signal,textBoxSpaceNum.Text);
}
}

View File

@@ -1,33 +0,0 @@
using Net461DllTest.Data;
using Net461DllTest.Signal;
using Serein.Library.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Net461DllTest.View
{
public partial class TeseFormView : Form
{
[AutoInjection]
public MyData MyData { get; set; }
public TeseFormView()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyData.Count = 0;
}
}
}

View File

@@ -1,6 +1,8 @@
namespace Net461DllTest.View
using System;
namespace Net461DllTest.View
{
partial class TeseFormView
partial class TestFormView
{
/// <summary>
/// Required designer variable.
@@ -37,17 +39,17 @@
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "清空";
this.button1.Text = "测试";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// TeseFormView
// TestFormView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(254, 118);
this.Controls.Add(this.button1);
this.Name = "TeseFormView";
this.Name = "TestFormView";
this.Text = "TeseForm";
this.ResumeLayout(false);

View File

@@ -0,0 +1,19 @@
using System;
using System.Windows.Forms;
namespace Net461DllTest.View
{
public partial class TestFormView : Form
{
public TestFormView()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}

View File

@@ -12,22 +12,21 @@ namespace Net461DllTest.ViewModel
public class FromWorkBenchViewModel
{
[AutoInjection]
public PlcDevice Device { get; set; }
public SiemensPlcDevice Device { get; set; }
public string Name { get; set; }
public string GetDeviceInfo()
{
if(Device is null)
{
return string.Empty;
}
return "PLC ID:" + Device.PlcId + " - " + Device.MyData.Count.ToString();
return Device?.ToString();
}
public void Trigger(OrderSignal signal)
public void Trigger(OrderSignal signal,string spcaeNumber)
{
Device.TriggerSignal(signal, 0);
_ = Task.Run(() =>
{
Device.TriggerSignal(signal, spcaeNumber);
});
}

View File

@@ -14,7 +14,7 @@ namespace Net461DllTest.Web
public class ApiController : ControllerBase
{
[AutoInjection]
public PlcDevice PlcDevice { get; set; }
public SiemensPlcDevice PlcDevice { get; set; }
[WebApi(API.POST)]
public dynamic Trigger([Url] string type, int value)

11
Net461DllTest/app.config Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.IO.Ports" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -1,4 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="IoTClient" version="1.0.40" targetFramework="net461" />
<package id="System.IO.Ports" version="4.6.0" targetFramework="net461" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net461" />
</packages>