C# 学习笔记(四)----- 串口读写

实例:串口读写

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;

namespace BatteryLife
{

    class PortConnection
    {
      //  private SerialPort comm = null;
        private Log log = new Log();
        private bool IsConnect = false;
        public bool isConnect
        {
            get { return IsConnect; }
            
        }
        public PortConnection()
        {           
        }
        public void InitPort(SerialPort comm,string portName,string baudRate)//连接串口
        {

            if (comm.IsOpen)
            {
                comm.Close();
                IsConnect = false;
            }
            else
            {
                comm.PortName = portName;
                comm.BaudRate = int.Parse(baudRate);
                try
                {
                    comm.Open();
                    comm_DataSend(comm, CommadType.Confirm, 0x00, TestType.none,0x00,0x00);//发送连接确认指令
                    Thread.Sleep(500);//等待数据
                    if (comm_DataRecieve(comm, new byte[17], new List<byte>(4096)) == CommadType.Confirm)
                    {
                        IsConnect = true;
                    }
                    else
                    {
                        if (TryAgain(comm, CommadType.Confirm, 0x00, TestType.none, 0x00, 0x00) == CommadType.Confirm)
                            IsConnect = true;
                        else
                            IsConnect = false;
                    }
                  
                }
                catch (Exception e)
                {
                    IsConnect = false;
                    comm = new SerialPort();
                }
            }
        }

        public void comm_DataSend(SerialPort comm,CommadType Cmd,byte Channel,TestType testType,byte onDelay, byte offDelay) //发送指令
        {
            try
            {
                byte temp = (byte)(Channel + testType);
                byte[] byteCommand = { 0x23, (byte)Cmd, temp, onDelay, offDelay, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0A };
                comm.Write(byteCommand, 0, byteCommand.Length);
                log.Save("Send command:0x"+Cmd.ToString("X"));
            }
            catch (Exception e)
            {
                log.Save("Connected abnormal:"+"\n" + e.Message);
            }
       
        }
        public CommadType comm_DataRecieve(SerialPort comm, byte[] byteData, List<byte> buffer)//接收并解析数据,抓取数据包放入byteData,并返回数据包类型
        {
            int n = comm.BytesToRead;    //获取缓存区数据长度 
            byte[] byteRead = new byte[n];
            comm.Read(byteRead, 0, n); //读取缓存区数据到数组 byteRead
            //解释协议
            //=====================================================================================
            if (n >= byteData.Length)
            {
                buffer.AddRange(byteRead);   //将数据放到集合 buffer
                while (buffer.Count >= byteData.Length)
                {
                    //if (buffer[15] == 0x0D && buffer[16] == 0x0A)//从缓存区筛选
                    //{
                        //buffer.CopyTo(0, byteData, 0, byteData.Length); //得到包,存放至 byteData

                    if (buffer[buffer.Count - 2] == 0x0D && buffer[buffer.Count - 1] == 0x0A)//从缓存区筛选
                    {
                        buffer.CopyTo(buffer.Count - byteData.Length, byteData, 0, byteData.Length);//得到包,存放至 byteData
                        
                        buffer.Clear();
                        switch (byteData[1])
                        {
                            case (byte)CommadType.Confirm:
                                return CommadType.Confirm;
                            case (byte)CommadType.Test:
                                return CommadType.Test;
                            case (byte)CommadType.End:
                                return CommadType.End;
                            case (byte)CommadType.Start:
                                return CommadType.Start;
                            case (byte)CommadType.Stop:
                                return CommadType.Stop;
                        }
                    }
                    else
                    {
                        buffer.RemoveAt(0);
                    }
                }
                return CommadType.Abnormal;
            }
            else
                return CommadType.Abnormal;
          //=====================================================================================
          
        }

        public CommadType TryAgain(SerialPort comm, CommadType Cmd, byte Channel, TestType testType, byte onDelay, byte offDelay)    //尝试重发指令
        {
            int n = 0;
            while (n < 3)
            {
                comm_DataSend(comm, Cmd, Channel, testType,onDelay, offDelay);
                Thread.Sleep(2000);
                CommadType result = comm_DataRecieve(comm, new byte[17], new List<byte>(4096));
                if (result != CommadType.Abnormal)
                    return result;
                else
                    n++;
            }
            return CommadType.Abnormal;
        }

        public CommadType comm_DataAnalyze(SerialPort comm, byte[] byteData, List<byte> buffer)//解析数据,抓取数据包放入byteData,并返回数据包类型
        {
            while (buffer.Count >= byteData.Length)
            {
                //if (buffer[15] == 0x0D && buffer[16] == 0x0A)//从缓存区筛选
                //{
                //    buffer.CopyTo(0, byteData, 0, byteData.Length); //得到包,存放至 byteData
                if (buffer[buffer.Count - 2] == 0x0D && buffer[buffer.Count - 1] == 0x0A)//从缓存区筛选
                {
                    buffer.CopyTo(buffer.Count - byteData.Length, byteData, 0, byteData.Length);//得到包,存放至 byteData
                         
                    buffer.Clear();
                    switch (byteData[1])
                    {
                        case (byte)CommadType.Confirm:
                            return CommadType.Confirm;
                        case (byte)CommadType.Test:
                            return CommadType.Test;
                        case (byte)CommadType.End:
                            return CommadType.End;
                        case (byte)CommadType.Start:
                            return CommadType.Start;
                        case (byte)CommadType.Stop:
                            return CommadType.Stop;
                    }
                }
                else
                {
                    buffer.RemoveAt(0);
                }
            }
            return CommadType.Abnormal;
           
            //=====================================================================================

        }
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值