SiemensS7PLC.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using PlcSiemens.O;
  2. using PlcSiemens.Protocol.Common;
  3. using ServiceCenter;
  4. using ServiceCenter.Virtual_PLC;
  5. using WCS.Core;
  6. namespace WCS.Service.PLCAccessors
  7. {
  8. public class SiemensS7PLC : IPLCAccessor
  9. {
  10. private SimenssPlc plc;
  11. public SiemensS7PLC(string ip, int port, int rack, int slot)
  12. {
  13. plc = new SimenssPlc(ip, rack, slot);
  14. plc.Connect();
  15. }
  16. public byte[] ReadBytes(ushort db, ushort address, ushort length)
  17. {
  18. if (!plc.Connected)
  19. plc.Connect();
  20. var res = plc.ReadArea(AreaType.DB, db, address, length, DataType.Byte);
  21. if (res == null)
  22. throw new Exception("读取DB块数据失败");
  23. return res.Data;
  24. }
  25. public void WriteBytes(ushort db, ushort address, byte[] data)
  26. {
  27. if (!plc.Connected)
  28. plc.Connect();
  29. var res = plc.WriteArea(AreaType.DB, db, address, (ushort)data.Length, DataType.Byte, data);
  30. if (!res)
  31. throw new Exception("写入DB块数据失败");
  32. }
  33. }
  34. }