protected virtual bool ValidateDeviceUniqueId(ReceivedCommand responseCommand) { bool valid = _uniqueDeviceId == responseCommand.ReadStringArg(); if (!valid) { Log(3, "Invalid device response. Device ID mismatch."); } return(valid); }
/// <summary> Blocks until acknowlegdement reply has been received. </summary> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowlegde command. </param> /// <returns> . </returns> private ReceivedCommand BlockedTillReply(int ackCmdId, int timeout) { // Disable listening, all callbacks are disabled until reply was received var start = TimeUtils.Millis; var time = start; var acknowledgeCommand = new ReceivedCommand(); while ((time - start < timeout) && !acknowledgeCommand.Ok) { time = TimeUtils.Millis; acknowledgeCommand = CheckForAcknowledge(ackCmdId); } return(acknowledgeCommand); }
/// <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); }
/// <summary> Blocks until acknowlegdement reply has been received. </summary> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowlegde command. </param> /// <param name="clearQueueState"></param> /// <returns> . </returns> private ReceivedCommand BlockedTillReply(int ackCmdId, int timeout, ClearQueue clearQueueState) { // Disable invoking command callbacks _receiveCommandQueue.ThreadRunState = CommandQueue.ThreadRunStates.Stop; var start = TimeUtils.Millis; var time = start; var acknowledgeCommand = new ReceivedCommand(); while ((time - start < timeout) && !acknowledgeCommand.Ok) { time = TimeUtils.Millis; acknowledgeCommand = CheckForAcknowledge(ackCmdId, clearQueueState); } // Re-enable invoking command callbacks _receiveCommandQueue.ThreadRunState = CommandQueue.ThreadRunStates.Start; return(acknowledgeCommand); }
/// <summary> Sends a command. </summary> /// <param name="cmdId"> Command ID. </param> /// <param name="arguments"> The arguments. </param> /// <param name="reqAc"> true to request acknowledge command. </param> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowlegde command. </param> /// <returns> . </returns> public ReceivedCommand SendCommand(int cmdId, string[] arguments, bool reqAc, int ackCmdId, int timeout) { // Disable listening, all callbacks are disabled until after command was sent // Var lock can result in deadlocks, instead we do a soft enforcement of synced sent/receive order var synced = Monitor.TryEnter(_processSerialDataLock, 100); try { _communications.NewLineReceived -= NewSerialDataReceived; CurrentSentLine = cmdId.ToString(CultureInfo.InvariantCulture); foreach (var argument in arguments) { CurrentSentLine += _fieldSeparator + argument; } if (PrintLfCr) { _communications.WriteLine(CurrentSentLine + _commandSeparator); } else { _communications.Write(CurrentSentLine + _commandSeparator); } InvokeEvent(NewLineSent); ReceivedCommand ackCommand = reqAc ? BlockedTillReply(ackCmdId, timeout) : new ReceivedCommand(); _communications.NewLineReceived += NewSerialDataReceived; return(ackCommand); } finally { if (synced) { Monitor.Exit(_processSerialDataLock); } } }
// ------------------ C A L L B A C K S --------------------- // Called when a received command has no attached function. void OnUnknownCommand(ReceivedCommand arguments) { Console.WriteLine("Command without attached callback received"); }
/// <summary> Handle message. </summary> /// <param name="receivedCommand"> The received command. </param> public void HandleMessage(ReceivedCommand receivedCommand) { MessengerCallbackFunction callback = null; //var commandId = -1; //ReceivedCommand receivedCommand; if (receivedCommand.Ok) { //receivedCommand = new ReceivedCommand(commandString); if (_callbackList.ContainsKey(receivedCommand.CommandId)) { callback = _callbackList[receivedCommand.CommandId]; } else { if (_defaultCallback != null) callback = _defaultCallback; } } else { // Empty command receivedCommand = new ReceivedCommand(); } InvokeCallBack(callback, receivedCommand); }
/// <summary> Handle message. </summary> /// <param name="receivedCommand"> The received command. </param> private void HandleMessage(ReceivedCommand receivedCommand) { MessengerCallbackFunction callback = null; if (receivedCommand.Ok) { if (_callbackList.ContainsKey(receivedCommand.CmdId)) { callback = _callbackList[receivedCommand.CmdId]; } else { if (_defaultCallback != null) callback = _defaultCallback; } } else { // Empty command receivedCommand = new ReceivedCommand { CommunicationManager = _communicationManager }; } InvokeCallBack(callback, receivedCommand); }
// Callback function that plots a data point for ADC 1 and ADC 2 private void OnPlotDataPoint(ReceivedCommand arguments) { var time = arguments.ReadFloatArg(); var analog1 = arguments.ReadFloatArg(); var analog2 = arguments.ReadFloatArg(); _chartForm.UpdateGraph(time, analog1, analog2); }
// Callback function that prints that the Arduino has acknowledged void OnAcknowledge(ReceivedCommand arguments) { Console.WriteLine(@" Arduino is ready"); }
private void UnknownCommand(ReceivedCommand args) { throw new NotSupportedException(Properties.Resources.UnknownCommand); }
private void OnUnknownCommand(ReceivedCommand receivedCommand) { Debug.WriteLine("Unknown command"); OnErrorEvent("Error > Unknown command"); }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { if (messengerCallbackFunction == null) { return; } messengerCallbackFunction(command); }
private void OnAcknowledge(ReceivedCommand receivedCommand) { Debug.WriteLine(receivedCommand.CommandString()); //var a = receivedCommand.ReadInt16Arg(); //var b = receivedCommand.ReadBoolArg(); //Debug.WriteLine(String.Format("channel number: {0}, status {1}", a,b)); }
private void OnError(ReceivedCommand receivedCommand) { Debug.WriteLine(String.Format("Error > {0}", receivedCommand.CommandString())); OnErrorEvent(String.Format("Error > {0}", receivedCommand.CommandString())); }
void OnButton1(ReceivedCommand arguments) { //Thread.Sleep(1000); Debug.Log("Arduino Button1: "); // test = arguments.ReadInt32Arg(); // Debug.Log(test); // var cmd_return = new SendCommand((int)Command.SetLed); // _cmdMessenger.SendCommand(cmd_return); }
void OnUnknownCommand(ReceivedCommand arguments) { Debug.Log("Command without attached callback received"); }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { if (messengerCallbackFunction == null || (ControlToInvokeOn != null && ControlToInvokeOn.IsDisposed)) { return; } if (ControlToInvokeOn != null) { //Asynchronously call on UI thread try { ControlToInvokeOn.BeginInvoke(new MessengerCallbackFunction(messengerCallbackFunction), (object)command); } catch { } } else { //Directly call try { messengerCallbackFunction.BeginInvoke(command, null, null); } catch { } } }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { if (messengerCallbackFunction != null) { if (_controlToInvokeOn != null && _controlToInvokeOn.InvokeRequired) { //Asynchronously call on UI thread _controlToInvokeOn.Invoke(new MessengerCallbackFunction(messengerCallbackFunction), (object) command); } else { //Directly call messengerCallbackFunction(command); } } }
private void OnWatchdog(ReceivedCommand receivedCommand) { Debug.WriteLine(String.Format("Watchdog > {0}", receivedCommand.CommandString())); }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { if (messengerCallbackFunction == null) return; //Directly call messengerCallbackFunction(command); }
/// <summary> Handle message. </summary> /// <param name="receivedCommand"> The received command. </param> public void HandleMessage(ReceivedCommand receivedCommand) { CurrentReceivedLine = receivedCommand.rawString; // Send message that a new line has been received and is due to be processed InvokeEvent(NewLineReceived); MessengerCallbackFunction callback = null; if (receivedCommand.Ok) { //receivedCommand = new ReceivedCommand(commandString); if (_callbackList.ContainsKey(receivedCommand.CmdId)) { callback = _callbackList[receivedCommand.CmdId]; } else { if (_defaultCallback != null) callback = _defaultCallback; } } else { // Empty command receivedCommand = new ReceivedCommand(); } InvokeCallBack(callback, receivedCommand); }
// Callback function that prints the Arduino status to the console void OnStatus(ReceivedCommand arguments) { Console.Write("Arduino status: "); Console.WriteLine(arguments.ReadStringArg()); }
/// <summary> Blocks until acknowlegdement reply has been received. </summary> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowlegde command. </param> /// <param name="clearQueueState"></param> /// <returns> . </returns> private ReceivedCommand BlockedTillReply(int ackCmdId, int timeout, ClearQueue clearQueueState) { // Disable invoking command callbacks _receiveCommandQueue.ThreadRunState = CommandQueue.ThreadRunStates.Stop; var start = TimeUtils.Millis; var time = start; var acknowledgeCommand = new ReceivedCommand(); while ((time - start < timeout) && !acknowledgeCommand.Ok) { time = TimeUtils.Millis; acknowledgeCommand = CheckForAcknowledge(ackCmdId, clearQueueState); } // Re-enable invoking command callbacks _receiveCommandQueue.ThreadRunState = CommandQueue.ThreadRunStates.Start; return acknowledgeCommand; }
// Callback function that prints that the Arduino has experienced an error void OnError(ReceivedCommand arguments) { Console.WriteLine(@"Arduino has experienced an error"); }
public void TestSendCommandWithAcknowledgementByArduinoFinished(ReceivedCommand command) { var result = command.ReadBoolArg(); if (!result) { Common.TestNotOk("Incorrect response"); } _acknowledgementByEmbeddedFinished = true; }
// Callback function that plots a data point for the current temperature, the goal temperature, // the heater steer value and the Pulse Width Modulated (PWM) value. private void OnPlotDataPoint(ReceivedCommand arguments) { var time = arguments.ReadBinFloatArg(); var currTemp = arguments.ReadBinFloatArg(); var goalTemp = arguments.ReadBinFloatArg(); var heaterValue = arguments.ReadBinFloatArg(); var heaterPwm = arguments.ReadBinBoolArg(); _chartForm.UpdateGraph(time, currTemp, goalTemp, heaterValue, heaterPwm); }
// ------------------ Command Callbacks ------------------------- private void OnAreYouReadyCommand(ReceivedCommand arguments) { // In response to AreYouReady ping. We send an ACK acknowledgment to say that we are ready _cmdMessenger.SendCommand(new SendCommand(_command["Ack"], "We are ready")); }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { if (messengerCallbackFunction == null || (ControlToInvokeOn != null && ControlToInvokeOn.IsDisposed)) return; if (ControlToInvokeOn != null) { //Asynchronously call on UI thread ControlToInvokeOn.BeginInvoke(new MessengerCallbackFunction(messengerCallbackFunction), (object)command); } else { //Directly call messengerCallbackFunction(command); } }
private void OnYouAreReadyCommand(ReceivedCommand arguments) { // in response to YouAreReady message TestSendCommandWithAcknowledgementByArduinoFinished(arguments); }
// Callback function To receive the plain text float series from the Arduino void OnReceivePlainTextFloatSeries(ReceivedCommand arguments) { if (_receivedPlainTextCount % 100 == 0) Console.WriteLine("Received value: {0}",arguments.ReadFloatArg()); if (_receivedPlainTextCount == 0) { // Received first value, start stopwatch _beginTime = Millis; } else if (_receivedPlainTextCount == SeriesLength - 1) { // Received all values, stop stopwatch _endTime = Millis; Console.WriteLine("{0} milliseconds per {1} items = is {2} ms/item", _endTime - _beginTime, SeriesLength, (_endTime - _beginTime) / (float)SeriesLength); _receivePlainTextFloatSeriesFinished = true; } _receivedPlainTextCount++; }
// Callback function To receive the plain text float series from the Arduino void OnReceiveSeries(ReceivedCommand arguments) { if (_receivedItemsCount % (SeriesLength / 10) == 0) Common.WriteLine(_receivedItemsCount+ " Received value: " + arguments.ReadFloatArg()); if (_receivedItemsCount == 0) { // Received first value, start stopwatch _beginTime = Millis; } _receivedItemsCount++; _receivedBytesCount += CountBytesInCommand(arguments, false); }
public static void OnUnknownCommand(ReceivedCommand arguments) { // In response to unknown commands and corrupt messages WriteLine(IdentWn + "Warn > Command without attached callback received"); }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { messengerCallbackFunction?.Invoke(command); }
/// <summary> Blocks until acknowlegdement reply has been received. </summary> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowlegde command. </param> /// <returns> . </returns> private ReceivedCommand BlockedTillReply(int ackCmdId, int timeout) { // Disable listening, all callbacks are disabled until reply was received var start = TimeUtils.Millis; var time = start; var acknowledgeCommand = new ReceivedCommand(); while ((time - start < timeout) && !acknowledgeCommand.Ok) { time = TimeUtils.Millis; acknowledgeCommand = CheckForAcknowledge(ackCmdId); } return acknowledgeCommand; }
/// <summary> Helper function to Invoke or directly call callback function. </summary> /// <param name="messengerCallbackFunction"> The messenger callback function. </param> /// <param name="command"> The command. </param> private void InvokeCallBack(MessengerCallbackFunction messengerCallbackFunction, ReceivedCommand command) { try { if (messengerCallbackFunction == null) { return; } if (_controlToInvokeOn != null && _controlToInvokeOn.InvokeRequired) { //Asynchronously call on UI thread _controlToInvokeOn.Invoke(new MessengerCallbackFunction(messengerCallbackFunction), (object)command); } else { //Directly call messengerCallbackFunction(command); } } catch (Exception) { } }
private void OnDoneReceiveSeries(ReceivedCommand receivedcommand) { float bps = CalcTransferSpeed(); if (bps > _minimalBps) { Common.TestOk("Embedded system is receiving data as fast as expected. Measured: " + bps + " bps, expected " + _minimalBps); } else { Common.TestNotOk("Embedded system is receiving data not as fast as expected. Measured: " + bps + " bps, expected " + _minimalBps); } _receiveSeriesFinished = true; Common.EndTest(); }
private void OnResponseCommandId(ReceivedCommand arguments) { // Do nothing. }
// Called when a RequestResetAcknowledge comes in private void OnRequestResetAcknowledge(ReceivedCommand receivedcommand) { // This function should not be called because OnRequestResetAcknowledge should // be handled by the requestResetAcknowledge synchronous command in WaitAndClear() // if it happens, we will do another WaitAndClear() and hope that works WaitAndClear(); }
// Callback function To receive the plain text float series from the Arduino void OnReceivePlainTextFloatSeries(ReceivedCommand arguments) { _receivedBytesCount += CountBytesInCommand(arguments, true); if (_receivedItemsCount % (SeriesLength/10) == 0) Console.WriteLine("Received value: {0}",arguments.ReadFloatArg()); if (_receivedItemsCount == 0) { // Received first value, start stopwatch _beginTime = Millis; } else if (_receivedItemsCount == SeriesLength - 1) { // Received all values, stop stopwatch _endTime = Millis; var deltaTime = (_endTime - _beginTime); Console.WriteLine("{0} milliseconds per {1} items = is {2} ms/item, {3} Hz", deltaTime, SeriesLength, (float)deltaTime / (float)SeriesLength, (float)1000 * SeriesLength / (float)deltaTime ); Console.WriteLine("{0} milliseconds per {1} bytes = is {2} ms/byte, {3} bytes/sec, {4} bps", deltaTime, _receivedBytesCount, (float)deltaTime / (float)_receivedBytesCount, (float)1000 * _receivedBytesCount / (float)deltaTime, (float)8 * 1000 * _receivedBytesCount / (float)deltaTime ); _receivePlainTextFloatSeriesFinished = true; } _receivedItemsCount++; }