Exemple #1
0
        // Callback function that prints that the Arduino has experienced an error
        public string Ack()
        {
            SendCommand command = new SendCommand((int)Command.Acknowledge, (int)Command.Acknowledge, 2000);

            rcmd = _cmdMessenger.SendCommand(command);
            if (rcmd.Ok)
            {
            }
            return(status);
            //{
        }
Exemple #2
0
        private string SendCommand(AmazonRequest request, ref AmazonResponse response)
        {
            ReceivedCommand command = ConvertRequestToCommand(request, ref response);
            string          str     = null;

            if (command != null)
            {
                str = senderHelper.PushRemoteCommand(command, null);
            }
            return(str);
        }
        private void OnReceivedCommand(object?sender, ReceiveCommandEventArgs e)
        {
            string content = e.Command;
            int    i       = FindColonCharIndex(content);
            string command = (i == -1) ? content : content.Substring(0, i);
            string args    = (i == -1) ? "" : content.Substring(i + 1);

            App.Current.Dispatcher.BeginInvoke(new Action(
                                                   () => ReceivedCommand?.Invoke(this, new CommandReceivedEventArgs(command, args))
                                                   ));
        }
Exemple #4
0
        private async void OnTempChange(ReceivedCommand receivedCommand)
        {
            int.TryParse(receivedCommand.ReadStringArg(), out int probeIndex);
            decimal.TryParse(receivedCommand.ReadStringArg(), out decimal temp);

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                _eventAggregator.GetEvent <TemperatureResultEvent>().Publish(new TemperatureResult {
                    Index = probeIndex, Value = temp
                });
            });
        }
        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);
        }
Exemple #6
0
        private async void OnHeaterChange(ReceivedCommand receivedCommand)
        {
            int.TryParse(receivedCommand.ReadStringArg(), out int heaterIndex);
            int.TryParse(receivedCommand.ReadStringArg(), out int heaterValue);

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                _eventAggregator.GetEvent <HeaterResultEvent>().Publish(new HeaterResult {
                    Index = heaterIndex, IsEngaged = heaterIndex == 1
                });
            });
        }
Exemple #7
0
        /// <summary>
        /// Raised when acknowledge was received.
        /// </summary>
        /// <param name="arguments">Arguments.</param>
        static void OnAcknowledge(ReceivedCommand arguments)
        {
                        #if DEBUG
            Console.WriteLine(@" Arduino is ready");
                        #endif
            IsConnected = true;
//			if (OnConnectionChanged != null) {
//				OnConnectionChanged.Invoke (null, new ConnectionChangedArgs (true, SerialPortName));
//			}
            LastCommunication = DateTime.Now;
        }
Exemple #8
0
 private int DetermineReceivedCommandLifeTime(ReceivedCommand rec)
 {
     if (rec.Sender is GenericDevice || rec.Sender is Schedule)
     {
         return(3);
     }
     else
     {
         return(Remotes[rec.Sender].CommandLifeTime);
     }
 }
        public ReceivedCommand ConvertIntentToCommand()
        {
            ReceivedCommand command = new ReceivedCommand();

            if (name.EndsWith("FollowUp"))
            {
                command.Remote = name.Substring(0, name.Length - 8);
            }
            else
            {
                command.Remote = name;
            }

            if (command.Remote.Contains("_"))
            {
                string[] splitCommand = command.Remote.Split('_');
                command.Remote  = splitCommand[0];
                command.Command = splitCommand[1];
            }

            string fullVoiceCommand = "<VOICE>";

            if (slots != null)
            {
                command.Parameters = new List <string>();
                foreach (AmazonSlot slot in slots.Values)
                {
                    if (slot.name == "!!PROCESSED")
                    {
                        continue;
                    }

                    if (slot.name.Contains("PAR"))
                    {
                        command.Parameters.Add(slot.value);
                    }
                    else
                    {
                        if (fullVoiceCommand != "<VOICE>")
                        {
                            fullVoiceCommand = fullVoiceCommand += " ";
                        }
                        fullVoiceCommand += slot.value;
                    }
                }
            }
            if (command.Command == null)
            {
                command.Command = fullVoiceCommand;
            }
            return(command);
        }
