C#串行端口驱动程序包装类代码和概念质量

C#串行端口驱动程序包装类代码和概念质量,c#,.net,serial-port,driver,wrapper,C#,.net,Serial Port,Driver,Wrapper,想知道你们对我的串行包装器类的看法。已经有一段时间了,我一直在使用串口,但从来没有分享过代码。某种程度上,这让我接近了自己的愿景 我想知道这是否是一个好的/坏的方法,如果接口是足够的,你在它上面看到了什么 我知道Stackoverflow是个问题,但同时这里有很多非常优秀的技术人员,分享代码和观点也能让每个人受益,这就是我决定发布它的原因 谢谢 using System.Text; using System.IO; using System.IO.Ports; using System; na

想知道你们对我的串行包装器类的看法。已经有一段时间了,我一直在使用串口,但从来没有分享过代码。某种程度上,这让我接近了自己的愿景

我想知道这是否是一个好的/坏的方法,如果接口是足够的,你在它上面看到了什么

我知道Stackoverflow是个问题,但同时这里有很多非常优秀的技术人员,分享代码和观点也能让每个人受益,这就是我决定发布它的原因

谢谢

using System.Text;
using System.IO;
using System.IO.Ports;
using System;

namespace Driver
{
    class SerialSingleton
    {
        // The singleton instance reference
        private static SerialSingleton instance = null;

        // System's serial port interface
        private SerialPort serial;

        // Current com port identifier
        private string comPort = null;

        // Configuration parameters
        private int confBaudRate;
        private int confDataBits;
        private StopBits confStopBits;
        private Parity confParityControl;

        ASCIIEncoding encoding = new ASCIIEncoding();

// ==================================================================================
// Constructors

        public static SerialSingleton getInstance()
        {
            if (instance == null)
            {
                instance = new SerialSingleton();
            }
            return instance;
        }

        private SerialSingleton()
        {
            serial = new SerialPort();
        }

// ===================================================================================
// Setup Methods

        public string ComPort
        {
            get { return comPort; }
            set {
                if (value == null)
                {
                    throw new SerialException("Serial port name canot be null.");
                }

                if (nameIsComm(value))
                {
                    close();
                    comPort = value;
                }
                else
                {
                    throw new SerialException("Serial Port '" + value + "' is not a valid com port.");
                }
            }

        }

        public void setSerial(string baudRate, int dataBits, StopBits stopBits, Parity parityControl)
        {
            if (baudRate == null)
            {
                throw new SerialException("Baud rate cannot be null");
            }

            string[] baudRateRef = { "300", "600", "1200", "1800", "2400", "3600", "4800", "7200", "9600", "14400", "19200", "28800", "38400", "57600", "115200" };

            int confBaudRate;
            if (findString(baudRateRef, baudRate) != -1)
            {
                confBaudRate = System.Convert.ToInt32(baudRate);
            }
            else
            {
                throw new SerialException("Baurate parameter invalid.");
            }

            int confDataBits;
            switch (dataBits)
            {
                case 5:
                    confDataBits = 5;
                    break;
                case 6:
                    confDataBits = 6;
                    break;
                case 7:
                    confDataBits = 7;
                    break;
                case 8:
                    confDataBits = 8;
                    break;
                default:
                    throw new SerialException("Databits parameter invalid");
            }

            if (stopBits == StopBits.None)
            {
                throw new SerialException("StopBits parameter cannot be NONE");
            }

            this.confBaudRate = confBaudRate;
            this.confDataBits = confDataBits;
            this.confStopBits = stopBits;
            this.confParityControl = parityControl;
        }

// ==================================================================================

        public string[] PortList
        {
            get {
                return SerialPort.GetPortNames();
            }
        }

        public int PortCount
        {
            get { return SerialPort.GetPortNames().Length; }
        }

// ==================================================================================
// Open/Close Methods


        public void open()
        {
            open(comPort);
        }

        private void open(string comPort) 
        {
            if (isOpen())
            {
                throw new SerialException("Serial Port is Already open");
            }
            else
            {
                if (comPort == null)
                {
                    throw new SerialException("Serial Port not defined. Cannot open");
                }


                bool found = false;
                if (nameIsComm(comPort))
                {
                    string portId;
                    string[] portList = SerialPort.GetPortNames();
                    for (int i = 0; i < portList.Length; i++)
                    {
                        portId = (portList[i]);
                        if (portId.Equals(comPort))
                        {
                            found = true;
                            break;
                        }
                    }
                }
                else
                {
                    throw new SerialException("The com port identifier '" + comPort + "' is not a valid serial port identifier");
                }
                if (!found)
                {
                    throw new SerialException("Serial port '" + comPort + "' not found");
                }

                serial.PortName = comPort;
                try
                {
                    serial.Open();
                }
                catch (UnauthorizedAccessException uaex)
                {
                    throw new SerialException("Cannot open a serial port in use by another application", uaex);
                }

                try
                {
                    serial.BaudRate = confBaudRate;
                    serial.DataBits = confDataBits;
                    serial.Parity = confParityControl;
                    serial.StopBits = confStopBits;
                }
                catch (Exception e)
                {
                    throw new SerialException("Serial port parameter invalid for '" + comPort + "'.\n" + e.Message, e);
                }
            }
        }

