/// <summary>
        /// Tries to connect to the assigned port.
        /// </summary>
        /// <exception cref="IOException">If connecting fails.</exception>
        override public void Connect()
        {
            if (isConnected)
            {
                return;
            }

            arduinoSerial.Open();//Opening the serial port
            arduinoSerial.DataReceived += arduinoSerial_DataReceived;
            isConnected = true;
            ConnectedCallback?.Invoke();
        }
Пример #2
0
        private void CheckConnection()
        {
            runChecker       = true;
            refreshRequested = true;

            while (runChecker)
            {
                if (Monitor.TryEnter(arduinoConnection))
                {
                    try
                    {
                        if (!Send("1000"))
                        {
                            DisconnectedCallback?.Invoke();
                            TryConnect();
                            IsConnected = false;
                        }
                        else
                        {
                            ConnectedCallback?.Invoke();
                            IsConnected = true;
                        }
                    }
                    finally
                    {
                        if (Monitor.IsEntered(arduinoConnection))
                        {
                            Monitor.Exit(arduinoConnection);
                        }
                    }
                }

                int sleeptFor = 0;
                while (++sleeptFor < 2000)
                {
                    if (refreshRequested)
                    {
                        refreshRequested = false;
                        break;
                    }
                    Thread.Sleep(1);
                }
            }
        }
        /// <summary>
        /// 处理连接之后的事件
        /// </summary>
        /// <param name="e"></param>
        private void ProcessConnectHandler(SocketAsyncEventArgs e)
        {
            try
            {
                isConnected = (e.SocketError == SocketError.Success);

                if (isConnected)
                {
                    e.SetBuffer(receiveBuffer, 0, blockSize);
                    if (!clientSocket.ReceiveAsync(e))
                    {
                        ProcessReceiveHandler(e);
                    }
                }

                ConnectedCallback?.Invoke(e.UserToken as SocketToken, isConnected);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }