// Loop function
        public void Loop()
        {
            // Create command FloatAddition, which will wait for a return command FloatAdditionResult
            var command = new SendCommand((int)Command.FloatAddition, (int)Command.FloatAdditionResult, 1000);

            // Add 2 float command arguments
            var a = 3.14F;
            var b = 2.71F;
            command.AddArgument(a);
            command.AddArgument(b);

            // Send command
            var floatAdditionResultCommand = _cmdMessenger.SendCommand(command);

            // Check if received a (valid) response
            if (floatAdditionResultCommand.Ok)
            {
                // Read returned argument
                var sum = floatAdditionResultCommand.ReadFloatArg();
                var diff = floatAdditionResultCommand.ReadFloatArg();

                // Compare with sum of sent values
                var errorSum  = sum  - (a + b);
                var errorDiff = diff - (a - b);

                Console.WriteLine("Received sum {0}, difference of {1}", sum, diff);
                Console.WriteLine("with errors {0} and {1}, respectively", errorSum, errorDiff);
            }
            else
                Console.WriteLine("No response!");

            // Stop running loop
            RunLoop = false;
        }
        // Setup function
        public void Setup()
        {
            _transport = new SerialTransport {CurrentSerialSettings = {DtrEnable = false}};
            // some boards (e.g. Sparkfun Pro Micro) DtrEnable may need to be true.                        
            // We do not need to set serial port and baud rate: it will be found by the connection manager                                                           

            // Initialize the command messenger with the Serial Port transport layer
            // Set if it is communicating with a 16- or 32-bit Arduino board
            _cmdMessenger = new CmdMessenger(_transport, BoardType.Bit16)
            {
                PrintLfCr = false // Do not print newLine at end of command, to reduce data being sent
            };

            // The Connection manager is capable or storing connection settings, in order to reconnect more quickly  
            // the next time the application is run. You can determine yourself where and how to store the settings
            // by supplying a class, that implements ISerialConnectionStorer. For convenience, CmdMessenger provides
            //  simple binary file storage functionality
            var serialConnectionStorer = new SerialConnectionStorer("SerialConnectionManagerSettings.cfg");

            // We don't need to provide a handler for the Identify command - this is a job for Connection Manager.
            _connectionManager = new SerialConnectionManager(
                _transport as SerialTransport, 
                _cmdMessenger,
                (int) Command.Identify, 
                CommunicationIdentifier,
                serialConnectionStorer)
            {
                // Enable watchdog functionality.
                WatchdogEnabled = true,

                // Instead of scanning for the connected port, you can disable scanning and only try the port set in CurrentSerialSettings
                //DeviceScanEnabled = false
            };

            // Show all connection progress on command line             
            _connectionManager.Progress += (sender, eventArgs) =>
            {
                // If you want to reduce verbosity, you can only show events of level <=2 or ==1
                if (eventArgs.Level <= 3) Console.WriteLine(eventArgs.Description);
            };

            // If connection found, tell the arduino to turn the (internal) led on
            _connectionManager.ConnectionFound += (sender, eventArgs) =>
            {
                // Create command
                var command = new SendCommand((int)Command.TurnLedOn);
                // Send command
                _cmdMessenger.SendCommand(command);
            };

            //You can also do something when the connection is lost
            _connectionManager.ConnectionTimeout += (sender, eventArgs) =>
            {
                //Do something
            };

            // Finally - activate connection manager
            _connectionManager.StartConnectionManager();
        }
示例#3
0
        public void SetLedFrequency(double ledFrequency)
        {
            // Send command to start sending data
            var command = new SendCommand((int)Command.SetLedFrequency,ledFrequency);

            // Send command
            _cmdMessenger.SendCommand(command);
        }
示例#4
0
        // Sent command to change led on/of state
        public void SetLedState(bool ledState)
        {
            // Create command to start sending data
            var command = new SendCommand((int)Command.SetLed, ledState);

            // Send command
            _cmdMessenger.SendCommand(new SendCommand((int)Command.SetLed, ledState));
        }
