SiemensS7PLC.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 (ServiceHub.Any(SystemMode.虚拟plc))
  19. {
  20. return PlcData.Read(new PLCData { IP = plc.IP, DB = db, Length = length, DataLength = length });
  21. }
  22. if (!plc.Connected)
  23. plc.Connect();
  24. var res = plc.ReadArea(AreaType.DB, db, address, length, DataType.Byte);
  25. if (res == null)
  26. throw new Exception("读取DB块数据失败");
  27. return res.Data;
  28. }
  29. public void WriteBytes(ushort db, ushort address, byte[] data)
  30. {
  31. if (ServiceHub.Any(SystemMode.虚拟plc))
  32. {
  33. PlcData.Write(new PLCData { IP = plc.IP, DB = db }, address, data);
  34. }
  35. else
  36. {
  37. if (!plc.Connected)
  38. plc.Connect();
  39. var res = plc.WriteArea(AreaType.DB, db, address, (ushort)data.Length, DataType.Byte, data);
  40. if (!res)
  41. throw new Exception("写入DB块数据失败");
  42. }
  43. }
  44. }
  45. }