예제 #1
0
        public async Task Me(CommandContext ctx)
        {
            var user = await db.GetUser(ctx.User.Id.ToString());

            if (user == null)
            {
                await ctx.RespondAsync($"{ctx.Message.Author.Mention}\nДля этого тебе нужно авторизоваться!\n\nОтправь команду `!shiki auth` и выполни полученные инструкции.");

                return;
            }

            var found = await api.SearchUser(user.ShikimoriNickname, user.AccessToken);

            if (found.StatusCode == HttpStatusCode.Unauthorized)
            {
                await CommandsHelper.UpdateTokens(user.ClientId, user.RefreshToken, db);

                user = await db.GetUser(ctx.User.Id.ToString());

                found = await api.SearchUser(user.ShikimoriNickname, user.AccessToken);
            }

            var embed = CommandsHelper.BuildUserInfoEmbed(found.Content);
            await ctx.RespondAsync(embed : embed);
        }
예제 #2
0
        private void OnGetCycleResponse(IReadOnlyCollection <byte> payload)
        {
            if (onGetCycleResponse == null)
            {
                return;
            }

            if (payload.Count != 5)
            {
                return;
            }

            var isContinuous = CommandsHelper.ToBool(payload.ElementAt(0));

            var txTimeSecondsBytes = payload
                                     .ToList()
                                     .GetRange(1, 2)
                                     .ToArray();

            var txTimeSeconds = BitConverter.ToUInt16(txTimeSecondsBytes, 0);

            var pauseTimeSecondsBytes = payload
                                        .ToList()
                                        .GetRange(3, 2)
                                        .ToArray();

            var pauseTimeSeconds = BitConverter.ToUInt16(pauseTimeSecondsBytes, 0);

            onGetCycleResponse(isContinuous, new TimeSpan(0, 0, txTimeSeconds), new TimeSpan(0, 0, pauseTimeSeconds));
        }
예제 #3
0
        public void SendSetFrequencyCommand(bool is144MHz, int frequency)
        {
            if (is144MHz)
            {
                if (frequency < Min144Frequency || frequency > Max144Frequency)
                {
                    throw new ArgumentException("Wrong frequency", nameof(frequency));
                }
            }
            else
            {
                if (frequency < Min35Frequency || frequency > Max35Frequency)
                {
                    throw new ArgumentException("Wrong frequency", nameof(frequency));
                }
            }

            var payload = new List <byte>();

            // 2th (from 0th) byte - is 144MHz flag
            payload.Add(CommandsHelper.FromBool(is144MHz));

            // 3th - 6th bytes - frequency
            payload.AddRange(BitConverter.GetBytes((uint)frequency));

            _packetsProcessor.SendCommand(CommandType.SetFrequency, payload);
        }
예제 #4
0
        public override void RunCommand(object sender, ScriptAction parentCommand)
        {
            var engine     = (IAutomationEngineInstance)sender;
            var loopResult = CommandsHelper.DetermineStatementTruth(engine, v_LoopActionType, v_ActionParameterTable);

            engine.ReportProgress("Starting Loop");

            while (loopResult)
            {
                foreach (var cmd in parentCommand.AdditionalScriptCommands)
                {
                    if (engine.IsCancellationPending)
                    {
                        return;
                    }

                    engine.ExecuteCommand(cmd);

                    if (engine.CurrentLoopCancelled)
                    {
                        engine.ReportProgress("Exiting Loop");
                        engine.CurrentLoopCancelled = false;
                        return;
                    }

                    if (engine.CurrentLoopContinuing)
                    {
                        engine.ReportProgress("Continuing Next Loop");
                        engine.CurrentLoopContinuing = false;
                        break;
                    }
                }
                loopResult = CommandsHelper.DetermineStatementTruth(engine, v_LoopActionType, v_ActionParameterTable);
            }
        }