示例#5
0
        // Loop function
        public void Loop()
        {
            // Create command
            var command = new SendCommand((int)Command.SetLed,_ledState);               

            // Send command
            _cmdMessenger.SendCommand(command);

            // Wait for 1 second and repeat
            Thread.Sleep(1000);
            _ledState = !_ledState;                                        // Toggle led state            
        }
示例#6
0
文件: Serial.cs 项目: robeat101/beakn
 public override void Send(string message)
 {
     try
     {
         var cmd = new SendCommand((int)SerialCommand.SetLed, message);
         var recieve = cmdMessenger.SendCommand(cmd);
         OnSendSuccess(new MessageEventArgs(string.Format("Message Send Success: Id={0}, Message={1}", recieve.RawString, message)));
     }
     catch (Exception e)
     {
         OnSendFailure(new MessageEventArgs("Message Send Failure: " + e.ToString()));
     }
 }
示例#7
0
        // Sent command to change led blinking frequency
        public void SetLedFrequency(double ledFrequency)
        {
            // Create command to start sending data
            var command = new SendCommand((int)Command.SetLedFrequency,ledFrequency);

            // Put the command on the queue and wrap it in a collapse command strategy
            // This strategy will avoid duplicates of this certain command on the queue: if a SetLedFrequency command is
            // already on the queue when a new one is added, it will be replaced at its current queue-position.
            // Otherwise the command will be added to the back of the queue.
            //
            // This will make sure that when the slider raises a lot of events that each send a new blink frequency, the
            // embedded controller will not start lagging.
            _cmdMessenger.QueueCommand(new CollapseCommandStrategy(command));
        }
示例#8
0
        // Loop function
        public void Loop()
        {
            // Create command
            var command = new SendCommand((int)Command.SetLed,_ledState);               

            // Send command
            _cmdMessenger.SendCommand(command);

            Console.Write("Turning led ");
            Console.WriteLine(_ledState?"on":"off");

            // Wait for 1 second and repeat
            Thread.Sleep(1000);
            _ledState = !_ledState;   // Toggle led state            
        }
        /// <summary> Directly executes the send command operation. </summary>
        /// <param name="sendCommand">    The command to sent. </param>
        /// <param name="sendQueueState"> Property to optionally clear the send and receive queues. </param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand ExecuteSendCommand(SendCommand sendCommand, SendQueue sendQueueState)
        {
            // Disable listening, all callbacks are disabled until after command was sent

            ReceivedCommand ackCommand;
            lock (_sendCommandDataLock)
            {

                if (PrintLfCr)
                    _communicationManager.WriteLine(sendCommand.CommandString());
                else
                    _communicationManager.Write(sendCommand.CommandString());
                ackCommand = sendCommand.ReqAc ? BlockedTillReply(sendCommand.AckCmdId, sendCommand.Timeout, sendQueueState) : new ReceivedCommand();
                }
                return ackCommand;
        }
        // Loop function
        public void Loop()
        {
            _count++;

            // Create command
            var command = new SendCommand((int)Command.SetLed,_ledState);               

            // Send command
            _cmdMessenger.SendCommand(command);

            // Wait for 1 second and repeat
            Thread.Sleep(1000);
            _ledState = !_ledState;                                        // Toggle led state  

            if (_count > 100) RunLoop = false;                             // Stop loop after 100 rounds
        }
        // ------------------ MAIN  ----------------------

        // Setup function
        public void Setup(ChartForm chartForm)
        {
           
            // getting the chart control on top of the chart form.
            _chartForm = chartForm;
            
            // Set up chart
            _chartForm.SetupChart();

            // Create Serial Port object
            // Note that for some boards (e.g. Sparkfun Pro Micro) DtrEnable may need to be true.
            _serialTransport = new SerialTransport
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200, DtrEnable = false } // object initializer
            };

            // Initialize the command messenger with the Serial Port transport layer
            // Set if it is communicating with a 16- or 32-bit Arduino board
            _cmdMessenger = new CmdMessenger(_serialTransport, BoardType.Bit16);

            // Tell CmdMessenger to "Invoke" commands on the thread running the WinForms UI
            _cmdMessenger.ControlToInvokeOn = chartForm;

            // Set Received command strategy that removes commands that are older than 1 sec
            _cmdMessenger.AddReceiveCommandStrategy(new StaleGeneralStrategy(1000));

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLinesReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;                       

            // Start listening
            _cmdMessenger.Connect();

            // Send command to start sending data
            var command = new SendCommand((int)Command.StartLogging);

            // Send command
            _cmdMessenger.SendCommand(command);
        }
