S7.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using IPLCConnect;
  2. using S7.Net;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace S7Connect
  5. {
  6. [PLCProtocol( PLCProtocol.S7)]
  7. public sealed class S7 : IPLCConnect.IPLCConnect
  8. {
  9. public PLCProtocol Protocol => PLCProtocol.S7;
  10. [AllowNull]
  11. private Plc plc;
  12. private bool isConnected = false;
  13. public CpuType CpuType { get; set; } = CpuType.S71200;
  14. public Int16 Rack { get; set; } = 0;
  15. public Int16 Slot { get; set; } = 1;
  16. public bool IsConnected
  17. {
  18. get => isConnected;
  19. set
  20. {
  21. if (isConnected = value) return;
  22. isConnected = value;
  23. StatusChanged?.Invoke(this, value);
  24. }
  25. }
  26. public string IP { get; private set; } = "127.0.0.1";
  27. public int Port { get; private set; } = 502;
  28. public event EventHandler<bool> StatusChanged;
  29. public void Connect()
  30. {
  31. if (plc == null) return;
  32. try
  33. {
  34. plc.Open();
  35. IsConnected = plc.IsConnected;
  36. }
  37. catch
  38. {
  39. IsConnected = false;
  40. }
  41. }
  42. public void DisConnect()
  43. {
  44. if (plc == null) return;
  45. try
  46. {
  47. plc.Close();
  48. }
  49. catch
  50. {
  51. }
  52. IsConnected = false;
  53. }
  54. public void Dispose()
  55. {
  56. try
  57. {
  58. plc?.Close();
  59. }
  60. catch
  61. {
  62. }
  63. plc = null;
  64. }
  65. public void Init(string ip, int port)
  66. {
  67. try
  68. {
  69. IP = ip;
  70. plc = new Plc(this.CpuType, IP, Rack, Slot);
  71. }
  72. catch
  73. {
  74. }
  75. IsConnected = false;
  76. }
  77. public T Read<T>(string addr) where T : unmanaged
  78. {
  79. if(plc ==null || !plc.IsConnected)
  80. {
  81. IsConnected = false;
  82. return default;
  83. }
  84. if (string.IsNullOrEmpty(addr)) return default;
  85. return (T)plc.Read(addr)!;
  86. }
  87. public void Write<T>(string addr, T value) where T : unmanaged
  88. {
  89. if(plc ==null || !plc.IsConnected)
  90. {
  91. IsConnected = false;
  92. return;
  93. }
  94. if (string.IsNullOrEmpty(addr)) return;
  95. plc.Write(addr, value);
  96. }
  97. public bool ReadBit(string addr, byte bitindex)
  98. {
  99. if (string.IsNullOrEmpty(addr)) return false;
  100. return Read<bool>(addr);
  101. }
  102. public void Writebit(string addr, byte bitindex, bool value)
  103. {
  104. if (string.IsNullOrEmpty(addr)) return;
  105. Write(addr, value);
  106. }
  107. }
  108. }