SiemensS7PLC.cs 1.5 KB

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