示例#12
0
        /// <summary> Directly executes the send command operation. </summary>
        /// <param name="sendCommand">    The command to sent. </param>
        /// <param name="sendQueueState"> Property to optionally clear the send and receive queues. </param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand ExecuteSendCommand(SendCommand sendCommand, SendQueue sendQueueState)
        {
            // Disable listening, all callbacks are disabled until after command was sent

            ReceivedCommand ackCommand;

            lock (_sendCommandDataLock)
            {
                sendCommand.CommunicationManager = this;
                sendCommand.InitArguments();

                if (sendCommand.ReqAc)
                {
                    // Stop processing receive queue before sending. Wait until receive queue is actualy done
                    _receiveCommandQueue.Suspend();
                }

                if (sendCommand.ReqAc)
                {
                    _receiveCommandQueue.PrepareForCmd(sendCommand.AckCmdId, sendQueueState);

                    WriteCommand(sendCommand);

                    var rc = BlockedTillReply(sendCommand.Timeout);

                    ackCommand = rc ?? new ReceivedCommand();
                }
                else
                {
                    WriteCommand(sendCommand);
                    ackCommand = new ReceivedCommand();
                }

                ackCommand.CommunicationManager = this;
            }

            if (sendCommand.ReqAc)
            {
                // Stop processing receive queue before sending
                _receiveCommandQueue.Resume();
            }

            return(ackCommand);
        }
示例#13
0
        // ------------------ MAIN  ----------------------

        // Setup function
        public void Setup(ChartForm chartForm)
        {
           
            // getting the chart control on top of the chart form.
            _chartForm = chartForm;
            
            // Set up chart
            _chartForm.SetupChart();

            // Create Serial Port object
            _serialTransport = new SerialTransport
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };

            // Initialize the command messenger with the Serial Port transport layer
            _cmdMessenger = new CmdMessenger(_serialTransport);

            // Tell CmdMessenger to "Invoke" commands on the thread running the WinForms UI
            _cmdMessenger.SetControlToInvokeOn(chartForm);

            // Set Received command strategy that removes commands that are older than 1 sec
            _cmdMessenger.AddReceiveCommandStrategy(new StaleGeneralStrategy(1000));

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLinesReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;                       

            // Start listening
            _cmdMessenger.StartListening();

            // Send command to start sending data
            var command = new SendCommand((int)Command.StartLogging);

            // Send command
            _cmdMessenger.SendCommand(command);
        }
