using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Microsoft.VisualBasic;
using System.IO.Ports;
using CommonClassLib;
namespace SimensSerialPort
{
    /// <summary>
    /// Create by Richard.liu 2008 
    /// Simens PLC通讯类,RS232的自由口协议
    /// </summary>
    public class CSimensSerialPort
    {
        SerialPort com;
        bool _ifInit;
        short _portNo;
        string _settings;
        
        /// <summary>
        /// 初始化PLC自由口协议通讯类
        /// </summary>
        /// <param name="Portno">计算机串口（COM口）号：1，2，3，4，5，6，7，8</param>
        /// <param name="Settings">通讯设置：9600，None，8，One；分隔符使用全角“，”</param>
        public CSimensSerialPort(short Portno, string Settings)
        {
            
            _portNo = Portno;
            _settings = Settings;
            com = new SerialPort();
            
        }
        string _ComError;


        public string ComError
        {
            get { return _ComError; }
            set { _ComError = value; }
        }
        public bool InitCom()
        {

            try
            {

                if (com.IsOpen  == true)
                {
                    com.Close();
                }
                com.PortName ="COM"+ _portNo.ToString();
                char[] cc = new char[1] { '，'};
                string[] split = _settings.Split(cc);
                com.BaudRate =Convert.ToInt32( split[0]);
                com.Parity = Parity.None;//(Parity)Convert.ChangeType(split[1], typeof(Parity));
                com.DataBits = Convert.ToInt32(split[2]);
                com.StopBits = StopBits.One;// (StopBits)Convert.ChangeType(split[3], typeof(StopBits));
                
                com.Open();
                _ifInit = true;
                return true;
            }
            catch (Exception ex)
            {
                _ComError = "通讯端口:" + _portNo + "初始化失败!" + ex.Message;
                return false;
            }


        }
        public byte[] ReadCom(short InBufCount)
        {
            if (_ifInit == false)
                InitCom();
            int i = 0;
            try
            {
                do
                {
                    i++;
                    if (i > 5)
                        break;
                    Thread.Sleep(300);

                } while (com.BytesToRead < InBufCount);
                if (com.BytesToRead <= 0)
                {
                    _ComError = "在串口输入缓冲区内没有要接收到的数据！";
                    return null;
                }
                byte[] inbyte = new byte[InBufCount];
                com.Read(inbyte, 0, InBufCount);
                //CCarryConvert.WriteDarkCasket(this.ToString(), "Read", com.PortName, inbyte);
                return inbyte;
            }
            catch (Exception ex)
            {
                _ComError = ex.Message;
                return null;
            }
        }
        public string ReadCom()
        {
            if (_ifInit == false)
                InitCom();
            try
            {
                string gets = com.ReadExisting();
                //CCarryConvert.WriteDarkCasket(this.ToString(), "ReadExisting", com.PortName, gets);
                return gets;
            }
            catch (Exception ex)
            {
                _ComError = ex.Message;
                return null;
            }
        }
        public bool WriteCom(string wData)
        {
            if (_ifInit == false)
                InitCom();
            try
            {
                
                com.Write( wData);
                //CCarryConvert.WriteDarkCasket(this.ToString(), "Write", com.PortName, wData);
                return true;

            }
            catch (Exception ex)
            {
                _ComError = "写串口缓冲区失败！" + ex.Message;
                return false;
            }
        }
        public bool WriteCom(byte[] wData)
        {
            if (_ifInit == false)
                InitCom();
            try
            {
                //com.WriteBufferSize = 0;
                com.Write(wData, 0, wData.GetUpperBound(0)+1);
                //CCarryConvert.WriteDarkCasket(this.ToString(), "Write", com.PortName, wData);
                return true;

            }
            catch (Exception ex)
            {
                _ComError = "写串口缓冲区失败！" + ex.Message;
                return false;
                

            }
        }
        public void CloseCom()
        {
            if (com.IsOpen==true) com.Close();
        }
    }
}
