自己整理的串口工具类

整理自己很久以前代码的时候发现的,那时的我没有写笔记的习惯,看着以前代码不好看,改了一下,也不知道能不能用了,好久没搞了

 

using System;
using System.Threading;
using System.IO.Ports;

public class Serial
{
    //默认
    private SerialPort serialPort;
    private Thread portThread;

    public delegate void CallBack();
    private CallBack callBack;

    /// <summary>
    /// 构造器 要是获取不到串口,用后面这句代码看下计算机上有没有串口了  string[] aaa = System.IO.Ports.SerialPort.GetPortNames();
    /// </summary>
    public Serial(string portName = "COM1", int baudRate = 9600, int dataBits = 8, StopBits stopBits = StopBits.One, Parity parity = Parity.None)
    {
        serialPort = new SerialPort();
        serialPort.PortName = portName;
        serialPort.BaudRate = baudRate;
        serialPort.DataBits = dataBits;
        serialPort.StopBits = stopBits;
        serialPort.Parity = parity;
    }


    /// <summary>
    /// 开始串口
    /// </summary>
    public void BeginSerialPort(CallBack callBack)
    {
        try
        {
            if (serialPort == null)
            {
                return;
            }
            //链接端口
            serialPort.Open();
            this.callBack = callBack;
            portThread = new Thread(ThreadPort);
            portThread.Start();
        }
        catch (Exception)
        {
            throw;
        }
    }


    /// <summary>
    /// 端口线程
    /// </summary>
    private void ThreadPort()
    {
        while (serialPort != null && serialPort.IsOpen)
        {
            if (serialPort.BytesToRead <= 0)
            {
                continue;
            }

            if (callBack != null)
            {
                callBack();
            }
        }
    }

    /// <summary>
    /// 获取byteArr
    /// </summary>
    /// <returns></returns>
    public byte[] GetByteArry()
    {
        if (serialPort == null || !serialPort.IsOpen)
        {
            return null;
        }

        int readLength = serialPort.BytesToRead;
        byte[] readBuf = new byte[readLength];
        //读取命令并放到readBuf字节数组里
        serialPort.Read(readBuf, 0, readLength);
        return readBuf;
    }

    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="bytes"></param>
    public void SendMessage(byte[] args)
    {
        if (serialPort == null || !serialPort.IsOpen)
        {
            return;
        }
        serialPort.Write(args, 0, args.Length);//发送命令
    }

    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="args"></param>
    public void SendMessage(string args)
    {
        if (serialPort == null || !serialPort.IsOpen)
        {
            return;
        }
        serialPort.Write(args);//发送命令
    }


    /// <summary>
    /// 退出串口
    /// </summary>
    public void ExitPort()
    {
        if (portThread != null)
        {
            portThread.Abort();
        }

        if (serialPort != null)
        {
            serialPort.Close();
        }
    }
}

 

 

 

posted on 2022-05-03 23:39  炼金师  阅读(119)  评论(0编辑  收藏  举报

导航