Пример #1
0
        private async void ReceiveData()
        {
            while (!_performClose)
            {
                try
                {
                    var incomingValue = _port.ReadByte();
                    Console.WriteLine("Channel > Incoming: " + incomingValue);
                    if (incomingValue == Constants.MESSAGE_START_BYTE)
                    {
                        //start byte received. construct message
                        var length = _port.ReadByte();
                        await Task.Delay(10);

                        var messageBytes = new byte[length];
                        messageBytes[0] = (byte)incomingValue;
                        messageBytes[1] = (byte)length;
                        await Task.Delay(10);

                        _port.Read(messageBytes, 2, messageBytes.Length - 2);
                        var message = new ArduinoMessage();
                        message.FromBytes(messageBytes);

                        //continue if the message is invalid
                        if (!message.IsValid)
                        {
                            Console.WriteLine("Channel > Received INVALID Message!");
                            continue;
                        }

                        //process the message, either send received handler or continue awaited message
                        ProcessReceivedMessage(message);
                    }
                }
                catch (InvalidOperationException)
                {
                    Debug.WriteLine("Channel > Connection closed. Arduino USB cable removed?");
                    break;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Channel > Exception while receiving data!");
                }

                await Task.Delay(10);
            }

            //reset close flag
            _performClose = false;
        }