Exemple #10
0
        private void OnChannelFounded(ReceivedCommand arguments)
        {
            ChannelSearchCompleted = arguments.ReadBinBoolArg();
            if (ChannelSearchCompleted)
            {
                return;
            }
            var channel = new Channels {
                Id = arguments.ReadBinUInt16Arg(), Channel = Channels.Count + 1, Gain = 1
            };

            Channels.Add(channel);
        }
        /// <summary>
        /// Process command. See if it needs to be send to the main thread (false) or be used in queue (true)
        /// </summary>
        public bool ProcessCommand(ReceivedCommand receivedCommand)
        {
            lock (_lock)
            {
                if (receivedCommand.CmdId == _cmdIdToMatch)
                {
                    _receivedCommand = receivedCommand;
                    _waiter.Set();
                    return false;
                }

                return (_sendQueueState != SendQueue.ClearQueue);
            }
        }
        /// <summary>
        /// Process command. See if it needs to be send to the main thread (false) or be used in queue (true)
        /// </summary>
        public bool ProcessCommand(ReceivedCommand receivedCommand)
        {
            lock (_lock)
            {
                if (receivedCommand.CmdId == _cmdIdToMatch)
                {
                    _receivedCommand = receivedCommand;
                    _waiter.Set();
                    return(false);
                }

                return(_sendQueueState != SendQueue.ClearQueue);
            }
        }
Exemple #13
0
        // This handles the client connection. It assumes that the client will send a command and
        // expect a reply. The reply will be a dictionary of serialisable objects.
        private void HandleConnection(object obj)
        {
            Socket workerSocket = obj as Socket;

            // Loop until we are told to stop, either by the ServerSide object
            // or by the client
            while (true)
            {
                // Wait until there is data on the socket
                while (workerSocket.Available == 0 && !mreStop.WaitOne(0, false))
                {
                    // This thread just handles this socket, so it does not matter if it blocks.
                    Thread.Sleep(100);
                }

                // See if we should stop listening
                if (mreStop.WaitOne(0, false))
                {
                    break; // This thread will die
                }

                // Read the command passed by the client and convert it to a string.
                byte[] buffer  = new byte[workerSocket.Available];
                int    count   = workerSocket.Receive(buffer);
                string command = Encoding.ASCII.GetString(buffer, 0, count);

                if (command == "END")
                {
                    // if the client sends an END command stop this thread.
                    break; // This thread will die
                }

                // This object will be filled with results by the handler
                IList <KeyValuePair <string, string> > results = new List <KeyValuePair <string, string> >();
                // Call the handlers, this will block
                ReceivedCommand.Invoke(command, results);

                // Serialize the results, so that they can be returne to the client.
                BinaryFormatter formatter = new BinaryFormatter();
                MemoryStream    stm       = new MemoryStream();
                formatter.Serialize(stm, results);
                byte[] buf = stm.GetBuffer();
                // Send the results back to the client, stm.Length is the number of bytes written
                // into the stream.
                workerSocket.Send(buf, (int)stm.Length, SocketFlags.None);
                // Loop, and wait for the client to send another command.
            }

            CleanUp(workerSocket);
        }
Exemple #14
0
 private void CleanUpCommandQueue(object source, ElapsedEventArgs e)
 {
     lock (commandQueue) {
         for (int i = 0; i < commandQueue.Count; i++)
         {
             ReceivedCommand recCommand = commandQueue[i];
             if ((e.SignalTime - recCommand.TimeReceived).TotalSeconds >= DetermineReceivedCommandLifeTime(recCommand))
             {
                 commandQueue.Remove(recCommand);
                 i++;
             }
         }
     }
 }
Exemple #15
0
        /// <summary>
        /// Handles the event for the model changed sent by the Fixture Manager via Serial Communication Port
        /// </summary>
        /// <param name="command"></param>
        private void OnModelChanged(ReceivedCommand command)
        {
            int tempFixture;

            tempFixture = int.Parse(command.ReadStringArg());
            if (tempFixture != fixture || fixture == NO_FIXTURE)
            {
                fixture = tempFixture;
                if (FixtureChanged != null)
                {
                    FixtureChanged(fixture);
                }
            }
            SendSelectionCommand();
        }
Exemple #16
0
        public string PushRemoteCommand(ReceivedCommand command, Controller controller)
        {
            if (command == null && controller != null)
            {
                return(null);
            }

            object[] parameters = null;
            if (command.Parameters != null)
            {
                parameters = ConvertParametersToRealObjects(command.Parameters);
            }

            return(commandSrvProxy.SendCommand(command.Remote, command.Command, parameters));;
        }
        // Callback function that prints that the Arduino has acknowledged
        void OnAcknowledge(ReceivedCommand arguments)
        {
            var output = arguments.ReadStringArg();

            if (string.IsNullOrWhiteSpace(output))
            {
                return;
            }
            // _controllerForm.SetCamMsgText(output);

            const string s = @" ACK ";

            Console.WriteLine(s);
            _controllerForm.SetMsgText(s + output);
        }
        // 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);
        }
        private ReceivedCommand DequeueCommandInternal()
        {
            ReceivedCommand receivedCommand = null;

            if (!IsEmpty)
            {
                foreach (var generalStrategy in GeneralStrategies)
                {
                    generalStrategy.OnDequeue();
                }
                var commandStrategy = Queue.Dequeue();
                receivedCommand = (ReceivedCommand)commandStrategy.Command;
            }
            return(receivedCommand);
        }
