Exemplo n.º 1
0
        private bool DetectBaudRate()
        {
            //Try with 9600 default value
            _port.Open();
            if (TrySendReceive())
            {
                return(true);
            }
            _port.ClearReceiveBuffer();
            _port.Close();

            //Try all known baud rates in descending order
            foreach (int key in BaudLookup.Keys.Reverse())
            {
                _port.BaudRate = key;
                _port.Open();
                if (TrySendReceive())
                {
                    return(true);
                }
                _port.ClearReceiveBuffer();
                _port.Close();
            }
            return(false);
        }
Exemplo n.º 2
0
        private async Task Disconnect(bool join)
        {
            await Task.Delay(5);

            Logger?.LogTrace($"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))
                {
                    await Task.Delay(1);

                    _autoEvent.Set();
                }
            }

            _writeThread = null;

            if (_serialPort != null)
            {
                try
                {
                    _serialPort.Close();
                }
                catch (IOException)
                {
                    // ignore exception
                }

                _serialPortCancellationTokenSource?.Dispose();
                _serialPortScope?.Dispose();
                _serialPort = null;
                _serialPortCancellationTokenSource = null;
            }

            Logger?.LogTrace($"Disconnected: {join.ToString()}");
        }
 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
     }
 }
Exemplo n.º 4
0
 public void Close()
 {
     if (_port != null)
     {
         _port.Close();
     }
 }
Exemplo n.º 5
0
        public async Task Close()
        {
            _cancellationSource.Cancel();

            await _broker;
            await Port.Close();
        }
Exemplo n.º 6
0
 public void Close()
 {
     if (serialPort != null)
     {
         serialPort.Close();
     }
 }
Exemplo n.º 7
0
        public void ReadJson()
        {
            try
            {
                serialPort.Open();
                if (serial.GetPort().IsOpen)
                {
                    var result = json.ReadJson(serialPort);
                    Console.WriteLine(result.SensNr);
                    Console.WriteLine(result.InstNr);
                    Console.WriteLine(result.BRet);

                    /*for (int i = 0; i < json.Data.Count; i++)
                     * {
                     *  Console.WriteLine(result.Data[i]);
                     * }*/
                    Console.WriteLine(result.Data[0]);
                    Console.WriteLine(result.Data[1]);
                }
            }
            finally
            {
                serialPort.Close();
            }
        }
Exemplo n.º 8
0
        public void RunMethod()
        {
            _commands.Clear();
            _protocol = new Protocol(PackageFound);

            while (_shouldRun)
            {
                if (_port.IsOpen)
                {
                    WriteAll();
                    ReadAll();
                }
                else
                {
                    Open();
                    Thread.Sleep(1000);
                }
            }

            _session.Connected = false;
            try
            {
                _port.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine("Serial IO error in closing: {0}", e.Message);
            }
        }
Exemplo n.º 9
0
 /// <summary>
 ///     Close the serial port and stop processing data.
 /// </summary>
 /// <remarks>
 ///     This method clears the buffer and destroys any pending text.
 /// </remarks>
 public void Close()
 {
     if (serialPort.IsOpen)
     {
         serialPort.Close();
     }
     buffer = string.Empty;
 }
Exemplo n.º 10
0
 void CloseComPort()
 {
     if (serialPort != null)
     {
         serialPort.Close();
         serialPort = null;
     }
 }
Exemplo n.º 11
0
 /// <summary>
 ///     Close the serial port and stop processing data.
 /// </summary>
 /// <remarks>
 ///     This method clears the buffer and destroys any pending text.
 /// </remarks>
 public void Close()
 {
     if (serialPort.IsOpen)
     {
         serialPort.Close();
     }
     buffer = "";
 }
Exemplo n.º 12
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());
        }
 public void Close()
 {
     if (port != null)
     {
         port.SetNotify(null);
         port.Close();
         port = null;
     }
 }
Exemplo n.º 14
0
 public void Dispose()
 {
     messageWriteQueue.Dispose();
     _port.DataReceived -= bus_DataReceived;
     if (_port.IsOpen)
     {
         _port.Close();
     }
     _port = null;
 }
