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


namespace DL580_9130
{
    class ComPort
    {
        public static SerialPort Com=new SerialPort();

        public static bool Listening = false;
        public static bool Closing = false;
        public static bool NotReceiving = false; //暂停接收


        public static  bool   OpenCom(string  ComName,string Baudrate,string  dataBits, string  stopBits)
        {
            if (ComName.Trim() == "" || Baudrate.Trim() == "") { return false; }
            if (Com.IsOpen) 
            {
                if (!CloseCom()) { return false; }
            }
            try
            {
            
                Com.PortName = ComName;
                Com.BaudRate = int.Parse(Baudrate.Substring (0,Baudrate.Length -3));
                Com.DataBits = int.Parse(dataBits);
                StopBits bit=StopBits.One ;
                if (stopBits == "0")
                {
                    bit = StopBits.None;
                }
                else if (stopBits == "2")
                {
                    bit = StopBits.Two;
                }
                Com.StopBits = bit;
                Com.Open();
            }
            catch (Exception ex)
            {
                Com = new SerialPort();
                MessageBox.Show(ex.Message+"  ","",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return false;
            }
            return true ;
        }
        public static bool CloseCom()
        {
            try
            {
                if (Com.IsOpen)
                {
                    Closing = true;
                    while (Listening)
                    {
                        Application.DoEvents();
                    }
                    Com.Close();
                    Closing = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }
//**********************************
    }
    
}
