You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.9 KiB
C#
97 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.IO.Ports;
|
|
|
|
namespace Mesnac.Communication
|
|
{
|
|
/// <summary>
|
|
/// 串口通讯服务类
|
|
/// </summary>
|
|
public class SerialPortService
|
|
{
|
|
#region 单例实现
|
|
|
|
private static SerialPortService instance = null;
|
|
private Dictionary<int, SerialPort> _dicSerialPort = null; //保存串口对象的集合
|
|
|
|
private SerialPortService()
|
|
{
|
|
if (this._dicSerialPort == null)
|
|
{
|
|
this._dicSerialPort = new Dictionary<int, SerialPort>();
|
|
}
|
|
}
|
|
|
|
public static SerialPortService Instance
|
|
{
|
|
get
|
|
{
|
|
if (instance == null)
|
|
{
|
|
instance = new SerialPortService();
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region 获取串口对象
|
|
|
|
/// <summary>
|
|
/// 获取串口对象
|
|
/// </summary>
|
|
/// <param name="portName">串口名称</param>
|
|
/// <param name="baudRate">波特率</param>
|
|
/// <returns>返可用的串口对象</returns>
|
|
public SerialPort GetSerialPort(string portName, int baudRate)
|
|
{
|
|
SerialPort currSerialPort = null;
|
|
foreach (SerialPort sp in this._dicSerialPort.Values)
|
|
{
|
|
if (sp.PortName == portName && sp.BaudRate == baudRate)
|
|
{
|
|
currSerialPort = sp;
|
|
break;
|
|
}
|
|
}
|
|
if (currSerialPort == null)
|
|
{
|
|
currSerialPort = new SerialPort();
|
|
currSerialPort.PortName = portName;
|
|
currSerialPort.BaudRate = baudRate;
|
|
currSerialPort.Encoding = System.Text.Encoding.Default;
|
|
this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort);
|
|
}
|
|
try
|
|
{
|
|
if (currSerialPort.IsOpen)
|
|
{
|
|
currSerialPort.Close();
|
|
currSerialPort.Open();
|
|
}
|
|
else
|
|
{
|
|
currSerialPort.Open();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
ICSharpCode.Core.LoggingService.Warn(String.Format("串口{0}关闭或打开失败,重新创建串口对象!", portName));
|
|
this._dicSerialPort.Remove(currSerialPort.GetHashCode());
|
|
currSerialPort = new SerialPort();
|
|
currSerialPort.PortName = portName;
|
|
currSerialPort.BaudRate = baudRate;
|
|
currSerialPort.Encoding = System.Text.Encoding.Default;
|
|
this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort);
|
|
currSerialPort.Open();
|
|
}
|
|
return currSerialPort;
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|