using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WCS.Core; using WCS.Entity; using HslCommunication.Profinet.Siemens; namespace WCS.Service.PLCAccessors { public class SiemensS7PLC : IPLCAccessor { PLC.Siemens.O.SimenssPlc plc; public SiemensS7PLC(string ip,int port,int rack,int slot) { plc = new PLC.Siemens.O.SimenssPlc(ip, rack, slot); plc.Connect(); } public byte[] ReadBytes(ushort db, ushort address, ushort length) { if (!plc.Connected) plc.Connect(); var res = plc.ReadArea(PLC.Siemens.Protocol.Common.AreaType.DB, db, address, length, PLC.Siemens.Protocol.Common.DataType.Byte); if (res == null) throw new Exception("读取DB块数据失败"); return res.Data; } public void WriteBytes(ushort db, ushort address, byte[] data) { if (!plc.Connected) plc.Connect(); var res = plc.WriteArea(PLC.Siemens.Protocol.Common.AreaType.DB, db, address, (ushort)data.Length, PLC.Siemens.Protocol.Common.DataType.Byte, data); if (!res) throw new Exception("写入DB块数据失败"); } } public class SiemensS7PLCHsl : IPLCAccessor { SiemensS7Net plc; public SiemensS7PLCHsl(string ip) { plc = new SiemensS7Net(SiemensPLCS.S1500, ip); plc.ConnectTimeOut = 3000; //plc.ReceiveTimeOut = 500; plc.ConnectServer(); } public byte[] ReadBytes(ushort db, ushort address, ushort length) { var addr = "DB" + db + "." + address; var res = plc.Read(addr, length); if (res.IsSuccess) return res.Content; throw new Exception("读取PLC数据失败:" + res.Message); } public void WriteBytes(ushort db, ushort address, byte[] data) { var start = db + address / 2; var res = plc.Write("D" + start, data); if (!res.IsSuccess) throw new Exception("写入PLC数据失败:" + res.Message); } } }