using Admin.Core.Common; using S71500.Impl; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Admin.Core.Plc { public class S71500Service : IS71500Service { public S71500Service() { string address = Appsettings.app("Siemens", "ConString").ToString(); int port = Appsettings.app("Siemens", "Port").ObjToInt(); Adapter.Registe(); Adapter.Connect(address, port); } public Task AddPlcAsync() { System.Timers.Timer timer = new System.Timers.Timer(5000);//创建定时器,设置间隔时间为1000毫秒; timer.Elapsed += new System.Timers.ElapsedEventHandler(ExecTask); //到达时间的时候执行事件; timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true); timer.Enabled = true;//需要调用 timer.Start()或者timer.Enabled = true来启动它, timer.Start();//timer.Start()的内部原理还是设置timer.Enabled = true; return Task.CompletedTask; } private void ExecTask(object source, System.Timers.ElapsedEventArgs e) { if (Adapter.Device_GetState("M100")) { Console.WriteLine("PLC连接成功!"); } else { if (!Adapter.IsConnected) { Console.WriteLine("PLC连接失败!"); if (Adapter.Device_Destroy()) { string address = Appsettings.app("Siemens", "ConString").ToString(); int port = Appsettings.app("Siemens", "Port").ObjToInt(); Adapter.Connect(address, port); } } } } } }