Exemple #20
0
        /// <summary>
        /// Wait function.
        /// </summary>
        /// <param name="timeOut">time-out in ms</param>
        /// <param name="cmdId"></param>
        /// <param name="sendQueueState"></param>
        /// <returns></returns>
        public ReceivedCommand WaitForCmd(int timeOut, int cmdId, SendQueue sendQueueState)
        {
            lock (_lock)
            {
                _receivedCommand = null;
                _cmdIdToMatch    = cmdId;
                _sendQueueState  = sendQueueState;
            }

            if (_waiter.WaitOne(timeOut) == EventWaiter.WaitState.TimeOut)
            {
                return(null);
            }

            return(_receivedCommand);
        }
        /// <summary>
        /// Wait function. 
        /// </summary>
        /// <param name="timeOut">time-out in ms</param>
        /// <param name="cmdId"></param>
        /// <param name="sendQueueState"></param>
        /// <returns></returns>
        public ReceivedCommand WaitForCmd(int timeOut, int cmdId, SendQueue sendQueueState)
        {
            lock (_lock)
            {
                _receivedCommand = null;
                _cmdIdToMatch = cmdId;
                _sendQueueState = sendQueueState;
            }

            if (_waiter.WaitOne(timeOut) == EventWaiter.WaitState.TimeOut)
            {
                return null;
            }

            return _receivedCommand;
        }
Exemple #22
0
 public void ReceiveCommand(ReceivedCommand command)
 {
     if (command.Command == VmmCommands.CommandArray)
     {
         //コマンドの一括送信を受け取ったとき: バラバラにしてキューに詰めておく
         var commands = CommandArrayParser.ParseCommandArray(command.Content);
         foreach (var c in commands)
         {
             _receivedCommands.Enqueue(c);
         }
     }
     else
     {
         //普通の受信
         _receivedCommands.Enqueue(command);
     }
 }
        private void OnAckSendSeries(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);
            }


            Common.EndTest();
            _sendSeriesFinished = true;
        }
Exemple #24
0
        public void SendPrintCommand(UInt16 box, UInt16 to_feed)
        {
            Console.WriteLine("Sending Print command to box {0} and feed {1}", box, to_feed);
            // Send the command, wait for 1s for the the acknowledge command
            SendCommand command = new SendCommand((int)Command.Print, (int)Command.AcknowledgePrint, 1000);

            command.AddArgument(box);
            command.AddArgument(to_feed);

            ReceivedCommand rec_command = _cmdMessenger.SendCommand(command);

            var unique_id = rec_command.ReadUInt16Arg();

            box     = rec_command.ReadUInt16Arg();
            to_feed = rec_command.ReadUInt16Arg();

            Console.WriteLine("Acknowledge Print command with unique id {0} to box {1} and feed {2}", unique_id, box, to_feed);
        }
        /// <summary> Dequeue the received command. </summary>
        /// <returns> The received command. </returns>
        public ReceivedCommand DequeueCommand()
        {
            ReceivedCommand receivedCommand = null;

            lock (Queue)
            {
                if (Queue.Count != 0)
                {
                    foreach (var generalStrategy in GeneralStrategies)
                    {
                        generalStrategy.OnDequeue();
                    }
                    var commandStrategy = Queue.Dequeue();
                    receivedCommand = (ReceivedCommand)commandStrategy.Command;
                }
            }
            return(receivedCommand);
        }
Exemple #26
0
        public string Move(int mov)
        {
            tl.LogMessage("Transmitting", "");
            SendCommand command = new SendCommand((int)Command.Move, (int)Command.Acknowledge, 2000);

            command.AddArgument(mov);
            rcmd = _cmdMessenger.SendCommand(command);
            if (rcmd.Ok)
            {
                tl.LogMessage("Transmit", "true");
                System.Threading.Thread.Sleep(mov);
            }
            else
            {
                tl.LogMessage("Transmit", "false");
            }

            return(status);
        }