        public void close()
        {
            if (serial.IsOpen)
            {
                serial.Close();
            }
        }

// ===================================================================================
// Auxiliary private Methods

        private int findString(string[] set, string search)
        {
            if (set != null)
            {
                for (int i = 0; i < set.Length; i++)
                {
                    if (set[i].Equals(search))
                    {
                        return i;
                    }
                }
            }
            return -1;
        }

        private bool nameIsComm(string name)
        {
            int comNumber;
            int.TryParse(name.Substring(3), out comNumber);
            if (name.Substring(0, 3).Equals("COM"))
            {
                if (comNumber > -1 && comNumber < 256)
                {
                    return true;
                }
            }
            return false;
        }

// =================================================================================
// Device state Methods

        public bool isOpen()
        {
            return serial.IsOpen;
        }

        public bool hasData()
        {
            int amount = serial.BytesToRead;
            if (amount > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

// ==================================================================================
// Input Methods

        public char getChar()
        {
            int data = serial.ReadByte();
            return (char)data;
        }

        public int getBytes(ref byte[] b)
        {
            int size = b.Length;
            char c;
            int counter = 0;
            for (counter = 0; counter < size; counter++)
            {
                if (tryGetChar(out c))
                {
                    b[counter] = (byte)c;
                }
                else
                {
                    break;
                }
            }
            return counter;
        }

        public string getStringUntil(char x)
        {
            char c;
            string response = "";
            while (tryGetChar(out c))
            {
                response = response + c;
                if (c == x)
                {
                    break;
                }
            }
            return response;
        }

        public bool tryGetChar(out char c)
        {
            c = (char)0x00;
            byte[] b = new byte[1];
            long to = 10;
            long ft = System.Environment.TickCount + to;
            while (System.Environment.TickCount < ft)
            {
                if (hasData())
                {
                    int data = serial.ReadByte();
                    c = (char)data;
                    return true;
                }
            }
            return false;
        }

// ================================================================================
// Output Methods

        public void sendString(string data)
        {
            byte[] bytes = encoding.GetBytes(data);
            serial.Write(bytes, 0, bytes.Length);
        }

        public void sendChar(char c)
        {
            char[] data = new char[1];
            data[0] = c;
            serial.Write(data, 0, 1);
        }


        public void sendBytes(byte[] data)
        {
            serial.Write(data, 0, data.Length);
        }

        public void clearBuffer()
        {
            if (serial.IsOpen)
            {
                serial.DiscardInBuffer();
                serial.DiscardOutBuffer();
            }
        }

    }

}
使用System.Text;
使用System.IO;
使用System.IO.Ports;
使用制度;
命名空间驱动程序
{
类串行单例
{
//单例实例引用
私有静态SerialSingleton实例=null;
//系统串口接口
专用串口;
//当前com端口标识符
私有字符串comPort=null;
//配置参数
私人利率;
私人int-Confits;
专用停止位;
私人对等控制;
ascienceoding encoding=新的ascienceoding();
// ==================================================================================
//建设者
公共静态SerialSingleton getInstance()
{
if(实例==null)
{
实例=新的SerialSingleton();
}
返回实例;
}
私有串行单例()
{
串行=新的串行端口();
}
// ===================================================================================
//设置方法
公共字符串组件
{
获取{return comPort;}
设置{
如果(值==null)
{
抛出新的SerialException(“串行端口名不能为null”);
}
如果(名称命令(值))
{
close();
comPort=值;
}
其他的
{
抛出新的SerialException(“串行端口“+”值“+”不是有效的com端口”);
}
}
}
public void setSerial(字符串波特率、整数数据位、停止位、奇偶校验位控制)
{
如果(波特率==null)
{
抛出新的SerialException(“波特率不能为空”);
}
字符串[]波特率参考={“300”、“600”、“1200”、“1800”、“2400”、“3600”、“4800”、“7200”、“9600”、“14400”、“19200”、“28800”、“38400”、“57600”、“115200”};
整数波特率;
如果(findString(波特率参考,波特率)!=-1)
{
confBaudRate=System.Convert.ToInt32(波特率);
}
其他的
{
抛出新的SerialException(“Baurate参数无效”);
}
int-confDataBits;
开关(数据位)
{
案例5:
它=5;
打破
案例6:
系数=6;
打破
案例7:
它=7;
打破
案例8:
它=8;
打破
违约:
抛出新的SerialException(“Databits参数无效”);
}
if(停止位==停止位.无)
{
抛出新的SerialException(“StopBits参数不能为NONE”);
}
this.confBaudRate=confBaudRate;
this.confDataBits=confDataBits;
this.confStopBits=停止位;
this.confParityControl=parityControl;
}
// ==================================================================================
公共字符串[]端口列表
{
得到{
返回SerialPort.GetPortNames();
}
}
公共整数端口计数
{
获取{return SerialPort.GetPortNames().Length;}
}
// ==================================================================================
//打开/关闭方法
公开作废
{
开放式;
}
私有void open(字符串组成)
{
if(isOpen())
{
抛出新的SerialException(“串行端口已打开”);
}
其他的
{
if(comPort==null)
{
抛出新的SerialException(“未定义串行端口。无法打开”);
}
bool-found=false;
if(名称命令(组件))
{
字符串端口;
字符串[]端口列表=SerialPort.GetPortNames();
for(int i=0;i