private void ProcessMessageInBuffer()
        {
            Console.WriteLine("Command received. Deserializing..");

            // stop the timer
            m_rxTimeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);

            // we've finished the packet
            TestCommand c = null;

            try
            {
                c = Serializer?.Deserialize(m_buffer);
                Console.WriteLine("done.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to deserialize: {ex.Message}");
            }

            if (c != null)
            {
                CommandReceived?.Invoke(this, c);
            }

            m_buffer = null;
            m_header.Clear();
        }
Ejemplo n.º 2
0
        public void AddCommandListener <TR>(CommandReceived <TR> callback, IChannel channel)
        {
            IRTCallback rtCallback = new RTCallback <TR>(callback, result =>
            {
                try
                {
                    Command <TR> command = new Command <TR>();

                    UserInfo userInfo = new UserInfo();

                    command.UserInfo = userInfo;

                    userInfo.ConnectionId = WeborbSerializationHelper.AsString(result, "connectionId");
                    userInfo.UserId       = WeborbSerializationHelper.AsString(result, "userId");

                    command.Type = WeborbSerializationHelper.AsString(result, "type");

                    IAdaptingType data = WeborbSerializationHelper.AsAdaptingType(result, "data");

                    command.Data = (TR)data.adapt(typeof(TR));
                    callback(command);
                }
                catch (System.Exception e)
                {
                    channel.ErrorHandler?.Invoke(RTErrorType.COMMAND, new BackendlessFault(e));
                }
            }, fault =>
            {
                channel.ErrorHandler?.Invoke(RTErrorType.COMMAND, fault);
            });

            AddCommandListener(rtCallback);
        }
Ejemplo n.º 3
0
        private async Task HandleCommand <TCommand>(CommandReceived <TCommand> commandHandler, IConsumeContext <TCommand> context)
            where TCommand : class, ICommand
        {
            CommandMessage <TCommand> message = _options.ContextManager.CreateCommandMessage(context);

            _logger.LogVerbose(new { commandType = typeof(TCommand).FullName, correlationId = message.CorrelationId, retryCount = context.RetryCount, command = message.Command.ToString() },
                               arg => $"Received command of type {arg.commandType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Command: {arg.command}");

            try
            {
                await commandHandler.Invoke(message).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(new { commandType = typeof(TCommand).FullName, correlationId = message.CorrelationId, retryCount = context.RetryCount, command = context.Message.ToString() }, ex,
                                 (arg, e) => $"Error while processing event of type {arg.commandType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Command: {arg.command}. Error: {e.Message}");

                var handled = await _options.CommandErrorStrategy.HandleError(context, ex).ConfigureAwait(false);

                if (!handled)
                {
                    throw ExceptionManager.PrepareForRethrow(ex);
                }
            }
        }
