ModbusServerHelper.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using DevExpress.XtraEditors;
  2. using HslCommunication.ModBus;
  3. using System;
  4. using System.Configuration;
  5. using System.IO;
  6. using System.IO.Ports;
  7. using System.Windows.Forms;
  8. namespace GCAS.Code
  9. {
  10. public class ModbusServerHelper
  11. {
  12. public static ModbusTcpServer StartModbusServer()
  13. {
  14. ModbusTcpServer busTcpServer = null;
  15. int.TryParse(ConfigurationManager.AppSettings["slave"], out int slave);
  16. var portName = ConfigurationManager.AppSettings["portName"];
  17. int.TryParse(ConfigurationManager.AppSettings["baudRate"], out int baudRate);
  18. int.TryParse(ConfigurationManager.AppSettings["dataBits"], out int dataBits);
  19. Enum.TryParse(ConfigurationManager.AppSettings["stopBits"], out StopBits stopBits);
  20. Enum.TryParse(ConfigurationManager.AppSettings["parity"], out Parity parity);
  21. SerialPort _tempPort = new SerialPort(portName);
  22. try
  23. {
  24. _tempPort.Open();
  25. }
  26. catch { XtraMessageBox.Show("打开串口 " + _tempPort.PortName + " 失败!"); return null; }
  27. if (_tempPort.IsOpen)
  28. {
  29. _tempPort.Close();
  30. }
  31. else
  32. {
  33. portName = null;
  34. string[] ports = SerialPort.GetPortNames();
  35. foreach (var port in ports)
  36. {
  37. _tempPort = new SerialPort(portName);
  38. try
  39. {
  40. _tempPort.Open();
  41. }
  42. catch (Exception e)
  43. {
  44. LogHelper.WriteError(e.Message);
  45. return null;
  46. }
  47. if (_tempPort.IsOpen)
  48. {
  49. _tempPort.Close();
  50. portName = port;
  51. Tools.UpdateAppConfig("portName", _tempPort.PortName);
  52. break;
  53. }
  54. else
  55. {
  56. continue;
  57. }
  58. }
  59. }
  60. if (portName != null)
  61. {
  62. busTcpServer = new ModbusTcpServer
  63. {
  64. LogNet = new HslCommunication.LogNet.LogNetSingle(Path.Combine(Application.StartupPath, "logs.txt")) // 配置日志信息
  65. };
  66. busTcpServer.ServerStart(502);
  67. busTcpServer.Station = slave;
  68. busTcpServer.StartModbusRtu(sp =>
  69. {
  70. sp.PortName = portName;
  71. sp.BaudRate = baudRate;
  72. sp.DataBits = dataBits;
  73. sp.StopBits = stopBits;
  74. sp.Parity = parity;
  75. });
  76. }
  77. return busTcpServer;
  78. }
  79. }
  80. }