MelsecPLC.cs 1.1 KB

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