示例#14
0
        /// <summary> Directly executes the send command operation. </summary>
        /// <param name="sendCommand">    The command to sent. </param>
        /// <param name="sendQueueState"> Property to optionally clear the send and receive queues. </param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand ExecuteSendCommand(SendCommand sendCommand, SendQueue sendQueueState)
        {
            // Disable listening, all callbacks are disabled until after command was sent

            ReceivedCommand ackCommand;

            lock (_sendCommandDataLock)
            {
                if (PrintLfCr)
                {
                    _communicationManager.WriteLine(sendCommand.CommandString());
                }
                else
                {
                    _communicationManager.Write(sendCommand.CommandString());
                }
                ackCommand = sendCommand.ReqAc ? BlockedTillReply(sendCommand.AckCmdId, sendCommand.Timeout, sendQueueState) : new ReceivedCommand();
            }
            return(ackCommand);
        }
        private const float SeriesBase = 1111111.111111F;       // Base of values to return: SeriesBase * (0..SeriesLength-1)

        // ------------------ M A I N  ----------------------

        // Setup function
        public void Setup()
        {
            // Create Serial Port object
            _serialTransport = new SerialTransport
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };

            // Initialize the command messenger with the Serial Port transport layer
            _cmdMessenger = new CmdMessenger(_serialTransport);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();                

            // Start listening
            _cmdMessenger.StartListening();

            _receivedPlainTextCount = 0;
            
            // Send command requesting a series of 100 float values send in plain text
            var commandPlainText = new SendCommand((int)Command.RequestPlainTextFloatSeries);
            commandPlainText.AddArgument(SeriesLength);
            commandPlainText.AddArgument(SeriesBase);
            // Send command 
            _cmdMessenger.SendCommand(commandPlainText);

            // Now wait until all values have arrived
            while (!_receivePlainTextFloatSeriesFinished) {}

            // Send command requesting a series of 100 float values send in plain text
            var commandBinary = new SendCommand((int)Command.RequestBinaryFloatSeries);
            commandBinary.AddBinArgument((UInt16)SeriesLength);
            commandBinary.AddBinArgument((Single)SeriesBase); 
            
            // Send command 
            _cmdMessenger.SendCommand(commandBinary);

            // Now wait until all values have arrived
            while (!_receiveBinaryFloatSeriesFinished) { }
        }
示例#16
0
        /// <summary> Directly executes the send command operation. </summary>
        /// <param name="sendCommand">     The command to sent. </param>
        /// <param name="clearQueueState"> Property to optionally clear the send and receive queues. </param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand ExecuteSendCommand(SendCommand sendCommand, ClearQueue clearQueueState)
        {
            // Disable listening, all callbacks are disabled until after command was sent

            lock (_sendCommandDataLock)
            {
                CurrentSentLine = CommandToString(sendCommand);


                if (PrintLfCr)
                {
                    _communicationManager.WriteLine(CurrentSentLine + _commandSeparator);
                }
                else
                {
                    _communicationManager.Write(CurrentSentLine + _commandSeparator);
                }
                InvokeEvent(NewLineSent);
                var ackCommand = sendCommand.ReqAc ? BlockedTillReply(sendCommand.AckCmdId, sendCommand.Timeout, clearQueueState) : new ReceivedCommand();
                return(ackCommand);
            }
        }
 /// <summary> Sends a command. 
 /// 		  If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
 ///  		  If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command 
 ///  		  has been received or the timeout has expired.
 ///  		  Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary>
 /// <param name="sendCommand">       The command to sent. </param>
 /// <param name="sendQueueState">    Property to optionally clear/wait the send queue</param>
 /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param>
 /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
 public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState = SendQueue.InFrontQueue, ReceiveQueue receiveQueueState = ReceiveQueue.Default)
 {
     return SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue);
 }
示例#18
0
 /// <summary> Sends a command. 
 /// 		  If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
 ///  		  If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command 
 ///  		  has been received or the timeout has expired. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public ReceivedCommand SendCommand(SendCommand sendCommand)
 {
     return SendCommand(sendCommand, ClearQueue.KeepQueue);
 }
示例#19
0
 /// <summary> Sends a command.
 ///           If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
 ///           If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command
 ///           has been received or the timeout has expired. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public ReceivedCommand SendCommand(SendCommand sendCommand)
 {
     return(SendCommand(sendCommand, ClearQueue.KeepQueue));
 }
示例#20
0
        // *** Benchmark 1 ***
        private void SetupReceiveSeries()
        {
            Common.StartTest("Calculating speed in receiving series of float data");

            WaitAndClear();

            _receiveSeriesFinished = false;
            _receivedItemsCount = 0;
            _receivedBytesCount = 0;
            _minimalBps = _systemSettings.MinReceiveSpeed;

            // Send command requesting a series of 100 float values send in plain text form
            var commandPlainText = new SendCommand(_command["RequestSeries"]);
            commandPlainText.AddArgument(SeriesLength);
            commandPlainText.AddArgument(SeriesBase);

            // Send command
            _cmdMessenger.SendCommand(commandPlainText);

            // Now wait until all values have arrived
            while (!_receiveSeriesFinished)
            {
                Thread.Sleep(10);
            }
        }
