110 lines
3.5 KiB
C#
110 lines
3.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.IO.Ports;
|
|
|
|
namespace HHWMS.Web
|
|
{
|
|
/// <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.ReadTimeout = 3000;
|
|
// currSerialPort.Handshake = Handshake.None;
|
|
// currSerialPort.ReceivedBytesThreshold = 1;
|
|
|
|
// currSerialPort.RtsEnable = true;
|
|
|
|
// 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}关闭或打开失败,重新创建串口对象,详情:{1}", portName, ex.Message));
|
|
// this._dicSerialPort.Remove(currSerialPort.GetHashCode());
|
|
// currSerialPort = new SerialPort();
|
|
// currSerialPort.PortName = portName;
|
|
// currSerialPort.BaudRate = baudRate;
|
|
|
|
// currSerialPort.ReadTimeout = 3000;
|
|
// currSerialPort.Handshake = Handshake.None;
|
|
// currSerialPort.ReceivedBytesThreshold = 1;
|
|
// currSerialPort.RtsEnable = true;
|
|
|
|
// currSerialPort.Encoding = System.Text.Encoding.Default;
|
|
// this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort);
|
|
// currSerialPort.Open();
|
|
// }
|
|
// return currSerialPort;
|
|
//}
|
|
|
|
#endregion
|
|
}
|
|
}
|