Example #1
0
        public bool Open()
        {
            bool rtn = false;

            Close();
            try
            {
                this.SerialPort                = new SerialPort();
                this.SerialPort.PortName       = this.PortName;
                this.SerialPort.BaudRate       = (int)this.BaudRate;
                this.SerialPort.DataBits       = (int)this.DataBits;
                this.SerialPort.StopBits       = this.StopBits;
                this.SerialPort.Parity         = this.Parity;
                this.SerialPort.Encoding       = Encoding.UTF8;
                this.SerialPort.DtrEnable      = this.DTR;
                this.SerialPort.RtsEnable      = this.RTS;
                this.SerialPort.DataReceived  += SerialPort_DataReceived;
                this.SerialPort.ErrorReceived += SerialPort_ErrorReceived;
                this.SerialPort.Open();
                rtn = true;
            }
            catch (Exception ex)
            {
                ExceptionThrown?.Invoke(this, ex);
            }

            if (this.SerialPort != null && this.SerialPort.IsOpen)
            {
                OpenStatusChanged?.Invoke(this, true);
            }

            return(rtn);
        }
Example #2
0
 public void Close()
 {
     if (this.SerialPort != null)
     {
         this.SerialPort.DataReceived  -= SerialPort_DataReceived;
         this.SerialPort.ErrorReceived -= SerialPort_ErrorReceived;
         if (this.SerialPort.IsOpen)
         {
             this.SerialPort.Close();
             OpenStatusChanged?.Invoke(this, false);
         }
         this.SerialPort.Dispose();
         this.SerialPort = null;
     }
 }