MelsecPLC.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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.Melsec;
  9. namespace WCS.Service.PLCAccessors
  10. {
  11. public class MelsecPLC : MelsecMcNet
  12. {
  13. MelsecMcNet plc;
  14. public MelsecPLC(string ip,int port)
  15. {
  16. plc = new MelsecMcNet(ip, port);
  17. plc.ConnectTimeOut = 3000;
  18. plc.ConnectServer();
  19. }
  20. public byte[] ReadBytes(ushort db, ushort address, ushort length)
  21. {
  22. var res = plc.Read("D" + db, length);
  23. if (res.IsSuccess)
  24. return res.Content;
  25. throw new Exception("读取PLC数据失败:" + res.Message);
  26. }
  27. public void WriteBytes(ushort db, ushort address, byte[] data)
  28. {
  29. var start = db + address / 2;
  30. var res = plc.Write("D" + start, data);
  31. if (!res.IsSuccess)
  32. throw new Exception("写入PLC数据失败:" + res.Message);
  33. }
  34. }
  35. }