Ejemplo n.º 4
0
        private void Receive()
        {
            while (!closeConnection)
            {
                try
                {
                    int b;
                    while ((b = stream.ReadByte()) != -1 && !closeConnection)
                    {
                        char c = (char)b;

                        if (c == '\n')
                        {
                            CommandReceived?.Invoke(new CommandReceivedEventArgs(pendingCommand.TrimEnd('\r')));
                            pendingCommand = string.Empty;
                        }
                        else
                        {
                            pendingCommand += c;
                        }
                    }
                }
                catch
                {
                    if (!closeConnection)
                    {
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private void DataReceive()
        {
            while (Tcp?.Connected ?? false)
            {
                try {
                    byte message = Reader.ReadByte();
                    switch (message)
                    {
                    case READY_BYTE:
                        Writer.Write(READY_BYTE);
                        break;

                    case COMMAND_BYTE:
                        byte command       = Reader.ReadByte();
                        byte processNumber = Reader.ReadByte();
                        CommandReceived?.Invoke(this, new Message <byte>(command, processNumber));
                        break;

                    case TEXT_BYTE:
                        string text = Reader.ReadString();
                        processNumber = Reader.ReadByte();
                        TextReceived?.Invoke(this, new Message <string>(text, processNumber));
                        break;
                    }
                }
                catch {
                    Connected = false;
                    return;
                }
            }
            Connected = false;
        }
Ejemplo n.º 6
0
        private async void Listen()
        {
            try
            {
                using (var serverStream = GetServerStream())
                {
                    await Task.Factory.FromAsync(
                        (cb, state) => serverStream.BeginWaitForConnection(cb, state),
                        ar => serverStream.EndWaitForConnection(ar),
                        null);

                    var command = ParseCommand(serverStream.ReadByte());

                    CommandReceived?.Invoke(this, new IpcEventArgs(command));

                    serverStream.Disconnect();
                }

                Listen();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to listen for IPC commands");
            }
        }
Ejemplo n.º 7
0
 public void ProcessMessage(Message message)
 {
     if (message.Content.StartsWith("!"))
     {
         string[] arguments = message.Content.Substring(1).Split(' ');
         CommandReceived?.Invoke(this, new StreamCommand
         {
             Service   = DiscordConstants.Service,
             Channel   = Key,
             User      = message.Author.Username,
             Command   = arguments[0],
             Arguments = arguments.Skip(1).ToArray()
         });
     }
     else
     {
         ChatMessage?.Invoke(this, new ChatMessage
         {
             Service      = DiscordConstants.Service,
             Channel      = Key,
             User         = message.Author.Username,
             AvatarLink   = message.Author.Avatar != null ? DataExtensions.GetAvatarURL(message.Author.ID, message.Author.Avatar) : null,
             Message      = message.Content,
             Emotes       = new ChatEmote[0],
             Attachements = ProcessAttachements(message.Attachments).ToArray(),
             IsWhisper    = false,
             UserColor    = Colors.White
         });
     }
 }
Ejemplo n.º 8
0
 public void Register()
 {
     if (++countModels == 2 && client.Connected)
     {
         Task t = new Task(() =>
         {
             Mutex mut = new Mutex();
             while (true)
             {
                 string JCommand = reader.ReadString();
                 CommandRecievedEventArgs command = CommandRecievedEventArgs.FromJSON(JCommand);
                 if (command.CommandID == (int)CommandEnum.CloseClientCommand)
                 {
                     client.Close();
                     break;
                 }
                 mut.WaitOne();
                 CommandReceived?.Invoke(this, command);
                 mut.ReleaseMutex();
             }
         }
                           );
         t.Start();
     }
 }
Ejemplo n.º 9
0
        private async void CloudToDeviceAsync()
        {
            while (true)
            {
                try {
                    Message receivedMessage = await deviceClient.ReceiveAsync();

                    if (receivedMessage == null)
                    {
                        await Task.Delay(2000);

                        continue;
                    }

                    await deviceClient.CompleteAsync(receivedMessage);

                    string command = Encoding.ASCII.GetString(receivedMessage.GetBytes());

                    if (telemetry.SetSampleRateInSeconds(command))
                    {
                        continue;
                    }

                    T cmd = (T)Convert.ChangeType(command, typeof(T));

                    CommandReceived?.Invoke(this, new CommandEventArgs <T>(cmd));
                }
                catch { telemetry.Exceptions++; }
            }
        }
Ejemplo n.º 10
0
        protected virtual void OnCommandReceived(SystemCommandModel theCmd)
        {
            SystemCommandEnum theEnum;

            Enum.TryParse(theCmd.Name, true, out theEnum);

            if (theEnum == SystemCommandEnum.None)
            {
                return;
            }

            var paramList = new List <KeyValuePair <string, object> >();

            paramList.Add(new KeyValuePair <string, object>("targetId", theCmd.TargetId));
            if (theCmd.NewPreference.HasValue)
            {
                paramList.Add(new KeyValuePair <string, object>("preference", theCmd.NewPreference));
            }

            CommandReceived?.Invoke(this, new CommandReceivedEventArgs
            {
                Command    = theEnum,
                Parameters = paramList
            });
        }
Ejemplo n.º 11
0
 protected virtual void OnCommandReceived(VoiceCommand command)
 {
     CommandReceived?.Invoke(this, new VoiceCommandControllerEventArgs()
     {
         Data = command
     });
 }
Ejemplo n.º 12
0
 private void ListenData(Connection connection)
 {
     while (true)
     {
         try
         {
             var data = connection.TransferProtocol.Read();
             if (data.Type == TrasnsferDataType.Command)
             {
                 _logger.LogMessage("Command received from " + connection.Id + " " + connection.Name);
                 CommandReceived?.Invoke(connection.Id, (CommandTrasnsferData)data);
             }
             else if (data.Type == TrasnsferDataType.DataObject)
             {
                 _logger.LogMessage("Data received from " + connection.Id + " " + connection.Name);
                 DataReceived?.Invoke(connection.Id, (ObjectTrasnsferData)data);
             }
             else
             {
                 _logger.LogMessage("File received from " + connection.Id + " " + connection.Name);
                 FileReceived?.Invoke(connection.Id, (FileTransferData)data);
             }
         }
         catch (Exception ex)
         {
             _logger.LogError("Disconected: " + connection.Id + " " + connection.Name + " Error connection: " + ex.Message);
             Disconect(connection);
             return;
         }
     }
 }
Ejemplo n.º 13
0
        private static async Task DiscordClient_MessageReceived(SocketMessage msg)
        {
            if (!msg.Content.StartsWith("!")) //Ignore message if it doesn't start with the command specifier "!"
            {
                return;
            }

            string[] splitmsg = msg.Content.Substring(1).Split(' ');

            if (splitmsg.Length == 0) //If the message is just an exclamation mark don't bother
            {
                return;
            }

            List <string> args = new List <string>();

            for (int i = 1; i < splitmsg.Length; i++)
            {
                args.Add(splitmsg[i]);
            }

            CommandReceived?.Invoke(new CommandReceivedEventArgs()
            {
                Command     = splitmsg[0],
                CommandArgs = args.ToArray(),
                Channel     = msg.Channel,
                User        = msg.Author
            });
        }
Ejemplo n.º 14
0
 protected virtual void OnCommandReceived(string commandName, string userName)
 {
     CommandReceived?.Invoke(this, new CommandReceivedEventArgs()
     {
         CommandName = commandName, Username = userName
     });
 }
Ejemplo n.º 15
0
        private async Task ReadLoop()
        {
            while (!_cancellationTokenSource.IsCancellationRequested && _pipe.IsConnected)
            {
                byte[] buffer = ArrayPool <byte> .Shared.Rent(_pipe.InBufferSize);

                int position = 0;
                do
                {
                    position += await _pipe.ReadAsync(buffer.AsMemory(position), _cancellationTokenSource.Token);
                } while (!_pipe.IsMessageComplete);

                if (position == 0)
                {
                    //I don't know why, but this happens when closing the pipe.
                    //return the buffer to the pool and skip the rest
                    ArrayPool <byte> .Shared.Return(buffer);

                    continue;
                }

                var dataLength = (int)BitConverter.ToUInt32(buffer, 0);
                var actualData = buffer.AsMemory(4, dataLength - 4);

                CommandReceived?.Invoke(this, actualData);

                ArrayPool <byte> .Shared.Return(buffer);
            }
            await _pipe.DisposeAsync();

            Disconnected?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 16
0
 private void OnCommandReceived(byte value)
 {
     if (CommandReceived != null)
     {
         CommandReceived.Invoke(value);
     }
 }
Ejemplo n.º 17
0
        protected virtual void OnCommandReceived(CommandEventArgs e)
#endif
        {
            if (CommandReceived != null)
            {
                CommandReceived.Invoke(this, e);
            }
        }
        public void SubscribeToCommand <TCommand>(CommandReceived <TCommand> commandReceived) where TCommand : class, ICommand
        {
            if (commandReceived == null)
            {
                throw new ArgumentNullException(nameof(commandReceived));
            }

            _commandSubscriptions.Add(configurator => configurator.Handler <TCommand>(ctx => HandleCommand(commandReceived, ctx)));
        }
Ejemplo n.º 19
0
        private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DebugHelper.LogInformation($"Connection received from {args.Socket.Information.RemoteAddress.DisplayName}:{args.Socket.Information.RemotePort}");

            string passkey = SecretManager.EncryptionKey; //Passkey used for this session.

            try
            {
                using (var reader = new DataReader(args.Socket.InputStream))
                {
                    using (var writer = new DataWriter(args.Socket.OutputStream))
                    {
                        reader.InputStreamOptions = InputStreamOptions.Partial;
                        try
                        {
                            var networkCommand = await ReceiveCommand(reader, passkey);

                            //if (networkCommand == null) break;
                            if (networkCommand == null)
                            {
                                await SendResponse(Command.CreateErrorCommand($"The command was null."), writer, passkey);

                                return;
                            }

                            CommandEventArgs commandArgs = new CommandEventArgs()
                            {
                                InputCommand = networkCommand
                            };

                            //Send command
                            await CommandReceived?.Invoke(commandArgs);

                            //If output command retrieve, send it
                            if (commandArgs.OutputCommand != null)
                            {
                                await SendResponse(commandArgs.OutputCommand, writer, passkey);
                            }
                        }
                        catch (Exception loopException)
                        {
                            await SendResponse(Command.CreateErrorCommand($"Error handling request: {loopException.Message}"), writer, passkey);
                        }
                        DebugHelper.LogInformation($"Connection from {args.Socket.Information.RemoteAddress.DisplayName}:{args.Socket.Information.RemotePort} ended");
                        if (args.Socket != null)
                        {
                            args.Socket.Dispose();
                            DebugHelper.LogVerbose("Socket disposed.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error handling request: {e.Message}");
            }
        }
Ejemplo n.º 20
0
        private async Task <bool> RaiseCommandReceivedAsync(Command envelope)
        {
            var eventArgs = new EnvelopeEventArgs <Command>(envelope);

            CommandReceived?.RaiseEvent(this, eventArgs);
            await eventArgs.WaitForDeferralsAsync().ConfigureAwait(false);

            return(true);
        }
Ejemplo n.º 21
0
        private async Task OnCommandReceived(object source, IrcCommandEventArgs args)
        {
            if (CommandReceived == null)
            {
                return;
            }

            await CommandReceived.Invoke(source, args);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// New API Request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DebugHelper.LogInformation($"Connection received from {args.Socket.Information.RemoteAddress.DisplayName}:{args.Socket.Information.RemotePort}");

            try
            {
                using (var reader = new DataReader(args.Socket.InputStream))
                {
                    using (var writer = new DataWriter(args.Socket.OutputStream))
                    {
                        reader.InputStreamOptions = InputStreamOptions.Partial;
                        try
                        {
                            Tuple <Command, HttpStatusCode> commandAndStatus = await ReceiveCommand(reader);

                            Command command = commandAndStatus.Item1;
                            if (command == null)
                            {
                                await SendResponse(Command.CreateErrorCommand($"The command was null."), writer, false, HttpStatusCode.BadRequest);

                                return;
                            }
                            if (command.BaseCommand == CommandsEnum.ResultError)
                            {
                                await SendResponse(command, writer, false, commandAndStatus.Item2);

                                return;
                            }

                            //Send command
                            CommandEventArgs commandArgs = new CommandEventArgs()
                            {
                                InputCommand = command
                            };
                            await CommandReceived?.Invoke(commandArgs);

                            //If output command retrieve, send it
                            if (commandArgs.OutputCommand != null)
                            {
                                await SendResponse(commandArgs.OutputCommand, writer, SecretManager.IsEncryptionEnabled);
                            }
                        }
                        catch (Exception loopException)
                        {
                            await SendResponse(Command.CreateErrorCommand($"Error handling request: {loopException.Message}"), writer, false, HttpStatusCode.InternalServerError);
                        }

                        DebugHelper.LogInformation($"Connection from {args.Socket.Information.RemoteAddress.DisplayName}:{args.Socket.Information.RemotePort} ended");
                    }
                }
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error handling request: {e.Message}");
            }
        }
Ejemplo n.º 23
0
        private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var         s = com.ReadLine();
            CommandInfo c = new CommandInfo();

            c.command = StringToEnum(s.Substring(0, 3));
            c.p       = Convert.ToInt32(s.Substring(3, 2));
            c.v       = s.Substring(5);
            CommandReceived?.Invoke(this, c);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Invokes the CommandReceived event and passes the appropriate args to the subscribed Objects.
        /// </summary>
        /// <param name="id">CommandEnum the code for the specific command</param>
        /// <param name="args">List<String> the args used by the Command</param>
        /// <param name="path">String, the target directory/file path</param>
        public void SendCommand(CommandEnum id, List <String> args, string path)
        {
            CommandReceivedEventArgs cArgs = new CommandReceivedEventArgs(id, args, path);

            CommandReceived?.Invoke(this, cArgs);
            if (id == CommandEnum.CloseServerCommand)
            {
                OnCloseServer();
            }
        }
 private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     while (_serialPort.BytesToRead > 0)
     {
         var command = _serialPort.ReadLine();
         _logger.Information($"RCV: {command}");
         command = command.Replace("\r", string.Empty);
         CommandReceived?.Invoke(command);
     }
 }
Ejemplo n.º 26
0
        public override void HandleCommand(TestCommand command)
        {
            Console.WriteLine("[{0}] Command {1} received in {2} [ms]", Key, command.Id, (DateTime.UtcNow - command.CreatedAt).TotalMilliseconds);

            Interlocked.Increment(ref _receivedMessages);

            if (_receivedMessages == _expectedMessages)
            {
                CommandReceived.Complete(true);
            }
        }
Ejemplo n.º 27
0
        /// Runs a command.
        /// <inheritdoc/>
        public override Dialogue.HandlerExecutionType RunCommand(Yarn.Command command, System.Action onCommandComplete)
        {
            // Dispatch this command via the 'On Command' handler.
            CommandReceived?.Invoke(command.Text);

            // Signal to the DialogueRunner that it should continue
            // executing. (This implementation of RunCommand always signals
            // that execution should continue, and never calls
            // onCommandComplete.)
            return(Dialogue.HandlerExecutionType.ContinueExecution);
        }
Ejemplo n.º 28
0
 private void CommandExecutorService_MessageRecieved(object sender, CommandReceived commandReceived)
 {
     if (InvokeRequired)
     {
         Invoke((MethodInvoker)(() => CommandExecutorService_MessageRecieved(sender, commandReceived)));
     }
     else
     {
         dataTable.Rows.Add(DateTime.Now, commandReceived.Type, commandReceived.Message);
         dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0];
     }
 }
Ejemplo n.º 29
0
        private void HandleCommandEvent(TelloCommand command)
        {
            ICommandReader reader =
                commandReaders.SingleOrDefault(t => t.Id == command.Id);
            IEventCommand evt = reader?.Read(command);

            if (evt == null)
            {
                return;
            }
            CommandReceived?.Invoke(this, evt);
        }
Ejemplo n.º 30
0
        public async Task HandleCommand <TCommand>(CommandMessage <TCommand> message) where TCommand : class, ICommand
        {
            Delegate @delegate;

            if (!_subscribedCommands.TryGetValue(typeof(TCommand), out @delegate))
            {
                return;
            }

            CommandReceived <TCommand> commandReceivedDelegate = (CommandReceived <TCommand>)@delegate;

            await commandReceivedDelegate(message).ConfigureAwait(false);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Occurs when the service is started
        /// </summary>
        protected override void OnStart(string[] args)
        {
            try
            {
                // hookup the command event
                eventReceivedCommand += new CommandReceived(IrcBotService_eventReceivedCommand);

                connect();

                CreateThreads(1, workerFunc);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error when starting: " + ex.Message);
            }
        }
Ejemplo n.º 32
0
 public void AddCommandListener(CommandReceived call)
 {
     OnCommandReceived += call;
 }