예제 #5
0
        private bool GetConditionResult(IAutomationEngineInstance engine)
        {
            bool isTrueStatement = true;

            foreach (DataRow rw in v_IfConditionsTable.Rows)
            {
                var commandData     = rw["CommandData"].ToString();
                var ifCommand       = JsonConvert.DeserializeObject <BeginIfCommand>(commandData);
                var statementResult = CommandsHelper.DetermineStatementTruth(engine, ifCommand.v_IfActionType, ifCommand.v_ActionParameterTable);

                if (!statementResult && v_LogicType == "And")
                {
                    isTrueStatement = false;
                    break;
                }

                if (statementResult && v_LogicType == "Or")
                {
                    isTrueStatement = true;
                    break;
                }
                else if (v_LogicType == "Or")
                {
                    isTrueStatement = false;
                }
            }
            return(isTrueStatement);
        }
예제 #6
0
        private void CreateCustomCommand(string command, CommandRepository commandRepository)
        {
            SpeechSynthesisService.Speak("Teach me how to do it");
            IList <ICoreCommand> subCommands = new List <ICoreCommand>();
            var newCommand = SpeechRecognitionService.Listen();

            while (true)
            {
                var intent = IntentService.GetIntent(newCommand);
                if (CommandsHelper.GetCoreCommandIntents().Contains(intent.TopScoringIntent.Name) && intent.TopScoringIntent.Score > 0.7)
                {
                    var factory     = new CoreCommandFactory();
                    var coreCommand = factory.Create(intent.TopScoringIntent.Name);
                    coreCommand.Validate(new List <string>(), true);
                    subCommands.Add(coreCommand);
                    SpeechSynthesisService.Speak("Anything else");
                }
                else
                {
                    if (intent.TopScoringIntent.Name == "no")
                    {
                        break;
                    }
                    SpeechSynthesisService.Speak("Cannot do that");
                }
                newCommand = SpeechRecognitionService.Listen();
                intent     = IntentService.GetIntent(newCommand);
                if (intent.TopScoringIntent.Name == "no")
                {
                    break;
                }
            }
            commandRepository.SaveCustomCommand(command, subCommands, Guid.NewGuid().ToString());
        }
예제 #7
0
        private void OnGetProfileNameResponse(IReadOnlyCollection <byte> payload)
        {
            if (_onGetProfileNameResponse == null)
            {
                return;
            }

            if (!CommandsHelper.IsSuccessful(payload.ElementAt(0)))
            {
                _onGetProfileNameResponse(false, 0, String.Empty);
                return;
            }

            var profileId = (int)payload.ElementAt(1);

            var expectedNameLength = payload.ElementAt(2);

            if (expectedNameLength < MinNameLength || expectedNameLength > MaxNameLength)
            {
                return;
            }

            if (payload.Count != expectedNameLength + 3)
            {
                return;
            }

            var name = Encoding.ASCII.GetString(payload
                                                .ToList()
                                                .GetRange(3, payload.Count - 3)
                                                .ToArray());

            _onGetProfileNameResponse(true, profileId, name);
        }
예제 #8
0
 public void LoadSettings(UserSettings userSettings, bool load)
 {
     if (!load)
     {
         return;
     }
     try
     {
         userSettings = GetLocalUserSettings(userSettings);
     }
     catch (Exception)
     {
         if (!FilesHelper.FileExists(userSettings.SettingsFileLocation))
         {
             NotificationsHelper.DisplayMessage(Messages.Preparing);
             PrepareEnvironment(new UserSettings());
         }
         else if (!CommandsHelper.ShouldExecuteTasks())
         {
             NotificationsHelper.DisplayMessage(Messages.Ready);
         }
         else
         {
             NotificationsHelper.DisplayMessage(Messages.ErrorInSettings);
         }
     }
 }
