zoukankan      html  css  js  c++  java
  • C# SerialPortHelper类

    using System;
    using System.IO.Ports;
    
    
    class SerialPortHelper
    {
        private long _receiveByteCount = 0, _sendByteOfCount = 0;
    
    
        public long ReceiveByteCount { get { return _receiveByteCount; } set { _receiveByteCount = value; } }
        public long SendByteOfCount { get { return _sendByteOfCount; } set { _sendByteOfCount = value; } }
    
    
        SerialPort _serialPort = new SerialPort();
    
    
        private DataReceived _received = null;
    
    
        public delegate void DataReceived(byte[] data);
    
    
        public bool IsOpen { get { return _serialPort.IsOpen; } }
    
    
        public static string[] SerialPortNames
        {
            get
            {
                string[] serialports = SerialPort.GetPortNames();
                Array.Sort(serialports, new Comparison<string>(
                    delegate(string x, string y)
                    {
                        if (x.Length > 3 && y.Length > 3)
                        {
                            string index1 = x.Substring(3);
                            string index2 = y.Substring(3);
                            try
                            {
                                int n1 = Convert.ToInt32(index1);
                                int n2 = Convert.ToInt32(index2);
                                return n1 - n2;
                            }
                            catch
                            {
                            }
                        }
                        return 0;
                    }));
                return serialports;
            }
        }
    
    
        public SerialPortHelper(DataReceived received)
        {
            _received = received;
            _serialPort.NewLine = "
    ";
            _serialPort.DataReceived += delegate
            {
                System.Threading.Thread.Sleep(50);
                int ReadLength = _serialPort.BytesToRead;
                if (ReadLength > 0)
                {
                    _receiveByteCount += ReadLength;
                    byte[] ReadBuffer = new byte[ReadLength];
                    _serialPort.Read(ReadBuffer, 0, ReadLength);
                    if(_received!=null)
                    {
                        _received(ReadBuffer);
                    }
                }
            };
        }
    
    
        public void Open(string PortName)
        {
            _serialPort.PortName = PortName;
            _serialPort.StopBits = StopBits.One;
            _serialPort.Parity = Parity.None;
            _serialPort.DataBits = 8;
            _serialPort.BaudRate = 19200;
            _serialPort.Open();
        }
    
    
        public void Close()
        {
            _serialPort.Close();
        }
    
    
        public void WriteLine(string text)
        {
            if (_serialPort.IsOpen)
            {
                _sendByteOfCount += text.Length;
                _serialPort.WriteLine(text);
            }
        }
    
    
        public void Write(byte[] buffer)
        {
            if (_serialPort.IsOpen)
            {
                _serialPort.Write(buffer, 0, buffer.Length);
                _sendByteOfCount += buffer.Length;
            }
        }
    }

    调用:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    
    namespace SerialnumPort1
    {
        public partial class Form1 : Form
        {
            string _tempfile = AppDomain.CurrentDomain.BaseDirectory + "temp.data";
            SerialPortHelper _helper = null;
            public Form1()
            {
                InitializeComponent();
                _helper = new SerialPortHelper(delegate(byte[] data)
                                                                        {
                                                                            this.Invoke(
                                                                             (EventHandler)delegate
                                                                             {
                                                                                 if (checkBox2.Checked)
                                                                                 {
                                                                                     using (System.IO.FileStream fs = new System.IO.FileStream(_tempfile, System.IO.FileMode.Append))
                                                                                     {
                                                                                         fs.Write(data, 0, data.Length);
                                                                                     }
                                                                                 }
    
                                                                                 StringBuilder readStr = new StringBuilder();
                                                                                 foreach (byte b in data)
                                                                                 {
                                                                                     string temp = string.Format("{0:X2} ", b);
                                                                                     readStr.Append(temp);
                                                                                 }
                                                                                 readStr.Append("已接收
    ");
    
                                                                                 toolStripStatusLabel1.Text = "已接收字节数:" + _helper.ReceiveByteCount;
                                                                                 richTextBox1.AppendText(readStr.ToString());
                                                                                 richTextBox1.ScrollToCaret();
                                                                             }
                                                                            );
                                                                        });
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                string[] serialnums = SerialPortHelper.SerialPortNames;
                comboBox1.Items.AddRange(serialnums);
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                if ("打开" == button2.Text)
                {
                    try
                    {
                        _helper.Open(comboBox1.Text);
                        button2.Text = "关闭";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "
    " + ex.StackTrace);
                    }
                }
                else
                {
                    button2.Text = "打开";
                    _helper.Close();
                }
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                if (_helper.IsOpen)
                {
                    if (!checkBox1.Checked)
                    {
                        _helper.WriteLine(textBox1.Text);
                    }
                    else
                    {
                        string sendtext = textBox1.Text.TrimEnd(' ');
                        string[] sps = sendtext.Split(' ');
                        byte[] sendata = new byte[sps.Length];
                        for (int i = 0; i < sendata.Length; ++i)
                        {
                            sendata[i] = (byte)Convert.ToInt32(sps[i], 16);
                        }
                        _helper.Write(sendata);
                    }
                    richTextBox1.AppendText(textBox1.Text + " 已发送
    ");
                    richTextBox1.ScrollToCaret();
                    toolStripStatusLabel2.Text = "已发送字节数:" + _helper.SendByteOfCount;
                }
            }
    
            private void checkBox2_CheckedChanged(object sender, EventArgs e)
            {
                if (checkBox2.Checked)
                {
                    System.IO.File.Delete(_tempfile);
                    using (System.IO.FileStream fs = System.IO.File.Create(_tempfile))
                    {
                    }
                }
            }
    
        }
    }
    


  • 相关阅读:
    CSS选择器
    HTML2
    html
    http协议
    python--Selectors模块/队列
    Linux系统管理02----目录和文件管理
    Linux系统管理01-----系统命令
    02作业 linux第一章和第三章命令
    01作业 Linux系统管理应用
    01:计算机硬件组层与基本配置------02计算机系统硬件核心知识
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/6727094.html
Copyright © 2011-2022 走看看