SiemensS7PLC.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using HslCommunication.Profinet.Siemens;
  3. using WCS.Core;
  4. namespace WCS.Service.PLCAccessors
  5. {
  6. public class SiemensS7PLC : IPLCAccessor
  7. {
  8. private PLC.Siemens.O.SimenssPlc plc;
  9. public SiemensS7PLC(string ip, int port, int rack, int slot)
  10. {
  11. plc = new PLC.Siemens.O.SimenssPlc(ip, rack, slot);
  12. plc.Connect();
  13. }
  14. public byte[] ReadBytes(ushort db, ushort address, ushort length)
  15. {
  16. if (!plc.Connected)
  17. plc.Connect();
  18. var res = plc.ReadArea(PLC.Siemens.Protocol.Common.AreaType.DB, db, address, length, PLC.Siemens.Protocol.Common.DataType.Byte);
  19. if (res == null)
  20. throw new Exception("读取DB块数据失败");
  21. return res.Data;
  22. }
  23. public void WriteBytes(ushort db, ushort address, byte[] data)
  24. {
  25. if (!plc.Connected)
  26. plc.Connect();
  27. var res = plc.WriteArea(PLC.Siemens.Protocol.Common.AreaType.DB, db, address, (ushort)data.Length, PLC.Siemens.Protocol.Common.DataType.Byte, data);
  28. if (!res)
  29. throw new Exception("写入DB块数据失败");
  30. }
  31. }
  32. public class SiemensS7PLCHsl : IPLCAccessor
  33. {
  34. private SiemensS7Net plc;
  35. public SiemensS7PLCHsl(string ip)
  36. {
  37. plc = new SiemensS7Net(SiemensPLCS.S1500, ip);
  38. plc.ConnectTimeOut = 3000;
  39. //plc.ReceiveTimeOut = 500;
  40. plc.ConnectServer();
  41. }
  42. public byte[] ReadBytes(ushort db, ushort address, ushort length)
  43. {
  44. var addr = "DB" + db + "." + address;
  45. var res = plc.Read(addr, length);
  46. if (res.IsSuccess)
  47. return res.Content;
  48. throw new Exception("读取PLC数据失败:" + res.Message);
  49. }
  50. public void WriteBytes(ushort db, ushort address, byte[] data)
  51. {
  52. var start = db + address / 2;
  53. var res = plc.Write("D" + start, data);
  54. if (!res.IsSuccess)
  55. throw new Exception("写入PLC数据失败:" + res.Message);
  56. }
  57. }
  58. }