示例#21
0
        // *** Benchmark 3 ***
        private void DirectSendSeries()
        {
            Common.StartTest("Calculating speed in individually sending a series of float data");
            WaitAndClear();

            _minimalBps = _systemSettings.MinDirectSendSpeed;
            _sendSeriesFinished = false;

            var prepareSendSeries = new SendCommand(_command["PrepareSendSeries"]);
            prepareSendSeries.AddArgument(SeriesLength);
            // We need to to send the prepareSendSeries by bypassing the queue or it might be sent after the directly send commands later on
            _cmdMessenger.SendCommand(prepareSendSeries, SendQueue.WaitForEmptyQueue, ReceiveQueue.WaitForEmptyQueue,UseQueue.BypassQueue);

            // Prepare
            _receivedBytesCount = 0;
            _cmdMessenger.PrintLfCr = true;
            _beginTime = Millis;

            // Now send all commands individually and bypass the queue
             for (var sendItemsCount = 0; sendItemsCount < SeriesLength; sendItemsCount++)
            {
                var sendSeries = new SendCommand(_command["SendSeries"]);
                sendSeries.AddArgument(sendItemsCount * SeriesBase);

                _receivedBytesCount += CountBytesInCommand(sendSeries, _cmdMessenger.PrintLfCr);

                _cmdMessenger.SendCommand(sendSeries, SendQueue.Default, ReceiveQueue.Default, UseQueue.BypassQueue);

                if (sendItemsCount%(SeriesLength/10) == 0)
                {
                    Common.WriteLine("Send value: " + sendItemsCount*SeriesBase);
                }
            }
            _endTime = Millis;
            // Now wait until receiving party acknowledges that values have arrived
            while (!_sendSeriesFinished)
            {
                Thread.Sleep(10);
            }
        }
示例#22
0
 /// <summary> Queue the send command. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public void QueueCommand(SendCommand sendCommand)
 {
     QueueCommand(new CommandStrategy(sendCommand));
 }
 /// <summary> Put the command at the back of the sent queue.</summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public void QueueCommand(SendCommand sendCommand)
 {
     _sendCommandQueue.QueueCommand(sendCommand);
 }
        private void ValuePingPongBool(bool value)
        {
            var pingCommand = new SendCommand(_command["ValuePing"], _command["ValuePong"], 1000);
            pingCommand.AddArgument((Int16)DataType.Bool);
            pingCommand.AddArgument(value);
            var pongCommand = _cmdMessenger.SendCommand(pingCommand);

            if (!pongCommand.Ok)
            {
                Common.TestNotOk("No response on ValuePing command");
                return;
            }

            var result = pongCommand.ReadBoolArg();

            if (result == value)
                Common.TestOk("Value as expected");
            else
                Common.TestNotOk("unexpected value received: " + result + " instead of " + value);
        }
示例#25
0
 /// <summary> Sends a command. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 /// <returns> . </returns>
 public ReceivedCommand SendCommand(SendCommand sendCommand)
 {
     return(SendCommand(sendCommand.CmdId, sendCommand.Arguments, sendCommand.ReqAc, sendCommand.AckCmdId,
                        sendCommand.Timeout));
 }
示例#26
0
 /// <summary> Sends a command.
 ///           If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
 ///           If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command
 ///           has been received or the timeout has expired.
 ///           Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary>
 /// <param name="sendCommand">       The command to sent. </param>
 /// <param name="sendQueueState">    Property to optionally clear/wait the send queue</param>
 /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param>
 /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
 public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState = SendQueue.InFrontQueue, ReceiveQueue receiveQueueState = ReceiveQueue.Default)
 {
     return(SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue));
 }
