DevicePlcS7.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using HslCommunication.Profinet.Siemens;
  2. using IMCS.CCS.Entitys;
  3. using IMCS_CCS.Utils;
  4. using S7.Net;
  5. using System;
  6. namespace IMCS.CCS.DeviceProtocol
  7. {
  8. public class DevicePlcS7
  9. {
  10. public static Plc S7(string ip,string type)
  11. {
  12. Plc s7Plc = new Plc(CpuType.S71500, ip, 0, 1);
  13. if (type == "S7_1200")
  14. {
  15. s7Plc = new Plc(CpuType.S71200, ip, 0, 1);
  16. }
  17. else if (type == "S7_400")
  18. {
  19. s7Plc = new Plc(CpuType.S7400, ip, 0, 1);
  20. }
  21. else if (type == "S7_300")
  22. {
  23. s7Plc = new Plc(CpuType.S7300, ip, 0, 1);
  24. }
  25. s7Plc.Open();
  26. return s7Plc;
  27. }
  28. public static SiemensS7Net SiemensS7(string ip, int port = 102)
  29. {
  30. SiemensS7Net SiemensS7Net = new SiemensS7Net(SiemensPLCS.S1200, ip) { ConnectTimeOut = 5000 };
  31. SiemensS7Net.ConnectionId = Guid.NewGuid().ToString();
  32. return SiemensS7Net;
  33. }
  34. public static string ReadValueAsString(SiemensS7Net s7, CcsActionAddress tagValueData)
  35. {
  36. if (s7 == null || tagValueData == null)
  37. return string.Empty;
  38. string result = string.Empty;
  39. string type = tagValueData.Type;
  40. if (type.Equals(TagValueReadTypeEnum.BOOL.ToString(), StringComparison.OrdinalIgnoreCase))
  41. {
  42. result = s7.ReadBool(tagValueData.Address).Content.ToString();
  43. }
  44. else if (type.Equals(TagValueReadTypeEnum.SHORT.ToString(), StringComparison.OrdinalIgnoreCase))
  45. {
  46. result = s7.ReadInt16(tagValueData.Address).Content.ToString();
  47. }
  48. else if (type.Equals(TagValueReadTypeEnum.String.ToString(), StringComparison.OrdinalIgnoreCase))
  49. {
  50. result = s7.ReadString(tagValueData.Address).Content?.ToString() ?? string.Empty;
  51. }
  52. else if (type.Equals(TagValueReadTypeEnum.Array.ToString(), StringComparison.OrdinalIgnoreCase))
  53. {
  54. var bytes = s7.Read(tagValueData.Address, 2048).Content;
  55. result = ToolUtils.ReturnStringByBytes(bytes);
  56. }
  57. return result;
  58. }
  59. }
  60. }