using BPASmartClient.Peripheral; using BPA.Helper; using BPASmartClient.Modbus; using BPASmartClient.Model; using BPASmartClient.Model.PLC; using static BPA.Helper.EventBus; namespace BPASmartClient.PLC { public class PLCMachine : BasePeripheral { ModbusTcp modbusTcp = new ModbusTcp(); public override void Init() { modbusTcp.IsReconnect = true; modbusTcp.Show += new Action((s) => { if (s != null) MessageLog.GetInstance.Show(s); }); modbusTcp.ShowEx += new Action((s) => { if (s != null) MessageLog.GetInstance.ShowEx(s); }); Task.Run(new Action(() => { modbusTcp.ConnectOk = new Action(() => { TaskManage.GetInstance.StartLong(new Action(() => { IsConnected = modbusTcp.Connected; if (!IsConnected) IsWork = false; while (IsConnected) { IsWork = true; foreach (var par in variables) { if (par?.Address.Length > 0) { var res = modbusTcp.Read(par.Address, (ushort)par.ReadLeng); if (status.ContainsKey(par.Address)) { status[par.Address] = res; } else { status.TryAdd(par.Address, res); } } } //foreach (var par in tempVar) //{ // if (par.Value?.Address.Length > 0) // { // var res = modbusTcp.Read(par.Value.Address, (ushort)par.Value.ReadLeng); // if (status.ContainsKey(par.Value.Address)) // { // status[par.Value.Address] = res; // } // else // { // status.TryAdd(par.Value.Address, res); // } // } //} Thread.Sleep(100); } Thread.Sleep(1000); }), $"设备[{DeviceId}][{modbusTcp.IPAdress}]PLC读取线程", true); }); modbusTcp.ModbusTcpConnect(communicationPar.IPAddress, communicationPar.IPPort); })); //PLC 设备连接 Thread.Sleep(1000); //写入数据 EventBus.GetInstance.Subscribe(DeviceId, delegate (IEvent @event, EventCallBackHandle callBack) { if (@event == null) return; var par = @event as WriteModel; modbusTcp.Write(par?.Address, par?.Value); }); } public override void Start() { } public override void Stop() { } public override void WriteData(string address, object value) { if (address != null && value != null) modbusTcp.Write(address, value); } //public override void AddVarInfo(string add, int len) //{ // if (!tempVar.ContainsKey(add) && !string.IsNullOrEmpty(add) && len > 0) // { // tempVar.TryAdd(add, new Variable() // { // Address = add, // ReadLeng = len // }); // } //} protected override void InitStatus() { } } }