示例#27
0
 /// <summary> Sends a command.
 ///           If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
 ///           If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command
 ///           has been received or the timeout has expired.
 ///           Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary>
 /// <param name="sendCommand">       The command to sent. </param>
 /// <param name="sendQueueState">    Property to optionally clear/wait the send queue</param>
 /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param>
 /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
 public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState)
 {
     return(SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue));
 }
示例#28
0
 /// <summary> Sends a command.
 ///           If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
 ///           If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command
 ///           has been received or the timeout has expired. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public ReceivedCommand SendCommand(SendCommand sendCommand)
 {
     return(SendCommand(sendCommand, SendQueue.InFrontQueue, ReceiveQueue.Default));
 }
        /// <summary> Sends a command. 
        /// 		  If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
        ///  		  If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command 
        ///  		  has been received or the timeout has expired.
        ///  		  Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary>
        /// <param name="sendCommand">       The command to sent. </param>
        /// <param name="sendQueueState">    Property to optionally clear/wait the send queue</param>
        /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param>
        /// <param name="useQueue">          Property to optionally bypass the queue</param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState, UseQueue useQueue)
        {
            var synchronizedSend = (sendCommand.ReqAc || useQueue == UseQueue.BypassQueue);

            // When waiting for an acknowledge, it is typically best to wait for the ReceiveQueue to be empty
            // This is thus the default state
            if (sendCommand.ReqAc && receiveQueueState == ReceiveQueue.Default)
            {
                receiveQueueState = ReceiveQueue.WaitForEmptyQueue;
            }

            if (sendQueueState == SendQueue.ClearQueue )
            {
                // Clear receive queue
                _receiveCommandQueue.Clear(); 
            }

            if (receiveQueueState == ReceiveQueue.ClearQueue )
            {
                // Clear send queue
                _sendCommandQueue.Clear();
            }

            // If synchronized sending, the only way to get command at end of queue is by waiting
            if (sendQueueState == SendQueue.WaitForEmptyQueue ||
                (synchronizedSend && sendQueueState == SendQueue.AtEndQueue)
            )
            {
                SpinWait.SpinUntil(() => _sendCommandQueue.IsEmpty);
            }
            
            if (receiveQueueState == ReceiveQueue.WaitForEmptyQueue)
            {
                SpinWait.SpinUntil(() => _receiveCommandQueue.IsEmpty);
            }

            if (synchronizedSend)
            {
                return SendCommandSync(sendCommand, sendQueueState);
            }
            
            if (sendQueueState != SendQueue.AtEndQueue)
            {
                // Put command at top of command queue
                _sendCommandQueue.SendCommand(sendCommand);
            }
            else
            {
                // Put command at bottom of command queue
                _sendCommandQueue.QueueCommand(sendCommand);
            }
            return new ReceivedCommand { CommunicationManager = _communicationManager };
        }
 /// <summary> Synchronized send a command. </summary>
 /// <param name="sendCommand">    The command to sent. </param>
 /// <param name="sendQueueState"> Property to optionally clear/wait the send queue. </param>
 /// <returns> . </returns>
 public ReceivedCommand SendCommandSync(SendCommand sendCommand, SendQueue sendQueueState)
 {
     // Directly call execute command
     var resultSendCommand = _communicationManager.ExecuteSendCommand(sendCommand, sendQueueState);
     InvokeNewLineEvent(NewLineSent, new CommandEventArgs(sendCommand));
     return resultSendCommand;            
 }
        private void ValuePingPongFloat(float value)
        {
            var pingCommand = new SendCommand(_command["ValuePing"], _command["ValuePong"], 1000);
            pingCommand.AddArgument((Int16)DataType.Float);
            pingCommand.AddArgument(value);
            var pongCommand = _cmdMessenger.SendCommand(pingCommand);

            if (!pongCommand.Ok)
            {
                Common.TestNotOk("No response on ValuePing command");
                return;
            }

            var result = pongCommand.ReadFloatArg();
            var difference = Math.Abs(result - value);
            
            var accuracy = Math.Abs(value * 2e-7);

            if (difference <= accuracy)
                Common.TestOk("Value as expected");
            else
                Common.TestNotOk("unexpected value received: " + result + " instead of " + value);
        }
