Beispiel #1
0
        public Task <t> AddToQueue <t>(Func <Task <t> > Action)
        {
            t         Result = default;
            Exception TaskEx = null;
            var       Done   = new Task <t>(() => {
                if (TaskEx != null)
                {
                    throw TaskEx;
                }
                return(Result);
            });
            Func <Task> Waiter = async() =>
            {
                try
                {
                    Result = await Action();

                    Done.Start();
                }
                catch (Exception ex)
                {
                    TaskEx = ex;
                    Done.Start();
                }
            };

            lock (this)
            {
                TaskQueue.Insert(Waiter);
                OnCommand?.Invoke();
            }
            return(Done);
        }
 public async void ExecuteCommand(string cmd)
 {
     if (cts == null)
     {
         cts = new CancellationTokenSource();
         if (History.LastOrDefault() != cmd)
         {
             History.Add(cmd);
         }
         histPtr = History.Count;
         args    = new CMDArgs(cmd);
         args.CancellationToken        = cts.Token;
         args.OutputStream.OnRecieved += (object s, EventArgs a) =>
         {
             if (s is ConsoleStream cs)
             {
                 this.Invoke(new Action(() => { this.AppendText(cs.ReadAll()); }));
             }
         };
         Task t = new Task(() => { OnCommand?.Invoke(this, args); });
         AppendText("\r\n");
         t.Start();
         await t;
         t.Dispose();
         cts.Dispose();
         cts = null;
         AppendText("\r\n");
         Start();
     }
 }
Beispiel #3
0
 /// <summary>Processes the command message.</summary>
 /// <param name="cmdMsg">The command MSG.</param>
 public void ProcessCommandMessage(ObjectCommandEnvelope cmdMsg)
 {
     if (OnCommand != null)
     {
         OnCommand.Invoke(cmdMsg);
     }
 }