예제 #9
0
        public void Detect()
        {
            SpeechSynthesisService.Speak("What do you want?");
            var command = SpeechRecognitionService.Listen();

            if (string.IsNullOrEmpty(command))
            {
                return;
            }
            var intent = IntentService.GetIntent(command);

            if (CommandsHelper.GetCoreCommandIntents().Contains(intent.TopScoringIntent.Name) && intent.TopScoringIntent.Score > 0.7)
            {
                var factory     = new CoreCommandFactory();
                var coreCommand = factory.Create(intent.TopScoringIntent.Name);
                var response    = coreCommand.Execute(new List <string>());
                var output      = response.ElementAtOrDefault(0);
                if (output != null)
                {
                    SpeechSynthesisService.Speak(output);
                }
                return;
            }
            ICustomCommand customCommand = SearchCommand(_commandRepository, command);

            if (customCommand == null)
            {
                CreateCustomCommand(command, _commandRepository);
            }
            else
            {
                customCommand.Execute();
            }
        }
        private void CreateWhileCondition(object sender, EventArgs e, IfrmCommandEditor parentEditor, ICommandControls commandControls)
        {
            var automationCommands = new List <AutomationCommand>()
            {
                CommandsHelper.ConvertToAutomationCommand(typeof(BeginWhileCommand))
            };
            IfrmCommandEditor editor = commandControls.CreateCommandEditorForm(automationCommands, null);

            editor.SelectedCommand = new BeginWhileCommand();
            editor.ScriptContext   = parentEditor.ScriptContext;
            editor.TypeContext     = parentEditor.TypeContext;

            if (((Form)editor).ShowDialog() == DialogResult.OK)
            {
                //get data
                var configuredCommand = editor.SelectedCommand as BeginWhileCommand;
                var displayText       = configuredCommand.GetDisplayValue();
                var serializedData    = JsonConvert.SerializeObject(configuredCommand);
                parentEditor.ScriptContext = editor.ScriptContext;
                parentEditor.TypeContext   = editor.TypeContext;

                //add to list
                v_WhileConditionsTable.Rows.Add(displayText, serializedData);
            }

            commandControls.AddIntellisenseListBoxToCommandForm();
        }
예제 #11
0
        private void OnGetAntennaMatchingDataResponse(IReadOnlyCollection <byte> payload)
        {
            if (_onGetAntennaMatchingDataResponse == null)
            {
                return;
            }

            if (payload.Count != 5)
            {
                return;
            }

            if (!CommandsHelper.IsSuccessful(payload.ElementAt(0)))
            {
                _onGetAntennaMatchingDataResponse(false, _matcherPosition, 0);
            }

            var voltageBytes = payload
                               .ToList()
                               .GetRange(1, 4)
                               .ToArray();

            var voltage = BitConverter.ToSingle(voltageBytes, 0);

            _onGetAntennaMatchingDataResponse(true, _matcherPosition, voltage);
        }
예제 #12
0
        public static List <AutomationCommand> GenerateAutomationCommands(IContainer container)
        {
            var commandList    = new List <AutomationCommand>();
            var commandClasses = new List <Type>();

            using (var scope = container.BeginLifetimeScope())
            {
                var types = scope.ComponentRegistry.Registrations
                            .Where(r => typeof(ScriptCommand).IsAssignableFrom(r.Activator.LimitType))
                            .Select(r => r.Activator.LimitType).ToList();

                commandClasses.AddRange(types);
            }

            var userPrefs = new ApplicationSettings().GetOrCreateApplicationSettings();

            //Loop through each class
            foreach (var commandClass in commandClasses)
            {
                var newAutomationCommand = CommandsHelper.ConvertToAutomationCommand(commandClass);

                //If command is enabled, pull for display and configuration
                if (newAutomationCommand != null)
                {
                    commandList.Add(newAutomationCommand);
                }
            }

            return(commandList.Distinct().ToList());
        }
예제 #13
0
        public void ExecuteCommand(Device device, Command command, string args)
        {
            var availableCommands = CommandsHelper.GetAvailableCommands(device);

            if (!availableCommands.Contains(command))
            {
                throw new ArgumentException($"Unsupported command {command} for device {device.Id} {device.DeviceType}");
            }

            switch (command)
            {
            case Command.SetTemperature:
                SetTemperature(device, args);
                break;

            case Command.TurnOn:
                TurnOn(device);
                break;

            case Command.TurnOff:
                TurnOff(device);
                break;

            default:
                throw new ArgumentException($"Cannot execute unknown command {command} for device {device.Id}");
            }
        }
예제 #14
0
        public void SendSetSpeedCommand(bool isFast)
        {
            var payload = new List <byte>();

            payload.Add(CommandsHelper.FromBool(isFast));

            packetsProcessor.SendCommand(CommandType.SetSpeed, payload);
        }
