1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using DevExpress.XtraEditors;
- using HslCommunication.ModBus;
- using System;
- using System.Configuration;
- using System.IO;
- using System.IO.Ports;
- using System.Windows.Forms;
- namespace GCAS.Code
- {
- public class ModbusServerHelper
- {
- public static ModbusTcpServer StartModbusServer()
- {
- ModbusTcpServer busTcpServer = null;
- int.TryParse(ConfigurationManager.AppSettings["slave"], out int slave);
- var portName = ConfigurationManager.AppSettings["portName"];
- int.TryParse(ConfigurationManager.AppSettings["baudRate"], out int baudRate);
- int.TryParse(ConfigurationManager.AppSettings["dataBits"], out int dataBits);
- Enum.TryParse(ConfigurationManager.AppSettings["stopBits"], out StopBits stopBits);
- Enum.TryParse(ConfigurationManager.AppSettings["parity"], out Parity parity);
- SerialPort _tempPort = new SerialPort(portName);
- try
- {
- _tempPort.Open();
- }
- catch { XtraMessageBox.Show("打开串口 " + _tempPort.PortName + " 失败!"); return null; }
- if (_tempPort.IsOpen)
- {
- _tempPort.Close();
- }
- else
- {
- portName = null;
- string[] ports = SerialPort.GetPortNames();
- foreach (var port in ports)
- {
- _tempPort = new SerialPort(portName);
- try
- {
- _tempPort.Open();
- }
- catch (Exception e)
- {
- LogHelper.WriteError(e.Message);
- return null;
- }
- if (_tempPort.IsOpen)
- {
- _tempPort.Close();
- portName = port;
- Tools.UpdateAppConfig("portName", _tempPort.PortName);
- break;
- }
- else
- {
- continue;
- }
- }
- }
- if (portName != null)
- {
- busTcpServer = new ModbusTcpServer
- {
- LogNet = new HslCommunication.LogNet.LogNetSingle(Path.Combine(Application.StartupPath, "logs.txt")) // 配置日志信息
- };
- busTcpServer.ServerStart(502);
- busTcpServer.Station = slave;
- busTcpServer.StartModbusRtu(sp =>
- {
- sp.PortName = portName;
- sp.BaudRate = baudRate;
- sp.DataBits = dataBits;
- sp.StopBits = stopBits;
- sp.Parity = parity;
- });
- }
- return busTcpServer;
- }
- }
- }
|