Modbus_Tcp.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. using FluentModbus;
  2. using System.Runtime.InteropServices;
  3. namespace Universal.IO;
  4. public class Modbus_Tcp : IModBus<byte[]?>
  5. {
  6. private ModbusTcpClient? _master;
  7. private IPEndPoint? EndPoint;
  8. private string? _name;
  9. private string _ip = string.Empty;
  10. private ushort _port;
  11. private ITcpConnectNority? _connect;
  12. public bool Initialize(string name, ITcpConnectNority tcpConnect)
  13. {
  14. if (!string.IsNullOrEmpty(this._name))
  15. return false;
  16. this._name = name;
  17. this._name ??= "Default";
  18. this._connect = tcpConnect;
  19. return true;
  20. }
  21. public bool Open(string ip, ushort port, bool notify = true)
  22. {
  23. if (this._master is not null)
  24. return false;
  25. if (!IPAddress.TryParse(ip, out IPAddress? address) || address is null)
  26. return false;
  27. try
  28. {
  29. IPEndPoint endPoint = new(address, port);
  30. ModbusTcpClient client = new()
  31. {
  32. ReadTimeout = 500,
  33. ConnectTimeout = 500
  34. };
  35. if (notify)
  36. client.Connect(endPoint);
  37. this._ip = ip;
  38. this._port = port;
  39. this.EndPoint = endPoint;
  40. this._master = client;
  41. }
  42. catch
  43. {
  44. return false;
  45. }
  46. return true;
  47. }
  48. public byte[]? GetBuffer(ushort index, ushort count, byte slaveAddress = 1)
  49. {
  50. if (this._master is null)
  51. return null;
  52. try
  53. {
  54. lock (this)
  55. {
  56. Span<byte> bytes = this._master.ReadHoldingRegisters(0x00, index, count);
  57. if (bytes == null)
  58. return null;
  59. return bytes.ToArray();
  60. }
  61. }
  62. catch
  63. {
  64. TryReconnect();
  65. return null;
  66. }
  67. }
  68. public unsafe bool SetFloat(ushort index, float value, byte slaveAddress = 1)
  69. {
  70. if (this._master is null)
  71. return false;
  72. byte[] bytes = new byte[4];
  73. float* pSource = &value;
  74. byte* pByte = (byte*)pSource;
  75. bytes[0] = pByte[3];
  76. bytes[1] = pByte[2];
  77. bytes[2] = pByte[1];
  78. bytes[3] = pByte[0];
  79. try
  80. {
  81. lock (this)
  82. this._master.WriteMultipleRegisters(0x00, (int)index, bytes);
  83. }
  84. catch
  85. {
  86. return false;
  87. }
  88. return true;
  89. }
  90. public unsafe bool SetValue<T>(ushort index, T value, byte slaveAddress = 1) where T : struct
  91. {
  92. if (this._master is null)
  93. return false;
  94. int size = Marshal.SizeOf<T>();
  95. if (size % 4 != 0)
  96. return false;
  97. byte[] bytes = new byte[size];
  98. #pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type
  99. T* pSource = &value;
  100. #pragma warning restore CS8500
  101. byte* pByte = (byte*)pSource;
  102. for (int i = 0; i < size; i += 4)
  103. {
  104. bytes[i] = pByte[i + 3];
  105. bytes[i + 1] = pByte[i + 2];
  106. bytes[i + 2] = pByte[i + 1];
  107. bytes[i + 3] = pByte[i];
  108. }
  109. try
  110. {
  111. lock (this)
  112. this._master.WriteMultipleRegisters(0x00, (int)index, bytes);
  113. }
  114. catch
  115. {
  116. return false;
  117. }
  118. return true;
  119. }
  120. public unsafe bool SetUshort(ushort index, ushort value, byte slaveAddress = 1)
  121. {
  122. if (this._master is null)
  123. return false;
  124. ushort* pUshort = &value;
  125. byte* pByte = (byte*)pUshort;
  126. byte[] result = [pByte[1], pByte[0]];
  127. try
  128. {
  129. lock (this)
  130. this._master.WriteSingleRegister(0x00, index, result);
  131. }
  132. catch
  133. {
  134. return false;
  135. }
  136. return true;
  137. }
  138. public bool Close()
  139. {
  140. this._master?.Dispose();
  141. this._master = null;
  142. this.IsCanceled = true;
  143. return true;
  144. }
  145. private volatile bool IsCanceled = false;
  146. private readonly Semaphore semaphore = new(1, 1);
  147. private void TryReconnect()
  148. {
  149. if (!semaphore.WaitOne(0))
  150. return;
  151. this._master?.Disconnect();
  152. this._connect?.DisConnect(this._ip, this._port);
  153. Task.Factory.StartNew(() =>
  154. {
  155. IsCanceled = false;
  156. this._master ??= new()
  157. {
  158. ReadTimeout = 500,
  159. ConnectTimeout = 500
  160. };
  161. try
  162. {
  163. while (true)
  164. {
  165. if (this.IsCanceled)
  166. return;
  167. try
  168. {
  169. this._master.Connect(EndPoint!);
  170. break;
  171. }
  172. catch
  173. {
  174. Thread.Sleep(1000);
  175. }
  176. }
  177. this._connect?.Connect(this._ip, this._port);
  178. }
  179. finally
  180. {
  181. semaphore.Release();
  182. }
  183. });
  184. }
  185. }