示例#32
0
 /// <summary> Sends a command. Note that the command is put at the front of the queue </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public void SendCommand(SendCommand sendCommand)
 {
     // Add command to front of queue
     QueueCommand(new TopCommandStrategy(sendCommand));
 }
        private void ValuePingPongDoubleSci(double value, double accuracy)
        {
            var pingCommand = new SendCommand(_command["ValuePing"], _command["ValuePong"], 1000);
            pingCommand.AddArgument((Int16)DataType.DoubleSci);
            pingCommand.AddArgument(value);
            var pongCommand = _cmdMessenger.SendCommand(pingCommand);

            if (!pongCommand.Ok)
            {
                Common.TestNotOk("No response on ValuePing command");
                return;
            }

            var result = pongCommand.ReadDoubleArg();

            var difference = RelativeError(value, result);
            
            if (difference <= accuracy)
                Common.TestOk("Value as expected");
            else
                Common.TestNotOk("unexpected value received: " + result + " instead of " + value);
        }
 /// <summary> Sends a command. </summary>
 /// <param name="sendCommand"> The command to sent. </param>
 /// <returns> . </returns>
 public ReceivedCommand SendCommand(SendCommand sendCommand)
 {
     return SendCommand(sendCommand.CmdId, sendCommand.Arguments, sendCommand.ReqAc, sendCommand.AckCmdId,
                        sendCommand.Timeout);
 }
        public bool MoveMotor(short Channel, short Speed)
        {
            if (!Initialized)
                throw new Exception("Not yet initialized");

            var command = new SendCommand((int)Command.MotorCommand, (int)Command.Acknowledge, 1000);
            command.AddArgument(Channel);
            command.AddArgument(Speed);
            var response = _cmdMessenger.SendCommand(command);
            if (response.Ok)
            {
                var cn = response.ReadInt16Arg();
                var cs = response.ReadInt16Arg();
                Debug.WriteLine(String.Format("Command response - channel={0}; speed={1}", cn, cs));
                if (Channel == cn && Speed == cs)
                {
                    Debug.WriteLine("Alles gut");
                    //OnChannelStateConfirmation(new ChannelStatus(cn, cs));
                    return true;
                }

            }
            return false;
        }
示例#36
0
        // *** Benchmark 2 ***
        // Setup queued send series
        private void SetupQueuedSendSeries()
        {
            Common.StartTest("Calculating speed in sending queued series of float data");
            WaitAndClear();

            _minimalBps = _systemSettings.MinSendSpeed;
            _sendSeriesFinished = false;
            var prepareSendSeries = new SendCommand(_command["PrepareSendSeries"]);
            prepareSendSeries.AddArgument(SeriesLength);
            _cmdMessenger.SendCommand(prepareSendSeries, SendQueue.WaitForEmptyQueue, ReceiveQueue.WaitForEmptyQueue);

            // Prepare
            _receivedBytesCount = 0;
            _cmdMessenger.PrintLfCr = true;
            _beginTime = Millis;

            // Now queue all commands
            for (var sendItemsCount = 0; sendItemsCount < SeriesLength; sendItemsCount++)
            {
                var sendSeries = new SendCommand(_command["SendSeries"]);
                sendSeries.AddArgument(sendItemsCount * SeriesBase);

                _receivedBytesCount += CountBytesInCommand(sendSeries, _cmdMessenger.PrintLfCr);

                _cmdMessenger.QueueCommand(sendSeries);
                if (sendItemsCount % (SeriesLength / 10) == 0)
                    Common.WriteLine("Send value: " + sendItemsCount * SeriesBase);
            }

            // Now wait until receiving party acknowledges that values have arrived
            while (!_sendSeriesFinished)
            {
                Thread.Sleep(10);
            }
        }
