using Admin.Core.Common; using Aucma.Core.MelsecPLc; using System.Timers; namespace Aucma.Core.Melsec { /// /// 扫码器初始化 /// public class MelsecService : IMelsecService { System.Timers.Timer timer = new System.Timers.Timer(5000);//创建定时器,设置间隔时间为1000毫秒; #region 构造函数 public MelsecService() { var r = MelsecPlc.Registed(); if (r) { string address = Appsettings.app("Middleware", "Melsec", "ConString").ToString(); int port = Appsettings.app("Middleware", "Melsec", "Port").ObjToInt(); MelsecPlc.Connect(address, port); } } #endregion #region 心跳 public Task StartMelsecAsync() { 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; } #endregion #region 心跳检测 private async void ExecTask(object? sender, ElapsedEventArgs e) { if (await MelsecPlc.Read("M100")) { MelsecPlc.IsConnected = true; //Console.WriteLine(_melsecPlc.ReadBool("M100")); //Console.WriteLine("PLC连接成功!"); } else { if (!MelsecPlc.IsConnected) { Console.WriteLine("PLC连接失败!"); System.GC.Collect(); if (MelsecPlc.DisConnect()) { string address = Appsettings.app("Middleware", "Melsec", "ConString").ToString(); int port = Appsettings.app("Middleware", "Melsec", "Port").ObjToInt(); MelsecPlc.Connect(address, port); } } } } #endregion } }