Exemplo n.º 15
0
        public void Close()
        {
            Port.Close();

            _eventQueue.CompleteAdding();
            _responseQueue.CompleteAdding();
            _transmitQueue.CompleteAdding();

            _portReadTask.Wait();
            _processEventsTask.Wait();
            _transmitTask.Wait();
        }
Exemplo n.º 16
0
 private void SerialInputWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     while (!stopReading)
     {
         try
         {
             SerialInputWork(Properties.Settings.Default.TestDataFile);
         }
         catch (Exception ex)
         {
             if (ignoreFirstReadError)
             {
                 ignoreFirstReadError = false;
             }
             else
             {
                 AddInfo("Error reading: " + ex.Message);
             }
         }
     }
     serialPort.Close();
 }
Exemplo n.º 17
0
 public void ClosePort(ISerialPort port) // port as argument, Why???
 {
     try
     {
         port.Close();
         port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
         port = null;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
0
 public DrumManager(ISerialPort serialPort)
 {
     if (serialPort == null)
     {
         throw new ArgumentNullException(nameof(serialPort));
     }
     if (serialPort.IsOpen)
     {
         serialPort.Close();
         if (serialPort.IsOpen)
         {
             throw new ArgumentException($"Already connected to device {SerialD.PortName}");
         }
     }
     SerialPort = serialPort;
     Connect();
 }
Exemplo n.º 20
0
 /// <summary>
 /// Close the hardware interface.
 /// </summary>
 public void Close()
 {
     if (serialPort != null)
     {
         //serialPort.DataReceived -= HandleDataReceived
         //serialPort.ErrorReceived -= HanldeErrorReceived;
         try
         {
             //serialPort.Dispose();
             serialPort.Close();
         }
         catch (Exception e)
         {
             logger.Error(e);
         }
         serialPort = null;
     }
 }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        public Dictionary <PropertyKey, int> Connect(InsteonConnection connection)
        {
            if (port != null)
            {
                port.Close();
            }

            port = SerialPortCreator.Create(connection);
            port.Open();

            byte[] input = new byte[] { 0x02, 0x60 };
            Dictionary <PropertyKey, int> properties = new Dictionary <PropertyKey, int>();
            List <byte> response = new List <byte>();

            try
            {
                for (int i = 1; i <= Constants.negotiateRetries; ++i)
                {
                    Log.WriteLine("TX: {0}", Utilities.ByteArrayToString(input));
                    port.Write(input);

                    port.Wait(Constants.openTimeout);
                    byte[] output = port.ReadAll();
                    if (output.Length <= 0)
                    {
                        Thread.Sleep(100);
                        continue; // try again
                    }

                    response.Clear();
                    response.AddRange(output);

                    while (output.Length > 0 && response.Count < 9)
                    {
                        port.Wait(Constants.openTimeout);
                        output = port.ReadAll();
                        response.AddRange(output);
                    }

                    Log.WriteLine("RX: {0}", Utilities.ByteArrayToString(response.ToArray()));

                    int offset = 0;
                    for (int j = 0; j < response.Count; ++j)
                    {
                        if (response[j] == 0x02)
                        {
                            offset = j;
                        }
                    }

                    if (response.Count >= offset + 9 && response[offset] == 0x02 && response[offset + 1] == 0x60 && response[offset + 8] == 0x06)
                    {
                        properties[PropertyKey.Address]         = response[offset + 2] << 16 | response[offset + 3] << 8 | response[offset + 4];
                        properties[PropertyKey.DevCat]          = response[offset + 5];
                        properties[PropertyKey.SubCat]          = response[offset + 6];
                        properties[PropertyKey.FirmwareVersion] = response[offset + 7];
                        break; // found
                    }
                }
            }
            finally
            {
                if (response.Count == 0)
                {
                    throw new IOException("Failed to open port, timeout waiting for response from port.");
                }

                if (properties.Keys.Count == 0)
                {
                    port.Close();
                    port = null;
                    throw new IOException("Failed to open port, unable to negotiate with INSTEON controller.");
                }
            }

            Log.WriteLine("Successfully negotiated with INSTEON controller on connection '{0}'...", connection);
            port.SetNotify(DataAvailable);
            return(properties);
        }
        public Dictionary<PropertyKey, int> Connect(InsteonConnection connection)
        {
            port?.Close();

            port = SerialPortCreator.Create(connection);
            port.Open();

            byte[] input = { Constants.MessageStartByte, (byte)InsteonModemSerialCommand.GetImInfo };
            var properties = new Dictionary<PropertyKey, int>();
            var response = new List<byte>();

            try
            {
                for (int i = 1; i <= Constants.negotiateRetries; ++i)
                {
                    logger.DebugFormat("TX: {0}", Utilities.ByteArrayToString(input));
                    port.Write(input);

                    port.Wait(Constants.openTimeout);
                    var output = port.ReadAll();
                    if (output.Length <= 0)
                    {
                        Thread.Sleep(100);
                        continue; // try again
                    }

                    response.Clear();
                    response.AddRange(output);

                    while (output.Length > 0 && response.Count < 9)
                    {
                        port.Wait(Constants.openTimeout);
                        output = port.ReadAll();
                        response.AddRange(output);
                    }

                    logger.DebugFormat("RX: {0}", Utilities.ByteArrayToString(response.ToArray()));

                    int offset = 0;

                    // determins the start location of the actual message returned
                    for (int j = 0; j < response.Count; ++j)
                    {
                        if (response[j] == Constants.MessageStartByte)
                        {
                            offset = j;
                        }
                    }

                    if (response.Count >= offset + 9 &&
                        response[offset] == Constants.MessageStartByte &&
                        response[offset + 1] == (byte)InsteonModemSerialCommand.GetImInfo &&
                        response[offset + 8] == Constants.MessageEndByte)
                    {
                        properties[PropertyKey.Address] = response[offset + 2] << 16 | response[offset + 3] << 8 | response[offset + 4];
                        properties[PropertyKey.DevCat] = response[offset + 5];
                        properties[PropertyKey.SubCat] = response[offset + 6];
                        properties[PropertyKey.FirmwareVersion] = response[offset + 7];
                        break; // found
                    }
                }
            }
            finally
            {
                if (response.Count == 0)
                {
                    throw new IOException("Failed to open port, timeout waiting for response from port.");
                }

                if (properties.Keys.Count == 0)
                {
                    port.Close();
                    port = null;
                    throw new IOException("Failed to open port, unable to negotiate with INSTEON controller.");
                }
            }

            logger.DebugFormat("Successfully negotiated with INSTEON controller on connection '{0}'...", connection);
            port.SetNotify(DataAvailable);
            return properties;
        }
Exemplo n.º 25
0
 public void Close()
 {
     sp.Close();
 }
Exemplo n.º 26
0
 public void Close()
 {
     _serialPort.Close();
     _serialPort = null;
 }
Exemplo n.º 27
0
    /// <summary>
    /// Finds a printer using the specified serial connection.
    /// </summary>
    /// <returns>
    /// An enumerator for a coroutine.
    /// </returns>
    /// <param name='aSerialPort'>
    /// A serial port connection.
    /// </param>
    IEnumerator FindPrinter(ISerialPort aSerialPort)
    {
        m_foundPrinter = false;
        int timeout = kLoopTimeout;

        while (!aSerialPort.isConnected && timeout-- > 0)
        {
            string[] availablePorts = m_serialPort.AvailablePorts();
            Text.Log(@"Found {0} available port{1}.", availablePorts.Length,
                     Text.S(availablePorts.Length));

            foreach (string aPortPath in availablePorts)
            {
                Text.Log(@"Trying to open {0}", aPortPath);

                bool success = false;
                try {
                    success = aSerialPort.OpenPort(aPortPath, kBaudRate);
                    Text.Log("Opened {0} at {1}.", aPortPath, kBaudRate);
                }
                catch (System.Exception e) {
                    Text.Error(e);
                    continue;
                }

                if (success)
                {
                    // Unity reboots the Propeller on OSX but not on Windows.
                    yield return(StartCoroutine(ResetCoroutine()));

                    // We're in text mode upon startup, so try pinging.
                    aSerialPort.Write("ping ");
                    // Not blocking, so wait a bit.
                    yield return(new UnityEngine.WaitForSeconds(1.0f));                   //0.02f);

                    string response = "(null)";
                    int    numRead  = aSerialPort.Read(8, out response);
                    response = response.Trim();
                    Text.Log("Received {0} byte{1}: {2}", numRead, Text.S(numRead), response);

                    if (response.Contains("pong"))
                    {
                        yield return(StartCoroutine(CheckVersion(aSerialPort)));

                        m_foundPrinter = m_wasProgrammingSuccessful;
                        if (m_foundPrinter)
                        {
                            Text.Log("Connected to " + aPortPath);
                            aSerialPort.Write("data ");

                            m_threadsActive = true;
                            m_txThread      = new Thread(TransmitData);
                            m_txThread.Name = "Tx Thread";
                            m_txThread.Start();

                            m_rxThread      = new Thread(ReceiveData);
                            m_rxThread.Name = "Rx Thread";
                            m_rxThread.Start();

                            Dispatcher.Broadcast(kOnSerialConnectionEstablished);
                        }
                        yield break;
                    }
                    aSerialPort.Close();
                    yield return(null);
                }
            }
            yield return(new WaitForSeconds(1));
        }
        if (timeout <= 0)
        {
            Text.Log(@"Couldn't find printer.");
            enabled = false;
        }
    }
Exemplo n.º 28
0
 public override Task Disable()
 {
     isEnabled = false;
     port.Close();
     return(Task.CompletedTask);
 }
        public Dictionary <PropertyKey, int> Connect(InsteonConnection connection)
        {
            port?.Close();

            port = SerialPortCreator.Create(connection);
            port.Open();

            byte[] input      = { Constants.MessageStartByte, (byte)InsteonModemSerialCommand.GetImInfo };
            var    properties = new Dictionary <PropertyKey, int>();
            var    response   = new List <byte>();

            try
            {
                for (int i = 1; i <= Constants.negotiateRetries; ++i)
                {
                    logger.DebugFormat("TX: {0}", Utilities.ByteArrayToString(input));
                    port.Write(input);

                    port.Wait(Constants.openTimeout);
                    var output = port.ReadAll();
                    if (output.Length <= 0)
                    {
                        Thread.Sleep(100);
                        continue; // try again
                    }

                    response.Clear();
                    response.AddRange(output);

                    while (output.Length > 0 && response.Count < 9)
                    {
                        port.Wait(Constants.openTimeout);
                        output = port.ReadAll();
                        response.AddRange(output);
                    }

                    logger.DebugFormat("RX: {0}", Utilities.ByteArrayToString(response.ToArray()));

                    int offset = 0;

                    // determins the start location of the actual message returned
                    for (int j = 0; j < response.Count; ++j)
                    {
                        if (response[j] == Constants.MessageStartByte)
                        {
                            offset = j;
                        }
                    }

                    if (response.Count >= offset + 9 &&
                        response[offset] == Constants.MessageStartByte &&
                        response[offset + 1] == (byte)InsteonModemSerialCommand.GetImInfo &&
                        response[offset + 8] == Constants.MessageEndByte)
                    {
                        properties[PropertyKey.Address]         = response[offset + 2] << 16 | response[offset + 3] << 8 | response[offset + 4];
                        properties[PropertyKey.DevCat]          = response[offset + 5];
                        properties[PropertyKey.SubCat]          = response[offset + 6];
                        properties[PropertyKey.FirmwareVersion] = response[offset + 7];
                        break; // found
                    }
                }
            }
            finally
            {
                if (response.Count == 0)
                {
                    throw new IOException("Failed to open port, timeout waiting for response from port.");
                }

                if (properties.Keys.Count == 0)
                {
                    port.Close();
                    port = null;
                    throw new IOException("Failed to open port, unable to negotiate with INSTEON controller.");
                }
            }

            logger.DebugFormat("Successfully negotiated with INSTEON controller on connection '{0}'...", connection);
            port.SetNotify(DataAvailable);
            return(properties);
        }
Exemplo n.º 30
0
 public void Close()
 {
     _logged.Close();
     _log.LogTrace("Port is now closed");
 }
Exemplo n.º 31
0
 public void Close() => _serialPort.Close();