示例#37
0
        /// <summary> Directly executes the send command operation. </summary>
        /// <param name="sendCommand">     The command to sent. </param>
        /// <param name="clearQueueState"> Property to optionally clear the send and receive queues. </param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand ExecuteSendCommand(SendCommand sendCommand, ClearQueue clearQueueState)
        {
            // Disable listening, all callbacks are disabled until after command was sent

            lock (_sendCommandDataLock)
            {

                CurrentSentLine = CommandToString(sendCommand);

                if (PrintLfCr)
                    _communicationManager.WriteLine(CurrentSentLine + _commandSeparator);
                else
                {
                    _communicationManager.Write(CurrentSentLine + _commandSeparator);
                }
                InvokeEvent(NewLineSent);
                var ackCommand = sendCommand.ReqAc ? BlockedTillReply(sendCommand.AckCmdId, sendCommand.Timeout, clearQueueState) : new ReceivedCommand();
                return ackCommand;
            }
        }
示例#38
0
        private void WaitAndClear()
        {
            var requestResetCommand = new SendCommand(_command["RequestReset"], _command["RequestResetAcknowledge"], 1000);
            var requestResetAcknowledge = _cmdMessenger.SendCommand(requestResetCommand, SendQueue.ClearQueue,ReceiveQueue.ClearQueue);

            Common.WriteLine(!requestResetAcknowledge.Ok ? "No Wait OK received" : "Wait received");
            // Wait another second to see if
            Thread.Sleep(1000);
            // Clear queues again to be very sure
            _cmdMessenger.ClearReceiveQueue();
            _cmdMessenger.ClearSendQueue();
        }
示例#39
0
        /// <summary> Sends a command. 
        /// 		  If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue
        ///  		  If a  command acknowledge is requested, the command will be send synchronously:  the program will block until the acknowledge command 
        ///  		  has been received or the timeout has expired.
        ///  		  Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary>
        /// <param name="sendCommand"> The command to sent. </param>
        /// <param name="clearQueueState"> Property to optionally clear the send and receive queues</param>
        /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns>
        public ReceivedCommand SendCommand(SendCommand sendCommand, ClearQueue clearQueueState)
        {
            //_sendCommandLogger.LogLine(CommandToString(sendCommand) + _commandSeparator);

            if (clearQueueState == ClearQueue.ClearReceivedQueue ||
                clearQueueState == ClearQueue.ClearSendAndReceivedQueue)
            {
                // Clear receive queue
                _receiveCommandQueue.Clear();
            }

            if (clearQueueState == ClearQueue.ClearSendQueue ||
                clearQueueState == ClearQueue.ClearSendAndReceivedQueue)
            {
                // Clear send queue
                _sendCommandQueue.Clear();
            }

            if (sendCommand.ReqAc)
            {
                // Directly call execute command
                return ExecuteSendCommand(sendCommand, clearQueueState);
            }

            // Put command at top of command queue
            _sendCommandQueue.SendCommand(sendCommand);
            return new ReceivedCommand();
        }
示例#40
0
 /// <summary> Put the command at the back of the sent queue.</summary>
 /// <param name="sendCommand"> The command to sent. </param>
 public void QueueCommand(SendCommand sendCommand)
 {
     _sendCommandQueue.QueueCommand(sendCommand);
 }
        public bool Switch(short ChannelName, bool state)
        {
            if (!Initialized)
                throw new Exception("Not yet initialized");
            OnChannelStateRequest(new ChannelStatus(ChannelName, state));
            var command = new SendCommand((int)Command.SwitchChannel,(int)Command.Acknowledge,1000);
            command.AddArgument(ChannelName);
            command.AddArgument(state);
            var response = _cmdMessenger.SendCommand(command);
            if (response.Ok)
            {
                var cn = response.ReadInt16Arg();
                var cs = response.ReadBoolArg();
                Debug.WriteLine(String.Format("Command response - channelNumber={0}; channelState={1}", cn,cs));
                if (ChannelName == cn && state == cs)
                {
                    OnChannelStateConfirmation(new ChannelStatus(cn, cs));
                    return true;
                }

            }
            return false;
        }