Beispiel #4
0
        public void Flush()
        {
            if (_rawCommand != null)
            {
                var rawCommand = _rawCommand;
                rawCommand.TraceMessage = _traceMessage.ToString();
                _traceMessage.Clear();

                try
                {
                    var parsedCommand = _parser.Parse(rawCommand);
                    OnCommand?.Invoke(this, parsedCommand);
                }
                catch (Exception ex)
                {
                    if (OnError != null)
                    {
                        OnError.Invoke(this, ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Beispiel #5
0
 public void SendCommand(Client destination, Command command)
 {
     if (OnCommand != null)
     {
         OnCommand.Invoke(destination, command);
     }
 }
Beispiel #6
0
 public void ProcessCommand(RdsCommand command)
 {
     foreach (var f in features)
     {
         f.ProcessCommand(this, command);
     }
     OnCommand?.Invoke(this, command);
 }
Beispiel #7
0
 private void Update()
 {
     foreach (var command in commandList)
     {
         OnCommand?.Invoke(command);
     }
     commandList.Clear();
 }
Beispiel #8
0
        internal static void InvokeCommand(string text)
        {
            MessageArgs args = new MessageArgs()
            {
                Text = text
            };

            OnCommand?.Invoke(args);
        }
Beispiel #9
0
 public void Dispose()
 {
     lock (this)
     {
         if (Disposed == false)
         {
             Disposed = true;
             OnCommand?.Invoke();
         }
     }
 }
Beispiel #10
0
        private void ProcessRequestAsync(HttpListenerContext context)
        {
            new Thread(() => {
                var req = context.Request;

                if (req.HttpMethod.Equals("get", StringComparison.OrdinalIgnoreCase))
                {
                    if (!req.QueryString.HasKeys())
                    {
                        using (var sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
                        {
                            context.Response.StatusCode  = 200;
                            context.Response.ContentType = " text/html; charset=utf-8";
                            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "CommandServer\\StaticContent\\index.html");

                            // DebugLogger.Log(filePath);

                            if (File.Exists(filePath))
                            {
                                sw.Write(File.ReadAllText(filePath));
                            }
                            return;
                        }
                    }
                }

                if (req.HttpMethod.Equals("post", StringComparison.OrdinalIgnoreCase))
                {
                    string content;
                    using (var sr = new StreamReader(req.InputStream, Encoding.UTF8))
                    {
                        content = sr.ReadToEnd();
                    }
                    using (var sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
                    {
                        context.Response.StatusCode = 200;
                        sw.Write($"Команда принята: {content}");
                    }
                    OnCommand?.Invoke(this, new CommandEventArgs(content));
                    return;
                }
                ;
                using (var sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
                {
                    context.Response.StatusCode = 404;
                    sw.Write($"Че-то не понял");
                }
            })
            .Start();
        }
Beispiel #11
0
 private void OnReceived(object sender, BasicDeliverEventArgs e)
 {
     try
     {
         // TODO Check Header["message_type"] == typeof(T).AssemblyQualifiedName
         var message = Encoding.UTF8.GetString(e.Body.ToArray());
         var command = JsonSerializer.Deserialize <T>(message);
         OnCommand?.Invoke(command);
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
     }
 }
        private void CheckForKeys(Event _event)
        {
            if (allowEnterKey && (chatInputField.Trim().Length > 0) && EnterPressed(_event))
            {
                string message = chatInputField.Trim();

                chatInputField             = "";
                allowEnterKey              = false;
                GUIUtility.keyboardControl = 0;

                if (message.StartsWith(VRCTools.ModPrefs.GetString(prefSection, "cmdprefix")))
                {
                    Utils.Log("OnCommand " + message);
                    OnCommand?.Invoke(new ChatCommand(message));
                }
                else
                {
                    Utils.Log("OnMessage " + message);
                    object Sender;
                    if (APIUser.CurrentUser is null)
                    {
                        Sender = "You";
                    }
                    else
                    {
                        Sender = APIUser.CurrentUser;
                    }
                    var msg = new ChatMessage(content: message, timestamp: DateTime.Now, sender: Sender);
#if UNITY_EDITOR
                    HandleMessage(msg, DateTime.Now, "Me");
#else
                    HandleMessage(msg);
#endif
                    OnMessage?.Invoke(msg);
                }
            }
            else
            {
                allowEnterKey = GUI.GetNameOfFocusedControl() == "chatInputField";
            }

            if (allowEnterKey && Event.current.keyCode == KeyCode.Escape)
            {
                GUIUtility.keyboardControl = 0;
            }
        }
        private void MonitorMethod()
        {
            while (true)
            {
                var Api    = Helper.Api;
                var server = Api.Groups.GetLongPollServer(_groupId);
                var poll   = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams()
                {
                    Server = server.Server,
                    Key    = server.Key,
                    Ts     = server.Ts,
                    Wait   = 25
                });

                if (poll?.Updates == null)
                {
                    continue;
                }
                foreach (var e in poll.Updates)
                {
                    if (e.Type == GroupUpdateType.MessageNew)
                    {
                        if (e.Message.Text.IndexOf("/") == 0)
                        {
                            var inputString = e.Message.Text.Trim().ToLower();
                            var StrCmdList  = inputString.Split('"').Select((element, index) => index % 2 == 0 ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) : new string[] { element }).SelectMany(element => element).ToList();
                            var CmdName     = StrCmdList[0];
                            StrCmdList.Remove(CmdName);
                            var res = Commands.GetCommand(CmdName.Remove(0, 1));
                            if (res != null)
                            {
                                OnCommand?.Invoke(this, new CommandEventArgs(e.Message, res, inputString, StrCmdList.ToArray()));
                            }
                            else
                            {
                                OnCommandNotFound?.Invoke(this, new CommandEventArgs(e.Message, res, inputString, StrCmdList.ToArray()));
                            }
                            break;
                        }
                        NewMessage?.Invoke(this, new NewMessageEventArgs(e.Message));
                        break;
                    }
                }
            }
        }
Beispiel #14
0
        public static void InvokeCommand(ref string query, ref CommandSender sender, ref bool allow)
        {
            OnCommand adminCommandEvent = RemoteAdminCommandEvent;

            if (adminCommandEvent == null)
            {
                return;
            }

            RACommandEvent ev = new RACommandEvent()
            {
                Allow   = allow,
                Command = query,
                Sender  = sender
            };

            adminCommandEvent?.Invoke(ref ev);
            query  = ev.Command;
            sender = ev.Sender;
            allow  = ev.Allow;
        }
Beispiel #15
0
        public async Task LockWrite(Func <Task> Action)
        {
            var         Done   = AsyncTaskMethodBuilder.Create();
            Func <Task> Waiter = async() =>
            {
                try
                {
                    await Action();
                }
                finally
                {
                    Done.SetResult();
                }
            };

            lock (this)
            {
                WriteQueue.Insert(Waiter);
                OnCommand?.Invoke();
            }
            await Done.Task;
        }
Beispiel #16
0
    /// <summary>
    /// Called when a message is received from service
    /// </summary>
    /// <param name="message"></param>
    public void Onmessagereceive(string message)
    {
        Debug.LogError("message received : " + message);
        FromService msg = JsonUtility.FromJson <FromService>(message);

        if (msg.command == constant.CMD_LOAD_SESSION)
        {
            sendReady();
            onReady.Invoke(msg.parameters);
        }
        else if (msg.command == constant.CMD_START_SESSION)
        {
            onStart.Invoke();
        }
        else if (msg.command == constant.CMD_STOP_SESSION)
        {
            onStop.Invoke();
        }
        else if (msg.command == constant.CMD_COMMAND_SESSION)
        {
            onCommand.Invoke(msg.parameters);
        }
    }
Beispiel #17
0
 public void HandleCommand(string command, string[] arguments) => OnCommand?.Invoke(command, arguments);
 public void Command(CommandEventArgs e) => OnCommand?.Invoke(this, e);
Beispiel #19
0
 public void FireCommand(object command)
 {
     OnCommand?.Invoke(command);
 }
 public CommandResult Execute(CommandContext command)
 {
     return(OnCommand.Invoke(command));
 }
Beispiel #21
0
        public void Run()
        {
            while (IsRunning)
            {
                if (!string.IsNullOrWhiteSpace(Prompt))
                {
                    console.Write(Level.None, Prompt);
                }

                while (IsRunning)
                {
                    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                    char           keyChar = keyInfo.KeyChar;


                    if (keyInfo.Key == ConsoleKey.Enter)
                    {
                        break;
                    }


                    switch (keyInfo.Key)
                    {
                    case ConsoleKey.Backspace:
                        if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
                        {
                            Clear();
                        }
                        else
                        {
                            Backspace();
                        }
                        break;

                    case ConsoleKey.Delete:
                        if (MoveCaretRight())
                        {
                            Backspace();
                        }
                        break;

                    case ConsoleKey.UpArrow:
                        ShowHistory(-1);
                        break;

                    case ConsoleKey.DownArrow:
                        ShowHistory(1);
                        break;

                    case ConsoleKey.LeftArrow:
                        MoveCaretLeft();
                        break;

                    case ConsoleKey.RightArrow:
                        MoveCaretRight();
                        break;

                    case ConsoleKey.Tab:
                        AttemptAutocomplete();
                        break;

                    default:
                        if (char.IsWhiteSpace(keyChar) || char.IsPunctuation(keyChar) || char.IsSymbol(keyChar) || char.IsLetterOrDigit(keyChar))
                        {
                            InsertChar(keyChar);
                        }
                        break;
                    }
                }

                console.WriteLine(Level.None);

                string cmd = sb.ToString().Trim();
                if (!string.IsNullOrWhiteSpace(cmd))
                {
                    commandHistory.Add(cmd);
                }
                historyIndex = commandHistory.Count;

                if (commandHistory.Count > MaxCommandHistory)
                {
                    commandHistory.RemoveAt(0);
                }

                OnCommand?.Invoke(this, cmd);

                sb.Clear();
                caretIndex = 0;
            }
        }
Beispiel #22
0
 internal static void InvokeOnCommand(Command cmd)
 {
     OnCommand?.Invoke(cmd);
 }
Beispiel #23
0
 internal static void RunCommand(string command) => OnCommand?.Invoke(command);
Beispiel #24
0
 internal void OnAssetState(AssetState state)
 {
     State = state;
     OnCommand?.Invoke(this, this);
 }
        private void HandleReceiveBuffer2(Socket socket)
        {
            // TODO - Refactor HandleReceiveBuffer2

            // 1: best-case scenario: er staat een geheel bericht in buffer
            // 2: meerdere berichten in buffer
            // 3: deelbericht in buffer
            // 4: kapotte buffer

            //System.Diagnostics.Debug.Print(DateTime.Now.ToString("HH:mm:ss.fffff") + ":HandleReceiveBuffer2:" + _receiveBuffer.Length);

            var msgs = Protocol.ParseBuffer(ref _receiveBuffer);

            if (msgs == null)
            {
                return;
            }



            foreach (MsgPack.MessagePackObject msg in msgs)
            {
                //if (OnMessage != null)
                //{
                //    OnMessage(this, new KeyConductorRawCommandEventArgs(msg)); // this is the raw message from the KeyConductorLite
                //}

                // handle the message
                // first key/pair = KCID
                // second key/pair = CommandType
                // rest is based on commandtype

                var dicMessage = msg.AsDictionary();

                // Generic parameters
                string kcid = "000000000000"; // default kcid
                Protocol.CommandType  commandType = Protocol.CommandType.Undefined;
                Protocol.ReturnValues returnValue = Protocol.ReturnValues.Undefined;
                string paramData = "";

                // Specific parameters
                byte position = 0;
                //Protocol.Capabilities capabilities = Protocol.Capabilities.None;
                Protocol.EventType eventType = Protocol.EventType.Undefined;

                Protocol.FileName fileName = Protocol.FileName.Undefined;
                uint   fileChecksum        = 0;
                byte[] fileContents        = new byte[] { };

                foreach (var dc in dicMessage)
                {
                    if ((byte)dc.Key == (byte)Protocol.Parameter.KCID) // always first parameter
                    {
                        kcid = Convert.ToString((UInt32)dc.Value, 16);
                    }
                    else if ((byte)dc.Key == (byte)Protocol.Parameter.CommandType) // always second parameter
                    {
                        commandType = (Protocol.CommandType)(byte) dc.Value;

                        switch (commandType)
                        {
                        case Protocol.CommandType.GetInfo:
                            OnLogMessage?.Invoke(this, new LogMessageEventArgs("GetInfo request"));
                            ReturnInfo();
                            break;

                        case Protocol.CommandType.PutFile:
                        case Protocol.CommandType.RemoteRelease:
                        case Protocol.CommandType.SetDateTime:
                        case Protocol.CommandType.RemoteReturn:
                            OnLogMessage?.Invoke(this, new LogMessageEventArgs(string.Format("Command:{0} request", commandType)));
                            ReturnOk(commandType);
                            break;
                        }
                    }
                    else if ((byte)dc.Key == (byte)Protocol.Parameter.Position)
                    {
                        position = (byte)dc.Value;
                    }
                    else // rest of the parameters depends on type of command/event
                    {
                        switch (commandType)
                        {
                        case Protocol.CommandType.GetFile:
                        {
                            if ((byte)dc.Key == (byte)Protocol.Parameter.FileName)
                            {
                                fileName = (Protocol.FileName)(byte) dc.Value;

                                OnLogMessage?.Invoke(this, new LogMessageEventArgs(string.Format("Command:GetFile {0} request", fileName)));
                                ReturnDummyFile(fileName);
                            }
                        }
                        break;


                        case Protocol.CommandType.OnEvent:
                        {
                            if ((byte)dc.Key == (byte)Protocol.Parameter.EventType)
                            {
                                eventType = (Protocol.EventType)(byte) dc.Value;
                            }

                            else if ((byte)dc.Key == (byte)Protocol.Parameter.EventData)
                            {
                                // depends on eventType
                                switch (eventType)
                                {
                                // Standalone events:

                                case Protocol.EventType.RemoteAuthentication:
                                {
                                    //case Protocol.EventType.KeyBoardPress: // ter simulatie

                                    string userCode = "0000";
                                    string pinCode  = "0000";
                                    string userData = "";

                                    // bytes[0] + bytes[1]: userCode of pinCode
                                    // bytes[2] + bytes[3]: pinCode
                                    // bytes[rest]: userData (optional)
                                    paramData = BitConverter.ToString((byte[])dc.Value).Replace("-", "");

                                    // Note that both UserCode and Pincode are byte-rotated; 1234 -> 3412

                                    if (paramData.Length == 4)
                                    {
                                        pinCode = paramData.Substring(2, 2) + paramData.Substring(0, 2);
                                    }
                                    else if (paramData.Length >= 8)
                                    {
                                        userCode = paramData.Substring(2, 2) + paramData.Substring(0, 2);
                                        pinCode  = paramData.Substring(6, 2) + paramData.Substring(4, 2);
                                    }

                                    if (paramData.Length > 8)
                                    {
                                        for (int i = 8; i < paramData.Length; i++)
                                        {
                                            userData += (char)paramData[i];                 // Convert.ToString(paramData[i], 10);
                                        }
                                    }

                                    var evtArg = new RemoteAuthenticationEventArgs(kcid, userCode, pinCode, userData);
                                    OnRemoteAuthentication?.Invoke(this, evtArg);
                                }
                                break;

                                case Protocol.EventType.Login:
                                case Protocol.EventType.Logout:
                                {
                                    string userCode = "0000";
                                    string pinCode  = "0000";
                                    string userData = "";

                                    // bytes[0] + bytes[1]: userCode of pinCode
                                    // bytes[2] + bytes[3]: pinCode
                                    // bytes[rest]: userData (optional)

                                    byte[] tmpAuthData = (byte[])dc.Value;


                                    paramData = BitConverter.ToString(tmpAuthData).Replace("-", "");

                                    // Note that both UserCode and Pincode are NOT byte-rotated


                                    if (paramData.Length == 4)
                                    {
                                        pinCode = paramData.Substring(0, 4);
                                    }
                                    else if (paramData.Length >= 8)
                                    {
                                        userCode = paramData.Substring(0, 4);
                                        pinCode  = paramData.Substring(4, 4);
                                    }

                                    if (paramData.Length > 8)
                                    {
                                        for (int i = 8; i < paramData.Length; i++)
                                        {
                                            userData += (char)paramData[i];                 // Convert.ToString(paramData[i], 10);
                                        }
                                    }

                                    var evtArg = new OnEventUserEventArgs(kcid, userCode, pinCode, userData);
                                    if (eventType == Protocol.EventType.Login)
                                    {
                                        OnEventLogin?.Invoke(this, evtArg);
                                    }
                                    else
                                    {
                                        OnEventLogout?.Invoke(this, evtArg);
                                    }
                                }
                                break;

                                case Protocol.EventType.DoorOpen:
                                case Protocol.EventType.DoorClosed:
                                {
                                    string userCode = "0000";

                                    // bytes[0] + bytes[1]: userCode of pinCode

                                    paramData = BitConverter.ToString((byte[])dc.Value).Replace("-", "");

                                    // Note that both UserCode and Pincode are NOT byte-rotated

                                    if (paramData.Length == 4)
                                    {
                                        userCode = paramData;
                                    }

                                    var evtArg = new OnEventDoorEventArgs(kcid, userCode, 0x00);
                                    if (eventType == Protocol.EventType.DoorOpen)
                                    {
                                        OnEventDoorOpen?.Invoke(this, evtArg);
                                    }
                                    else
                                    {
                                        OnEventDoorClosed?.Invoke(this, evtArg);
                                    }
                                }
                                break;

                                case Protocol.EventType.KeyReturned:
                                case Protocol.EventType.KeyPicked:
                                {
                                    string userCode = "0000";
                                    ushort slot     = 0;

                                    // bytes[0] + bytes[1]: userCode
                                    // V2: bytes[2]: slot
                                    // V3: bytes[2] + bytes[3]: slot (ushort)

                                    byte[] data = (byte[])dc.Value;
                                    paramData = BitConverter.ToString(data).Replace("-", "");

                                    // Note that both UserCode and Pincode are byte-rotated; 1234 -> 3412

                                    userCode = paramData.Substring(2, 2) + paramData.Substring(0, 2);

                                    if (data.Length == 3)
                                    {
                                        // Firmware 2
                                        slot = data[2];
                                    }
                                    else if (data.Length == 4)
                                    {
                                        // Firmware 3
                                        slot = (ushort)(data[2] * 256 + data[3]);
                                    }

                                    var evtArg = new OnEventKeyEventArgs(kcid, userCode, slot);
                                    if (eventType == Protocol.EventType.KeyReturned)
                                    {
                                        OnEventKeyReturned?.Invoke(this, evtArg);
                                    }
                                    else
                                    {
                                        OnEventKeyPicked?.Invoke(this, evtArg);
                                    }
                                }
                                break;

                                case Protocol.EventType.Timeout:
                                case Protocol.EventType.Warning:
                                case Protocol.EventType.ExternalAlarm:
                                case Protocol.EventType.ExternalAlarmCleared:
                                case Protocol.EventType.Startup:
                                case Protocol.EventType.MainsVoltageLost:
                                case Protocol.EventType.MainsVoltageConnected:
                                {
                                    string userCode = "0000";

                                    // bytes[0] + bytes[1]: userCode
                                    byte[] data = (byte[])dc.Value;
                                    paramData = BitConverter.ToString(data).Replace("-", "");

                                    // Note that both UserCode is NOT byte-rotated
                                    userCode = paramData;

                                    var evtArg = new OnEventWarningEventArgs(kcid, userCode, eventType);

                                    switch (eventType)
                                    {
                                    case Protocol.EventType.Warning:
                                        OnEventWarning?.Invoke(this, evtArg);
                                        break;

                                    case Protocol.EventType.Timeout:
                                        OnEventTimeout?.Invoke(this, evtArg);
                                        break;

                                    case Protocol.EventType.ExternalAlarm:
                                        OnEventAlarm?.Invoke(this, evtArg);
                                        break;

                                    case Protocol.EventType.ExternalAlarmCleared:
                                        OnEventAlarmCleared?.Invoke(this, evtArg);
                                        break;

                                    case Protocol.EventType.Startup:
                                        OnEventStartUp?.Invoke(this, evtArg);
                                        break;

                                    case Protocol.EventType.MainsVoltageLost:
                                        OnEventMainsVoltageLost?.Invoke(this, evtArg);
                                        break;

                                    case Protocol.EventType.MainsVoltageConnected:
                                        OnEventMainsVoltageConnected?.Invoke(this, evtArg);
                                        break;
                                    }
                                }
                                break;
                                }
                            }
                            else if ((byte)dc.Key == (byte)Protocol.Parameter.Result_Code)         // n-th parameter
                            {
                                // dit komt niet voor bij events !!
                            }
                        }
                        break;

                        default:
                        {
                            if ((byte)dc.Key == (byte)Protocol.Parameter.Result_Code)         // n-th parameter
                            {
                                returnValue = (Protocol.ReturnValues)(byte) dc.Value;

                                var evtArg = new KeyConductorBaseReplyEventArgs(kcid, commandType, returnValue);

                                OnCommand?.Invoke(this, evtArg);

                                // raise event for individual functions
                                switch (commandType)
                                {
                                case Protocol.CommandType.Unknown:
                                    OnUnknownCommand?.Invoke(this, evtArg);
                                    break;

                                case Protocol.CommandType.PutFile:
                                    OnPutFile?.Invoke(this, evtArg);
                                    break;

                                case Protocol.CommandType.SetDateTime:
                                    OnSetDateTime?.Invoke(this, evtArg);
                                    break;

                                case Protocol.CommandType.RemoteRelease:
                                    OnRemoteRelease?.Invoke(this, evtArg);
                                    break;

                                case Protocol.CommandType.RemoteReturn:
                                    OnRemoteReturn?.Invoke(this, evtArg);
                                    break;

                                case Protocol.CommandType.RemoteReboot:
                                    OnRemoteReboot?.Invoke(this, evtArg);
                                    break;
                                }
                            }         // if parameter = resultcode
                        }
                        break;
                        } // /Switch commandType
                    }     //Else parameter
                }         // foreach dc in dicMessage
            }             // foreach msg in msgs
        }                 // /HandleReceiveBuffer
Beispiel #26
0
 public static void InvokeCommand(CommandEventArgs e)
 {
     OnCommand?.Invoke(e);
 }