SiemensS7PLC.cs 1.6 KB

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