SiemensS7PLC.cs 1.6 KB

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