ModbusTcpSlaverService.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. using System.Net.Sockets;
  2. using System.Net;
  3. using System.Threading;
  4. using System;
  5. using LogoForceTestApp.Services.Interfaces;
  6. using NModbus;
  7. using LogoForceTestApp.Services.Interfaces.Events;
  8. namespace LogoForceTestApp.Services
  9. {
  10. public class ModbusTcpSlaverService : IModbusTcpSlaverService
  11. {
  12. private IModbusSlave _modbusSlave;
  13. private TcpListener slaveTcpListener;
  14. public event EventHandler<StorageEventArgs<bool>> CoilDiscretesHandler;
  15. public event EventHandler<StorageEventArgs<ushort>> InputRegistersHandler;
  16. public event EventHandler<StorageEventArgs<ushort>> HoldeRegistersHandler;
  17. private CancellationTokenSource _cancellationTokenSource;
  18. public ModbusTcpSlaverService()
  19. {
  20. _cancellationTokenSource = new CancellationTokenSource();
  21. }
  22. /// <summary>
  23. /// create and start the TCP slave
  24. /// 默认创建所有监听所有网卡ip地址和localhost
  25. /// 默认端口号为502
  26. /// 默认slaveId为1
  27. /// </summary>
  28. public void CreateModbusTcpSlave(string ip = default, byte slaveId = 1, int port = 502)
  29. {
  30. IPAddress address;
  31. if (ip == default)
  32. {
  33. address = IPAddress.Any;
  34. }
  35. else
  36. {
  37. var ret = IPAddress.TryParse(ip, out address);
  38. if (!ret)
  39. {
  40. throw new ArgumentException("ip 参数错误");
  41. }
  42. }
  43. slaveTcpListener = new TcpListener(address, port);
  44. slaveTcpListener.Start();
  45. var factory = new ModbusFactory();
  46. //var tcpClient = new TcpClient("",5555);
  47. //var master = factory.CreateMaster(tcpClient);
  48. var network = factory.CreateSlaveNetwork(slaveTcpListener);
  49. var slaveStorage = new SlaveStorage();
  50. slaveStorage.InputRegisters.StorageOperationOccurred += InputRegisters_StorageOperationOccurred;
  51. slaveStorage.HoldingRegisters.StorageOperationOccurred += HoldingRegisters_StorageOperationOccurred;
  52. slaveStorage.CoilInputs.StorageOperationOccurred += CoilInputs_StorageOperationOccurred;
  53. slaveStorage.CoilDiscretes.StorageOperationOccurred += CoilDiscretes_StorageOperationOccurred; ;
  54. var slave = factory.CreateSlave(1, slaveStorage);
  55. network.AddSlave(slave);
  56. var listenTask = network.ListenAsync(_cancellationTokenSource.Token);
  57. _modbusSlave = slave;
  58. }
  59. private void CoilDiscretes_StorageOperationOccurred(object sender, StorageEventArgs<bool> args)
  60. {
  61. //Debug.Write($"DANFOSS CoilDiscretes: {args.Operation} starting at {args.StartingAddress},count {args.Points.Length}");
  62. CoilDiscretesHandler?.Invoke(this, args);
  63. }
  64. private void CoilInputs_StorageOperationOccurred(object sender, StorageEventArgs<bool> args)
  65. {
  66. //LogUtil.WriteInfo($"DANFOSS CoilInputs: {args.Operation} starting at {args.StartingAddress},count {args.Points.Length}");
  67. }
  68. private void HoldingRegisters_StorageOperationOccurred(object sender, StorageEventArgs<ushort> args)
  69. {
  70. //HoldeRegistersHandler?.Invoke(this, args);
  71. //var x=args.Points[32];
  72. }
  73. private void InputRegisters_StorageOperationOccurred(object sender, StorageEventArgs<ushort> args)
  74. {
  75. //LogUtil.WriteInfo($"DANFOSS Input registers: {args.Operation} starting at {args.StartingAddress},count {args.Points.Length}");
  76. InputRegistersHandler?.Invoke(this, args);
  77. }
  78. public IModbusSlave GetModbusSlaveByIp()
  79. {
  80. return _modbusSlave;
  81. }
  82. /// <summary>
  83. /// 写入32位整数
  84. /// </summary>
  85. /// <param name="startAddress"></param>
  86. /// <param name="value"></param>
  87. public void WriteParameter(ushort startAddress, int value)
  88. {
  89. if (_modbusSlave == null)
  90. {
  91. throw new Exception("没有创建modbus slave");
  92. }
  93. var bytes = BitConverter.GetBytes(value);
  94. var first = BitConverter.ToUInt16(new[] { bytes[0], bytes[1] }, 0);
  95. var second = BitConverter.ToUInt16(new[] { bytes[2], bytes[3] }, 0);
  96. _modbusSlave.DataStore.HoldingRegisters.WritePoints(startAddress, new[] { first, second });
  97. }
  98. public void WriteCoilParameter(ushort startAddress, bool value)
  99. {
  100. if (_modbusSlave == null)
  101. {
  102. throw new Exception("没有创建modbus slave");
  103. }
  104. _modbusSlave.DataStore.CoilInputs.WritePoints(startAddress, new bool[] { value });
  105. }
  106. /// <summary>
  107. /// 写入32位正整数
  108. /// </summary>
  109. /// <param name="startAddress"></param>
  110. /// <param name="value"></param>
  111. public void WriteParameter(ushort startAddress, uint value)
  112. {
  113. if (_modbusSlave == null)
  114. {
  115. throw new Exception("没有创建modbus slave");
  116. }
  117. var bytes = BitConverter.GetBytes(value);
  118. var first = BitConverter.ToUInt16(new[] { bytes[0], bytes[1] }, 0);
  119. var second = BitConverter.ToUInt16(new[] { bytes[2], bytes[3] }, 0);
  120. _modbusSlave.DataStore.HoldingRegisters.WritePoints(startAddress, new[] { first, second });
  121. }
  122. /// <summary>
  123. /// 写入16位正整数
  124. /// </summary>
  125. /// <param name="startAddress"></param>
  126. /// <param name="value"></param>
  127. public void WriteParameter(ushort startAddress, ushort value)
  128. {
  129. if (_modbusSlave == null)
  130. {
  131. throw new Exception("没有创建modbus slave");
  132. }
  133. var bytes = BitConverter.GetBytes(value);
  134. var first = BitConverter.ToUInt16(new[] { bytes[0], bytes[1] }, 0);
  135. _modbusSlave.DataStore.HoldingRegisters.WritePoints(startAddress, new[] { first });
  136. }
  137. /// <summary>
  138. /// 写入16位整数
  139. /// </summary>
  140. /// <param name="startAddress"></param>
  141. /// <param name="value"></param>
  142. public void WriteParameter(ushort startAddress, short value)
  143. {
  144. if (_modbusSlave == null)
  145. {
  146. throw new Exception("没有创建modbus slave");
  147. }
  148. var bytes = BitConverter.GetBytes(value);
  149. var first = BitConverter.ToUInt16(new[] { bytes[0], bytes[1] }, 0);
  150. _modbusSlave.DataStore.HoldingRegisters.WritePoints(startAddress, new[] { first });
  151. }
  152. public void Dispose()
  153. {
  154. slaveTcpListener.Stop();
  155. _cancellationTokenSource.Cancel();
  156. }
  157. }
  158. }