예제 #15
0
        public void test_if_move_command_works_as_expected(int xLocation, int yLocation, Direction direction, string output)
        {
            CommandsHelper.ResetWells();
            CommandsHelper.Place(xLocation, yLocation);
            CommandsHelper.Move(direction);
            var report = CommandsHelper.Report();

            Assert.Equal(output, report);
        }
 private void Run()
 {
     CommandsHelper.ForeachFiles(Directory, async(file) =>
     {
         string newFolder = await GetFileFolder(file);
         CreateFolderIfIsNecessary(newFolder);
         MoveFileToNewPath(file, newFolder);
     });
 }
예제 #17
0
        private void OnAddNewProfileResponse(IReadOnlyCollection <byte> payload)
        {
            if (_onAddNewProfileResponse == null)
            {
                return;
            }

            _onAddNewProfileResponse(CommandsHelper.IsSuccessful(payload.ElementAt(0)));
        }
예제 #18
0
        public static void Main(string[] args)
        {
            RegisterServices();
            var tasksHandler = DependencyInjectionHelper.InjectDependency <ITasksHandler>();

            CommandsHelper.AnalyseCommandArgs(args);
            tasksHandler.ExecuteTasks();
            NotificationsHelper.DisplayMessage(Messages.Finish);
            SystemsHelper.Sleep();
        }
예제 #19
0
        public void SendSetP80mFactors(bool resetToDefaults, float a, float b)
        {
            var payload = new List<byte>();

            payload.Add(CommandsHelper.FromBool(resetToDefaults));

            payload.AddRange(BitConverter.GetBytes(a));
            payload.AddRange(BitConverter.GetBytes(b));

            _packetsProcessor.SendCommand(CommandType.SetP80mToU80mFactors, payload);
        }
예제 #20
0
        public void Should_GetClosestCommand()
        {
            var commands = new ICommand[]
            {
                new CommandA(),
                new CommandB()
            };

            var closest = CommandsHelper.GetClosestCommand <CommandA>(commands, 1);

            Assert.Same(commands.ElementAt(0), closest);
        }
예제 #21
0
        public void Should_GetClosestCommand_ThrowException_WhenNoTargetCommand()
        {
            var commands = new ICommand[]
            {
                new CommandNeutral(),
                new CommandNeutral(),
                new CommandNeutral(),
                new CommandB()
            };

            Assert.Throws <InvalidCommandOrderException>(() => { CommandsHelper.GetClosestCommand <CommandA>(commands, 3, new[] { typeof(CommandNeutral) }); });
        }
예제 #22
0
        private void IfConditionHelper_CellContentClick(object sender, DataGridViewCellEventArgs e, IfrmCommandEditor parentEditor, ICommandControls commandControls)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                var buttonSelected = senderGrid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewButtonCell;
                var selectedRow    = v_IfConditionsTable.Rows[e.RowIndex];

                if (buttonSelected.Value.ToString() == "Edit")
                {
                    //launch editor
                    var statement   = selectedRow["Statement"];
                    var commandData = selectedRow["CommandData"].ToString();

                    var ifCommand = commandControls.CreateBeginIfCommand(commandData);

                    var automationCommands = new List <AutomationCommand>()
                    {
                        CommandsHelper.ConvertToAutomationCommand(ifCommand.GetType())
                    };
                    IfrmCommandEditor editor = commandControls.CreateCommandEditorForm(automationCommands, null);
                    editor.SelectedCommand      = ifCommand;
                    editor.EditingCommand       = ifCommand;
                    editor.OriginalCommand      = ifCommand;
                    editor.CreationModeInstance = CreationMode.Edit;
                    editor.ScriptEngineContext  = parentEditor.ScriptEngineContext;
                    editor.TypeContext          = parentEditor.TypeContext;

                    if (((Form)editor).ShowDialog() == DialogResult.OK)
                    {
                        parentEditor.ScriptEngineContext = editor.ScriptEngineContext;
                        parentEditor.TypeContext         = editor.TypeContext;

                        var editedCommand  = editor.SelectedCommand as BeginIfCommand;
                        var displayText    = editedCommand.GetDisplayValue();
                        var serializedData = JsonConvert.SerializeObject(editedCommand);

                        selectedRow["Statement"]   = displayText;
                        selectedRow["CommandData"] = serializedData;
                    }
                }
                else if (buttonSelected.Value.ToString() == "Delete")
                {
                    //delete
                    v_IfConditionsTable.Rows.Remove(selectedRow);
                }
                else
                {
                    throw new NotImplementedException("Requested Action is not implemented.");
                }
            }
        }
        public async override Tasks.Task RunCommand(object sender, ScriptAction parentCommand)
        {
            var engine = (IAutomationEngineInstance)sender;

            bool whileResult;

            if (v_Option == "Inline")
            {
                whileResult = (bool)await v_Condition.EvaluateCode(engine);
            }
            else
            {
                whileResult = await CommandsHelper.DetermineStatementTruth(engine, v_ActionType, v_ActionParameterTable);
            }

            engine.ReportProgress("Starting While");

            while (whileResult)
            {
                foreach (var cmd in parentCommand.AdditionalScriptCommands)
                {
                    if (engine.IsCancellationPending)
                    {
                        return;
                    }

                    await engine.ExecuteCommand(cmd);

                    if (engine.CurrentLoopCancelled)
                    {
                        engine.ReportProgress("Exiting While");
                        engine.CurrentLoopCancelled = false;
                        return;
                    }

                    if (engine.CurrentLoopContinuing)
                    {
                        engine.ReportProgress("Continuing Next While");
                        engine.CurrentLoopContinuing = false;
                        break;
                    }
                }
                if (v_Option == "Inline")
                {
                    whileResult = (bool)await v_Condition.EvaluateCode(engine);
                }
                else
                {
                    whileResult = await CommandsHelper.DetermineStatementTruth(engine, v_ActionType, v_ActionParameterTable);
                }
            }
        }
