public override void Dispose()
 {
     _isActive = false;
     _serialPort.Dispose();
     _serialPort = null;
     _receiveSignal.Set();
     _sendSignal.Set();
 }
Пример #2
0
        public async Task CloseAsync()
        {
            await _serialPort.CloseAsync();

            _serialPort.Dispose();
            _serialPort = null;

            IsConected = false;
        }
 private void CloseSerialPortConnection()
 {
     lock (_serialPortLock)
     {
         if (_serialPort != null)
         {
             try
             {
                 if (_serialPort.IsOpen)
                 {
                     _log.DebugFormat($"Closing serial port {_config.COMPort}");
                     _serialPort.DiscardOutBuffer();
                     _serialPort.Close();
                 }
                 try
                 {
                     GC.ReRegisterForFinalize(_serialPort.BaseStream);
                 }
                 catch { }
                 _serialPort.Dispose();
             }
             catch (Exception e)
             {
                 _log.Error(e.Message, e);
             }
             _serialPort = null;
         }
         _unsuccessfulConnectionAttempts = 0; //reset unsuccessful connection attempts counter
     }
 }
Пример #4
0
        private async Task Disconnect(bool join)
        {
            Trace.WriteTraceFlush("Disconnecting", join.ToString());
            Aborted = true;
            _serialPortCancellationTokenSource?.Cancel();


            if (join && _readThread != null)
            {
                try
                {
                    _readThread.Abort();
                }
                catch (PlatformNotSupportedException)
                {
                    // ignore
                }
            }
            _readThread = null;

            if (join && _writeThread != null)
            {
                while (!_writeThread.Join(100))
                {
                    _autoEvent.Set();
                }
            }
            _writeThread = null;

            if (_serialPort != null)
            {
                try
                {
                    _serialPort.Close();
                }
                catch (IOException)
                {
                    // ignore exception
                }
                _serialPort.Dispose();
                _serialPortCancellationTokenSource?.Dispose();
                _serialPort = null;
                _serialPortCancellationTokenSource = null;
            }
            Trace.WriteTraceFlush("Disconnected", join.ToString());
        }
Пример #5
0
        protected override void CloseDevice()
        {
            //if opened, set all channels to 0 before closing
            if (m_buff != null)
            {
                Array.Clear(m_buff, m_prefix.Count, m_channels.Count * m_bytes);
                //memset(m_buff + m_prefix.size(), 0, m_channels.size() * m_bytes);
                m_serialport.Write(m_buff, m_buffsize);

                m_buff     = null;
                m_buffsize = 0;
            }

            m_serialport.Dispose();
        }
Пример #6
0
        public bool Close()
        {
            bool rt = false;
            int  errorCode = 0; string errorMsg = "关闭成功";

            try
            {
                if (ISerialPort != null)
                {
                    if (ISerialPort.IsOpen)
                    {
                        ISerialPort.Close();
                        System.Threading.Thread.Sleep(100);
                    }
                    rt = true;
                }
            }
            catch (Exception ex)
            {
                Property.IsConnected = false;
                errorMsg             = ex.Message;
            }
            finally
            {
                if (ClosedEvt != null)
                {
                    System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control;
                    errorCode = 1;
                    errorMsg  = string.Format("串口[{0}]{1}", ISerialPort.PortName, errorMsg);
                    if (target != null && target.InvokeRequired)
                    {
                        //非创建控件线程同步调用事件:SerialPortClosed
                        target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg });
                    }
                    else
                    {
                        //创建控件线程调用事件
                        ClosedEvt(Property, errorCode, errorMsg);
                    }
                }
                if (ISerialPort != null)
                {
                    ISerialPort.Dispose();
                    ISerialPort = null;
                }
            }
            return(rt);
        }
Пример #7
0
        public bool Connect()
        {
            bool rt = false;

            try
            {
                if (ISerialPort != null)
                {
                    if (ISerialPort.IsOpen)
                    {
                        ISerialPort.DataReceived -= SerialPort_DataReceived;
                        ISerialPort.Close();
                        System.Threading.Thread.Sleep(100);
                        ISerialPort.Dispose();
                    }

                    ISerialPort.BaudRate = Property.BaudRate;
                    ISerialPort.Parity   = Property.Parity;
                    ISerialPort.DataBits = Property.DataBits;
                    ISerialPort.StopBits = Property.StopBits;
                    //ISerialPort.ReceivedBytesThreshold = ComSerialPort.ReceivedBytesThreshold;
                    ISerialPort.NewLine       = Property.NewLine;
                    ISerialPort.ReadTimeout   = Property.ReceiveTimeOut;
                    ISerialPort.DtrEnable     = Property.DtrEnable;
                    ISerialPort.RtsEnable     = Property.RtsEnable;
                    ISerialPort.DataReceived += SerialPort_DataReceived;
                    System.AsyncCallback OnConnected = new System.AsyncCallback(ConnectedCallBack);

                    //当完成连接后回调:OnConnected委托
                    ISerialPort.Open();
                    OnConnected(null);
                    rt = true;
                }
            }
            catch (Exception ex) { }
            finally { }
            return(rt);
        }
Пример #8
0
        public bool GetSerialPortByName(string protName)
        {
            bool rt = false;

            try
            {
                if (SerialPortNameList != null &&
                    SerialPortNameList.Length > 0)
                {
                    for (int i = 0; i < SerialPortNameList.Length; i++)
                    {
                        if (protName == SerialPortNameList[i])
                        {
                            ISerialPort = new System.IO.Ports.SerialPort(protName);
                            rt          = true; break;
                        }
                    }
                }

                if (!rt)
                {
                    if (ISerialPort != null)
                    {
                        if (ISerialPort.IsOpen)
                        {
                            ISerialPort.Close();
                        }

                        ISerialPort.Dispose();
                        ISerialPort = null;
                    }
                }
            }
            catch (System.Exception ex)
            {
            }
            return(rt);
        }
Пример #9
0
        static void Main(string[] args)
        {
            //List<SPInstanceBase> SPIs = new List<SPInstanceBase>()
            //{
            //    new SPInstanceBase("COM1","1",delegate(Hex hex,object obj){Console.WriteLine((obj as string)+":"+hex.hexstring); }),
            //    new SPInstanceBase("COM2","2",delegate(Hex hex,object obj){Console.WriteLine((obj as string)+":"+hex.hexstring); }),

            //};
            //for (int i = 0; i < 10; i++)
            //{
            //    SPIs[0].WriteHex("0x01 ab A 0xA".GetHexValue());
            //    Thread.Sleep(500);
            //    SPIs[1].WriteHex("0xAB 0XA B 1".GetHexValue());
            //    Thread.Sleep(500);
            //}
            //Console.Read();

            ISerialPort COM1 = RS232Helper.Create("COM1", null, (str, obj) =>
            {
                Console.Write(str as string);
            });
            ISerialPort COM2 = RS232Helper.Create("COM2", null, (str, obj) =>
            {
                Console.Write(str as string);
            });

            for (int i = 0; i < 10; i++)
            {
                COM1.WriteStr("ABC");
                Thread.Sleep(500);
                COM2.WriteStr("EFG");
                Thread.Sleep(500);
            }
            COM1.Dispose();
            COM2.Dispose();
        }
Пример #10
0
 public void Dispose()
 {
     _serialPort?.Dispose();
 }
Пример #11
0
 public void Dispose()
 {
     _logged.Dispose();
 }