SiemensS7PLC.cs 2.2 KB

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