예제 #24
0
        static void Main(string[] args)
        {
            Program instance = new Program();

            instance.StartTCPIPserver(Properties.Settings.Default.TCP_SERVER_PORT);
            instance.StartWebAppConnectorServer(Properties.Settings.Default.CONNECTOR_SERVER_PORT);

            while (true)
            {
                var read = Console.ReadLine();
                CommandsHelper.WriteCommand(read);
            }
        }
예제 #25
0
        public void Should_GetClosestCommand_ThrowException_When_WithoutSkipTypes()
        {
            var commands = new ICommand[]
            {
                new CommandA(),
                new CommandNeutral(),
                new CommandNeutral(),
                new CommandNeutral(),
                new CommandB()
            };

            Assert.Throws <InvalidCommandOrderException>(() => { CommandsHelper.GetClosestCommand <CommandA>(commands, 4); });
        }
예제 #26
0
        private void OnSetCurrentDateAndTimeResponse(IReadOnlyCollection <byte> payload)
        {
            if (onSetDateAndTimeResponse == null)
            {
                return;
            }

            if (payload.Count != 1)
            {
                return;
            }

            onSetDateAndTimeResponse(CommandsHelper.IsSuccessful(payload.ElementAt(0)));
        }
예제 #27
0
        private void OnSetRTCCalibrationValueResponse(IReadOnlyCollection <byte> payload)
        {
            if (_onSetRTCCalibrationValueResponse == null)
            {
                return;
            }

            if (payload.Count != 1)
            {
                return;
            }

            _onSetRTCCalibrationValueResponse(CommandsHelper.IsSuccessful(payload.ElementAt(0)));
        }
        private void OnSetDisarmOnDischargeThresholdResponse(IReadOnlyCollection <byte> payload)
        {
            if (_onSetDisarmOnDischargeThresholdResponse == null)
            {
                return;
            }

            if (payload.Count != 1)
            {
                return;
            }

            _onSetDisarmOnDischargeThresholdResponse(CommandsHelper.IsSuccessful(payload.ElementAt(0)));
        }
예제 #29
0
        private void OnDisarmFoxResponse(IReadOnlyCollection <byte> payload)
        {
            if (onDisarmFoxResponse == null)
            {
                return;
            }

            if (payload.Count != 1)
            {
                return;
            }

            onDisarmFoxResponse(CommandsHelper.IsSuccessful(payload.ElementAt(0)));
        }
예제 #30
0
        private void OnIsFoxArmedResponse(IReadOnlyCollection <byte> payload)
        {
            if (_onIsFoxArmedResponse == null)
            {
                return;
            }

            if (payload.Count != 1)
            {
                return;
            }

            _onIsFoxArmedResponse(CommandsHelper.ToBool(payload.ElementAt(0)));
        }