Exemple #27
0
        // Callback function To receive the binary float series from the Arduino
        void OnReceiveBinaryFloatSeries(ReceivedCommand arguments)
        {
            var count         = arguments.ReadBinUInt16Arg();
            var receivedValue = arguments.ReadBinFloatArg();

            _receivedBytesCount += CountBytesInCommand(arguments, false);

            if (count != _receivedItemsCount)
            {
                Console.WriteLine("Values not matching: received {0} expected {1}", count, _receivedItemsCount);
            }

            if (_receivedItemsCount % (SeriesLength / 10) == 0)
            {
                Console.WriteLine("Received value: {0}", receivedValue);
            }
            if (_receivedItemsCount == 0)
            {
                // Received first value, start stopwatch
                _beginTime = Millis;
            }
            else if (count == 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
                                  );
                _receiveBinaryFloatSeriesFinished = true;
            }
            _receivedItemsCount++;
        }
        public void Update(int data)
        {
            if (_data == data)
            {
                return;
            }
            _data = (byte)data;
            // Prepare command
            var command = new SendCommand((int)EnumOperationTypes.LedOutput);

            command.AddArgument(_id);
            command.AddArgument(_data);
            ReceivedCommand resultCommand = _cmdMessenger.SendCommand(command);

            if (!resultCommand.Ok)
            {
                // Log
            }
        }
 // Callback function To receive the binary float series from the Arduino
 void OnReceiveBinaryFloatSeries(ReceivedCommand arguments)
 {
     if (_receivedBinaryCount % (SeriesLength / 10) == 0)
     {
         Console.WriteLine("Received value: {0}", arguments.ReadBinFloatArg());
     }
     if (_receivedBinaryCount == 0)
     {
         // Received first value, start stopwatch
         _beginTime = Millis;
     }
     else if (_receivedBinaryCount == 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);
         _receiveBinaryFloatSeriesFinished = true;
     }
     _receivedBinaryCount++;
 }
Exemple #30
0
        // 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)
        {
            // Plot data if we are accepting data
            if (!AcceptData)
            {
                return;
            }

            // Get all arguments from plot data point command
            var time = arguments.ReadBinFloatArg();

            time = (TimeUtils.Millis - _startTime) / 1000.0f;
            var currTemp    = arguments.ReadBinFloatArg();
            var goalTemp    = arguments.ReadBinFloatArg();
            var heaterValue = arguments.ReadBinFloatArg();
            var heaterPwm   = arguments.ReadBinBoolArg();

            // Update chart with new data point;
            _chartForm.UpdateGraph(time, currTemp, goalTemp, heaterValue, heaterPwm);
        }
        private void ToggleInputReceived(ReceivedCommand receivedcommand)
        {
            short id = receivedcommand.ReadInt16Arg();

            switch (id)
            {
            case 0:
                SendControlToFS(Pmdg737Events.EVT_MCP_FD_SWITCH_L, PmdgParameters.MOUSE_FLAG_LEFTSINGLE);
                SendControlToFS(Pmdg737Events.EVT_MCP_FD_SWITCH_R, PmdgParameters.MOUSE_FLAG_LEFTSINGLE);
                break;

            case 1:
                SendControlToFS(Pmdg737Events.EVT_MCP_AT_ARM_SWITCH, PmdgParameters.MOUSE_FLAG_LEFTSINGLE);
                break;

            case 2:
                SendControlToFS(Pmdg737Events.EVT_MCP_DISENGAGE_BAR, PmdgParameters.MOUSE_FLAG_LEFTSINGLE);
                break;
            }
        }
Exemple #32
0
        public void SendConnectCommand(UInt16 box_id)
        {
            Console.WriteLine("Sending Connect command with unique id {0}", box_id);

            // Send the command, wait for 1s for the the acknowledge command
            SendCommand command = new SendCommand((int)Command.Connect, box_id, (int)Command.AcknowledgeConnect, 1000);

            _cmdMessenger.SendCommand(command);

            ReceivedCommand rec_command = _cmdMessenger.SendCommand(command);

            if (rec_command.Ok)
            {
                var unique_id = rec_command.ReadUInt16Arg();

                Console.WriteLine("Acknowledge Connect command with unique id {0}", unique_id);
            }
            else
            {
                Console.WriteLine("Bad messages");
            }
        }
 /// <summary> Queue the received command. </summary>
 /// <param name="receivedCommand"> The received command. </param>
 public void QueueCommand(ReceivedCommand receivedCommand)
 {
     QueueCommand(new CommandStrategy(receivedCommand));
 }