using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; namespace HHWMS.Web { /// /// 串口通讯服务类 /// public class SerialPortService { #region 单例实现 //private static SerialPortService instance = null; //private Dictionary _dicSerialPort = null; //保存串口对象的集合 //private SerialPortService() //{ // if (this._dicSerialPort == null) // { // this._dicSerialPort = new Dictionary(); // } //} //public static SerialPortService Instance //{ // get // { // if (instance == null) // { // instance = new SerialPortService(); // } // return instance; // } //} //#endregion //#region 获取串口对象 ///// ///// 获取串口对象 ///// ///// 串口名称 ///// 波特率 ///// 返可用的串口对象 //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 } }