using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;

namespace 帆板仪表盘
{
    public static class SerialFun
    {

        /// <summary>
        /// 判断某一个COM端口是否可用
        /// </summary>
        /// <param name="portName">端口号</param>
        /// <returns></returns>
        public static bool IsCommPortValid(string portName)
        {
            SerialPort sp = new SerialPort(portName);
            try
            {
                sp.Open();
                sp.Close();
                return true;//端口可用
            }
            catch
            {
                return false;//打开失败,端口被占用
            }
        }
        //public static string SerialDataRec(string portName)
        //{
        //    byte[] b = new byte[32];
        //    SerialPort sp = new SerialPort(portName);

        //    while (true)
        //    {
        //        //打开新的串行端口连接
        //        sp.Open();
        //        //丢弃来自串行驱动程序的接受缓冲区的数据
        //        sp.DiscardInBuffer();
        //        //丢弃来自串行驱动程序的传输缓冲区的数据
        //        sp.DiscardOutBuffer();
        //        //从串口输入缓冲区读取一些字节并将那些字节写入字节数组中指定的偏移量处
        //        sp.Read(b, 0, b.Length);

        //        StringBuilder sb = new StringBuilder();

        //        for (int i = 0; i < b.Length; i++)
        //        {
        //            sb.Append(Convert.ToString(b[i]) + " ");
        //        }
        //    }
        //}

    }


    #region MyRegion
    /// <summary>
    /// 扫描并且在comBox中列出可用端口
    /// </summary>
    /// <param name="comboBox1"></param>
    /// <returns></returns>
    //public static bool ScanAllPorts(ComboBox comboBox1)
    //{
    //    //create vars for testing
    //    bool _available = false;
    //    SerialPort _tempPort;
    //    String[] Portname = SerialPort.GetPortNames();

    //    //create a loop for each string in SerialPort.GetPortNames
    //    foreach (string str in Portname)
    //    {
    //        try
    //        {
    //            _tempPort = new SerialPort(str);
    //            _tempPort.Open();

    //            //if the port exist and we can open it
    //            if (_tempPort.IsOpen)
    //            {
    //                comboBox1.Items.Add(str);
    //                _tempPort.Close();
    //                _available = true;
    //            }
    //        }

    //        //else we have no ports or can't open them display the 
    //        //precise error of why we either don't have ports or can't open them
    //        catch (Exception ex)
    //        {
    //           // MessageBox.Show(ex.ToString(), "Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
    //            _available = false;
    //        }
    //    }

    //    //return the temp bool
    //    return _available;
    //} 
    #endregion
}