BgModbusTcpCommunicate.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using Modbus.Data;
  2. using Modbus.Device;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using TeamAAS_VP;
  13. using TeamAAS_VP.Models;
  14. using TeamAAS_VP.Resources.Languages;
  15. namespace TeamAAS_VP.Core
  16. {
  17. /// <summary>
  18. /// 后台Modbus TCP 通讯
  19. /// </summary>
  20. public class BgModbusTcpCommunicate
  21. {
  22. public TcpListener TcpListener { get;private set; }
  23. public ModbusSlave Slave { get; private set; }
  24. BgModbusTcp Config;
  25. public string IP { get => Config.IP; }
  26. public int Port { get => Config.Port; }
  27. public byte SlaveID { get => Config.SlaveID; }
  28. public bool IsEnabled { get => Config.IsEnabled; }
  29. public BgModbusTcpCommunicate(BgModbusTcp _Config)
  30. {
  31. Config = _Config;
  32. if (!Config.IsEnabled)
  33. {
  34. return;
  35. }
  36. if (TcpListener == null)
  37. {
  38. TcpListener = new TcpListener(IPAddress.Parse(Config.IP), Config.Port);
  39. TcpListener.Start();
  40. }
  41. Slave = ModbusTcpSlave.CreateTcp(Config.SlaveID, TcpListener);
  42. Slave.DataStore = Modbus.Data.DataStoreFactory.CreateDefaultDataStore();
  43. Slave.ModbusSlaveRequestReceived += Slave_ModbusSlaveRequestReceived;
  44. Slave.DataStore.DataStoreWrittenTo += DataStore_DataStoreWrittenTo;
  45. Slave.DataStore.DataStoreReadFrom += DataStore_DataStoreReadFrom;
  46. }
  47. public void Listen()
  48. {
  49. Slave.Listen();
  50. }
  51. private void Slave_ModbusSlaveRequestReceived(object sender, ModbusSlaveRequestEventArgs e)
  52. {
  53. try
  54. {
  55. switch (e.Message.FunctionCode)
  56. {
  57. case 2:
  58. break;
  59. case 4:
  60. break;
  61. default:
  62. break;
  63. }
  64. }
  65. catch (Exception ex)
  66. {
  67. LogHelper.WriteLogError(string.Format(Lang.后台Modbustcp读取0, e.Message.FunctionCode), ex);
  68. }
  69. }
  70. /// <summary>
  71. /// 当通过Modbus命令读取数据存储时发生
  72. /// </summary>
  73. /// <param name="sender"></param>
  74. /// <param name="e"></param>
  75. private void DataStore_DataStoreReadFrom(object sender, Modbus.Data.DataStoreEventArgs e)
  76. {
  77. try
  78. {
  79. switch (e.ModbusDataType)
  80. {
  81. case ModbusDataType.HoldingRegister:
  82. break;
  83. case ModbusDataType.InputRegister:
  84. break;
  85. case ModbusDataType.Coil:
  86. break;
  87. case ModbusDataType.Input:
  88. break;
  89. default:
  90. break;
  91. }
  92. }
  93. catch (Exception ex)
  94. {
  95. LogHelper.WriteLogError(string.Format(Lang.后台Modbustcp读取0, e.ModbusDataType.ToString()), ex);
  96. }
  97. }
  98. /// <summary>
  99. /// 当slave 收到 master 的命令 写入 DO 值或 AO 值到 DataStore 时触发事件。
  100. /// </summary>
  101. /// <param name="sender"></param>
  102. /// <param name="e"></param>
  103. private void DataStore_DataStoreWrittenTo(object sender, Modbus.Data.DataStoreEventArgs e)
  104. {
  105. switch (e.ModbusDataType)
  106. {
  107. case ModbusDataType.Coil: //code 5 //写入单个线圈
  108. //ModbusDataCollection<bool> discretes = slave.DataStore.CoilDiscretes; //获取线圈离散
  109. break;
  110. case ModbusDataType.HoldingRegister: //code 15
  111. //ModbusDataCollection<ushort> holdingRegisters = slave.DataStore.HoldingRegisters; //获取保存寄存器。
  112. break;
  113. }
  114. }
  115. /// <summary>
  116. /// 将接收到的ushort[]转换为float类型
  117. /// </summary>
  118. /// <param name="val"></param>
  119. /// <returns></returns>
  120. public float GetFloatFormUshortArray(ushort[] val)
  121. {
  122. if (val != null && val.Length == 2)
  123. {
  124. List<byte> result = new List<byte>();
  125. result.AddRange(BitConverter.GetBytes(val[0]));
  126. result.AddRange(BitConverter.GetBytes(val[1]));
  127. return BitConverter.ToSingle(result.ToArray(), 0);
  128. }
  129. else
  130. {
  131. return 0.0f;
  132. }
  133. }
  134. /// <summary>
  135. /// 将float类型分解成两个ushort类型
  136. /// </summary>
  137. /// <param name="value"></param>
  138. /// <returns></returns>
  139. public ushort[] GetUshortArrayFormFloat(float value)
  140. {
  141. ushort lowOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(value), 2);
  142. ushort highOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(value), 0);
  143. return new ushort[2] { lowOrderValue, highOrderValue };
  144. }
  145. /// <summary>
  146. /// 获取输入位状态
  147. /// </summary>
  148. /// <param name="index"></param>
  149. /// <returns></returns>
  150. public bool SW(int index)
  151. {
  152. try
  153. {
  154. return Slave.DataStore.CoilDiscretes[index];
  155. }
  156. catch (Exception ex)
  157. {
  158. LogHelper.WriteLogError(Lang.获取输入位状态时出错, ex);
  159. return false;
  160. }
  161. }
  162. /// <summary>
  163. /// 获取输出位状态
  164. /// </summary>
  165. /// <param name="index"></param>
  166. /// <returns></returns>
  167. public bool Oport(int index)
  168. {
  169. try
  170. {
  171. return Slave.DataStore.InputDiscretes[index];
  172. }
  173. catch (Exception ex)
  174. {
  175. LogHelper.WriteLogError(Lang.获取输出位状态时出错, ex);
  176. return false;
  177. }
  178. }
  179. /// <summary>
  180. /// 输出位操作
  181. /// </summary>
  182. /// <param name="index">地址</param>
  183. /// <param name="state">状态</param>
  184. /// <param name="time">脉冲时间</param>
  185. /// <param name="_async">是否异步执行</param>
  186. public void BitOperate(int index, bool state)
  187. {
  188. try
  189. {
  190. Slave.DataStore.InputDiscretes[index] = state;
  191. }
  192. catch (Exception ex)
  193. {
  194. LogHelper.WriteLogError(Lang.输出位操作时出错, ex);
  195. }
  196. }
  197. /// <summary>
  198. /// 输出字操作
  199. /// </summary>
  200. /// <param name="index">字编号</param>
  201. /// <param name="value">输出值</param>
  202. /// <param name="time">脉冲时长</param>
  203. /// <param name="_async">是否异步</param>
  204. public void OutW(int index, ushort value)
  205. {
  206. try
  207. {
  208. Slave.DataStore.InputRegisters[index] = value;
  209. }
  210. catch (Exception ex)
  211. {
  212. LogHelper.WriteLogError(Lang.输出字操作时出错, ex);
  213. }
  214. }
  215. /// <summary>
  216. /// 获取输出字值
  217. /// </summary>
  218. /// <param name="index"></param>
  219. /// <returns></returns>
  220. public ushort ReadOutW(int index)
  221. {
  222. try
  223. {
  224. return Slave.DataStore.InputRegisters[index];
  225. }
  226. catch (Exception ex)
  227. {
  228. LogHelper.WriteLogError(Lang.获取输出字值时出错, ex);
  229. return 0;
  230. }
  231. }
  232. /// <summary>
  233. /// 获取输入字值
  234. /// </summary>
  235. /// <param name="index"></param>
  236. /// <returns></returns>
  237. public ushort InW(int index)
  238. {
  239. try
  240. {
  241. return Slave.DataStore.HoldingRegisters[index];
  242. }
  243. catch (Exception ex)
  244. {
  245. LogHelper.WriteLogError(Lang.获取输入字值时出错, ex);
  246. return 0;
  247. }
  248. }
  249. /// <summary>
  250. /// 输出浮点数
  251. /// </summary>
  252. /// <param name="index">字编号</param>
  253. /// <param name="value">值</param>
  254. /// <param name="time">脉冲时长</param>
  255. /// <param name="_async">是否异步</param>
  256. public void OutReal(int index, float value)
  257. {
  258. try
  259. {
  260. ushort[] data = GetUshortArrayFormFloat(value);
  261. Slave.DataStore.InputRegisters[index] = data[0];
  262. Slave.DataStore.InputRegisters[index + 1] = data[1];
  263. }
  264. catch (Exception ex)
  265. {
  266. LogHelper.WriteLogError(Lang.输出浮点数时出错, ex);
  267. }
  268. }
  269. /// <summary>
  270. /// 获取输出浮点数
  271. /// </summary>
  272. /// <param name="index"></param>
  273. /// <returns></returns>
  274. public float ReadOutReal(int index)
  275. {
  276. try
  277. {
  278. return GetFloatFormUshortArray(new ushort[] { Slave.DataStore.InputRegisters[index], Slave.DataStore.InputRegisters[index + 1] });
  279. }
  280. catch (Exception ex)
  281. {
  282. LogHelper.WriteLogError(Lang.获取输出浮点数时出错, ex);
  283. return 0.0f;
  284. }
  285. }
  286. /// <summary>
  287. /// 获取输入浮点数
  288. /// </summary>
  289. /// <param name="index"></param>
  290. /// <returns></returns>
  291. public float InReal(int index)
  292. {
  293. try
  294. {
  295. return GetFloatFormUshortArray(new ushort[] { Slave.DataStore.HoldingRegisters[index + 1], Slave.DataStore.HoldingRegisters[index + 0] });
  296. }
  297. catch (Exception ex)
  298. {
  299. LogHelper.WriteLogError(Lang.获取输入浮点数时出错, ex);
  300. return 0.0f;
  301. }
  302. }
  303. }
  304. }