public VersionsViewModel()
 {
     InitialHeight = (System.Windows.Application.Current.MainWindow as MainWindow).ActualHeight;
     ShowBottomPart = false;
     IsBusy = true;
     IsRefreshing = true;
     ChangeVersionCommand = new SwitchCommand(this);
     RefreshPackagesCommand = new RelayCommand((param) =>
         {
             this.ShowBottomPart = false;
             this.RefreshPackages();
         }, (param) => { return !this.IsBusy; });
     CloseProgramCommand = new RelayCommand((param) => System.Windows.Application.Current.Shutdown(), (param) => { return !this.IsBusy; });
 }
Exemple #2
0
        public static void PrintMainPlusOffset(ulong offset, int size)
        {
            sb.Connect(sb.IP, sb.Port);

            Thread.Sleep(1000);

            var tid = getTitleId();
            var mainAt = getMainNsoBase();
            sb.SendRawBytes(SwitchCommand.PeekAbsolute(mainAt+offset, size));
            byte[] received = sb.ReadRawBytes(size); // this returns chars
            string strToWrite = "";
            foreach (byte rec in received)
                strToWrite += (char)rec;
            strToWrite = strToWrite.Replace("\n", string.Empty);
            Console.WriteLine(strToWrite);
        }
        public async Task InitializeHardware(IBotStateSettings settings, CancellationToken token)
        {
            Log("Detaching on startup.");
            await DetachController(token).ConfigureAwait(false);

            if (settings.ScreenOff)
            {
                Log("Turning off screen.");
                await SetScreen(ScreenState.Off, token).ConfigureAwait(false);
            }

            Log("Setting BDSP-specific hid waits.");
            await Connection.SendAsync(SwitchCommand.Configure(SwitchConfigureParameter.keySleepTime, 50), token).ConfigureAwait(false);

            await Connection.SendAsync(SwitchCommand.Configure(SwitchConfigureParameter.pollRate, 50), token).ConfigureAwait(false);
        }
Exemple #4
0
        public static void ReadItemDump(FakeItem item, uint offset, uint offsetItem)
        {
            FakeItem itemToWrite = item;
            sb.WriteBytes(itemToWrite.GetAsBytes5(), offset);

            sb.SendRawBytes(SwitchCommand.Click(SwitchButton.DRIGHT));

            Thread.Sleep(1500);

            sb.SendRawBytes(SwitchCommand.Click(SwitchButton.B));

            byte[] received = sb.ReadBytes(offsetItem, 4196);
            string txt = System.Text.Encoding.UTF8.GetString(received);

            Console.WriteLine(txt);
            Console.WriteLine("******************************************************************************************************************");
        }
Exemple #5
0
        private async Task ClickAsyncImpl(SwitchButton button, BotSource <PokeBotState> bot)
        {
            if (!Enum.IsDefined(typeof(SwitchButton), button))
            {
                await ReplyAsync($"Unknown button value: {button}").ConfigureAwait(false);

                return;
            }

            var b = bot.Bot;
            var crlf = b is SwitchRoutineExecutor <PokeBotState> {
                UseCRLF : true
            };
            await b.Connection.SendAsync(SwitchCommand.Click(button, crlf), CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{b.Connection.Name} has performed: {button}").ConfigureAwait(false);
        }
Exemple #6
0
        private static KeyValuePair<string, int> PullKVP(ulong ramAddress)
        {
            sb.SendRawBytes(SwitchCommand.PeekAbsolute(ramAddress, 8));
            byte[] received = sb.ReadRawBytes(8); // this returns chars
            string strToWrite = "";
            foreach (byte rec in received)
                strToWrite += (char)rec;
            strToWrite = strToWrite.Replace("\n", string.Empty);
            Console.WriteLine(strToWrite);

            string half1 = strToWrite.Substring(0, 8);
            string half2 = strToWrite.Substring(8, 8);
            string half1Sorted = string.Format("0x{0}", new string(fix32BitEndian(half1.ToCharArray())));
            string half2Sorted = new string(fix32BitEndian(half2.ToCharArray()));
            Console.WriteLine(half1Sorted + " is " + half2Sorted);

            return new KeyValuePair<string, int>(half1Sorted, int.Parse(half2Sorted, System.Globalization.NumberStyles.HexNumber));
        }
        public void UndoWithoutExecuteTest()
        {
            //Arrange
            ICommand innerCommand = MockRepository.GenerateStrictMock <ICommand>();

            innerCommand.Expect(ic => ic.Undo()).
            Repeat.Never();

            SwitchCommand command = new SwitchCommand(innerCommand);

            //Act
            bool undoResult = command.Undo();

            //Assert
            Assert.IsFalse(undoResult);

            innerCommand.VerifyAllExpectations();
        }
Exemple #8
0
        private async Task DropItem(Item item, bool first, CancellationToken token)
        {
            // Exit out of any menus.
            if (first)
            {
                for (int i = 0; i < 3; i++)
                {
                    await Click(SwitchButton.B, 0_400, token).ConfigureAwait(false);
                }
            }

            var itemName = GameInfo.Strings.GetItemName(item);

            LogUtil.LogInfo($"Injecting Item: {item.DisplayItemId:X4} ({itemName}).", Config.IP);

            // Inject item.
            var data = item.ToBytesClass();
            var poke = SwitchCommand.Poke(Config.Offset, data);
            await Connection.SendAsync(poke, token);

            await Task.Delay(0_300, token).ConfigureAwait(false);

            // Open player inventory and open the currently selected item slot -- assumed to be the config offset.
            await Click(SwitchButton.X, 1_100, token).ConfigureAwait(false);
            await Click(SwitchButton.A, 0_500, token).ConfigureAwait(false);

            // Navigate down to the "drop item" option.
            var downCount = item.GetItemDropOption();

            for (int i = 0; i < downCount; i++)
            {
                await Click(SwitchButton.DDOWN, 0_400, token).ConfigureAwait(false);
            }

            // Drop item, close menu.
            await Click(SwitchButton.A, 0_400, token).ConfigureAwait(false);
            await Click(SwitchButton.X, 0_400, token).ConfigureAwait(false);

            // Exit out of any menus (fail-safe)
            for (int i = 0; i < 2; i++)
            {
                await Click(SwitchButton.B, 0_400, token).ConfigureAwait(false);
            }
        }
        public void CommitTest()
        {
            //Arrange
            ICommand innerCommand = MockRepository.GenerateStrictMock <ICommand>();

            innerCommand.Expect(ic => ic.Commit()).
            Repeat.Once().
            Return(true);

            SwitchCommand command = new SwitchCommand(innerCommand);

            //Act
            bool commitResult = command.Commit();

            //Assert
            Assert.IsTrue(commitResult);

            innerCommand.VerifyAllExpectations();
        }
Exemple #10
0
        public static async Task <bool> ValidateStartup(Bot b, CancellationToken token)
        {
            // Validate our config file inputs.
            if (!ValidateConfigFileParameters(b))
            {
                return(false);
            }

            // Disconnect our virtual controller; will reconnect once we send a button command after a request.
            b.Log("Detaching controller on startup as first interaction.");
            await b.Connection.SendAsync(SwitchCommand.DetachController(b.UseCRLF), token).ConfigureAwait(false);

            await Task.Delay(200, token).ConfigureAwait(false);

            // Validate inventory offset.
            var inventoryValid = await ValidateStartupInventory(b, token).ConfigureAwait(false);

            if (!inventoryValid)
            {
                return(false);
            }

            if (b.Config.VillagerConfig.AllowVillagerInjection)
            {
                await b.VillagerState.InitializeVillagers(token).ConfigureAwait(false);
            }

            if (b.Config.ViewConfig.SkipSessionCheck)
            {
                return(await StartupGetDodoCode(b.ViewState, b, token, true).ConfigureAwait(false));
            }

            var sessionActive = await b.ViewState.IsLinkSessionActive(token).ConfigureAwait(false);

            if (sessionActive)
            {
                return(await b.ViewState.StartupGetDodoCode(b, token, true).ConfigureAwait(false));
            }

            bool gates = await b.ViewState.StartupOpenGates(b, token).ConfigureAwait(false);

            return(gates && await b.ViewState.StartupGetDodoCode(b, token).ConfigureAwait(false));
        }
Exemple #11
0
        private async Task SetScreen(bool on, string ip)
        {
            var bot = GetBot(ip);

            if (bot == null)
            {
                await ReplyAsync($"No bot has that IP address ({ip}).").ConfigureAwait(false);

                return;
            }

            var b = bot.Bot;
            var crlf = b is SwitchRoutineExecutor <PokeBotState> {
                UseCRLF : true
            };
            await b.Connection.SendAsync(SwitchCommand.SetScreen(on ? ScreenState.On : ScreenState.Off, crlf), CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync("Screen state set to: " + (on ? "On" : "Off")).ConfigureAwait(false);
        }
Exemple #12
0
        private async Task SetStickAsyncImpl(SwitchStick s, short x, short y, ushort ms, BotSource <PokeBotConfig> bot)
        {
            if (!Enum.IsDefined(typeof(SwitchStick), s))
            {
                await ReplyAsync($"Unknown stick: {s}").ConfigureAwait(false);

                return;
            }

            await bot.Bot.Connection.SendAsync(SwitchCommand.SetStick(s, x, y), bot.Bot.Config.ConnectionType, CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{bot.Bot.Connection.Name} has performed: {s}").ConfigureAwait(false);

            await Task.Delay(ms).ConfigureAwait(false);

            await bot.Bot.Connection.SendAsync(SwitchCommand.ResetStick(s), bot.Bot.Config.ConnectionType, CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{bot.Bot.Connection.Name} has reset the stick position.").ConfigureAwait(false);
        }
        private async Task SetStickAsyncImpl(SwitchStick s, short x, short y, ushort ms)
        {
            if (!Enum.IsDefined(typeof(SwitchStick), s))
            {
                await ReplyAsync($"Unknown stick: {s}").ConfigureAwait(false);

                return;
            }

            var b = Bot;
            await b.Connection.SendAsync(SwitchCommand.SetStick(s, x, y, b.UseCRLF), CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{b.Connection.Name} has performed: {s}").ConfigureAwait(false);

            await Task.Delay(ms).ConfigureAwait(false);

            await b.Connection.SendAsync(SwitchCommand.ResetStick(s, b.UseCRLF), CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{b.Connection.Name} has reset the stick position.").ConfigureAwait(false);
        }
Exemple #14
0
        private async Task CleanUp(CancellationToken token)
        {
            LogUtil.LogInfo("Picking up leftover items during idle time.", Config.IP);

            // Exit out of any menus.
            for (int i = 0; i < 3; i++)
            {
                await Click(SwitchButton.B, 0_400, token).ConfigureAwait(false);
            }

            // Pick up and delete.
            for (int i = 0; i < PickupCount; i++)
            {
                await Click(SwitchButton.Y, 2_000, token).ConfigureAwait(false);

                var poke = SwitchCommand.Poke(Config.Offset, Item.NONE.ToBytes());
                await Connection.SendAsync(poke, token);

                await Task.Delay(1_000, token).ConfigureAwait(false);
            }
        }
        public void InitializeServer()
        {
            server = new RestServer(8000, "RelayAutomation");

            server.GetContentRequestData = (method, data) =>
            {
                if (method == GetLamps)
                {
                    return(JsonConvert.SerializeObject(Lamps));
                }
                else if (method == SwitchLamp)
                {
                    SwitchCommand.Execute(null);
                    return(JsonConvert.SerializeObject(Lamps.First()));
                }

                return(String.Empty);
            };

            server.StartServer();
        }
Exemple #16
0
    public async Task DoSocketQueue(bool isNetwork, CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            if (ExecutionQueue.TryDequeue(out var item))
            {
                byte[] command = Array.Empty <byte>();
                switch (item.PType)
                {
                case PressType.ButtonPress: command = SwitchCommand.Hold(item.ButtonToPress, isNetwork); break;

                case PressType.ButtonRelease: command = SwitchCommand.Release(item.ButtonToPress, isNetwork); break;

                case PressType.Joystick: command = SwitchCommand.SetStick(item.StickToMove, item.X, item.Y); break;
                }
                try { Connection.CurrentConnection.SendBytes(command); } catch { }
            }

            await Task.Delay(1, token).ConfigureAwait(false);
        }
    }
Exemple #17
0
        public static void SendRawEncoded(string encode, bool expectReturn = false, bool connect = true)
        {
            if (connect)
            {
                sb.Connect(sb.IP, sb.Port);

                Thread.Sleep(1000);
            }
            else
                Thread.Sleep(16);
            sb.SendRawBytes(SwitchCommand.Encode(encode));

            if (expectReturn)
            {
                byte[] received = sb.ReadRawBytes(200); // this returns chars
                string strToWrite = "";
                foreach (byte rec in received)
                    strToWrite += (char)rec;
                strToWrite = strToWrite.Replace("\n", string.Empty);
                Console.WriteLine(strToWrite);
            }
        }
Exemple #18
0
        private static void DoSwitchAction(SwitchCommand action)
        {
            SwitchBinary switchB;
            if (zw.Controller.Nodes.ContainsKey(action.NodeID))
            {
                switchB = zw.Controller.Nodes[action.NodeID] as SwitchBinary;

                switch (action.Action)
                {
                    case SwitchAction.ON:
                        Console.WriteLine(string.Format("DoSwitchAction: SWITCH ID:{0} Turn: {1}.", action.NodeID, "ON"));
                        switchB.On();
                        break;
                    case SwitchAction.OFF:
                        Console.WriteLine(string.Format("DoSwitchAction: SWITCH ID:{0} Turn: {1}.", action.NodeID, "OFF"));
                        switchB.Off();
                        break;
                    default:
                        break;
                }
            }
        }
        public void UndoAfterExecuteTest()
        {
            //Arrange
            ICommand innerCommand = MockRepository.GenerateStrictMock <ICommand>();

            innerCommand.Expect(ic => ic.Execute()).
            Repeat.Once().
            Return(true);
            innerCommand.Expect(ic => ic.Undo()).
            Repeat.Once().
            Return(true);

            SwitchCommand command = new SwitchCommand(innerCommand);

            //Act
            bool execteResult = command.Execute();
            bool undoResult   = command.Undo();

            //Assert
            Assert.IsTrue(execteResult);
            Assert.IsTrue(undoResult);

            innerCommand.VerifyAllExpectations();
        }
Exemple #20
0
        private async Task SetStickAsyncImpl(SwitchStick s, short x, short y, ushort ms, BotSource <PokeBotState> bot)
        {
            if (!Enum.IsDefined(typeof(SwitchStick), s))
            {
                await ReplyAsync($"Unknown stick: {s}").ConfigureAwait(false);

                return;
            }

            var b = bot.Bot;
            var crlf = b is SwitchRoutineExecutor <PokeBotState> {
                UseCRLF : true
            };
            await b.Connection.SendAsync(SwitchCommand.SetStick(s, x, y, crlf), CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{b.Connection.Name} has performed: {s}").ConfigureAwait(false);

            await Task.Delay(ms).ConfigureAwait(false);

            await b.Connection.SendAsync(SwitchCommand.ResetStick(s, crlf), CancellationToken.None).ConfigureAwait(false);

            await ReplyAsync($"{b.Connection.Name} has reset the stick position.").ConfigureAwait(false);
        }
    }
        public async Task GetDodoCode(ulong CoordinateAddress, uint Offset, bool isRetry, CancellationToken token)
        {
            // Navigate through dialog with Dodo to open gates and to get Dodo code.
            await Task.Delay(0_500, token).ConfigureAwait(false);

            var Hold = SwitchCommand.Hold(SwitchButton.L);
            await Connection.SendAsync(Hold, token).ConfigureAwait(false);

            await Task.Delay(0_700, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 4_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_000, token).ConfigureAwait(false);

            if (!isRetry)
            {
                await BotRunner.Click(SwitchButton.A, 2_100, token).ConfigureAwait(false);
            }
            await BotRunner.Click(SwitchButton.DDOWN, 0_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.DDOWN, 0_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 20_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.DUP, 0_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.DUP, 0_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.DUP, 0_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 1_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_500, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 3_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_000, token).ConfigureAwait(false);

            await BotRunner.Click(SwitchButton.A, 2_000, token).ConfigureAwait(false);

            await Task.Delay(0_500, token).ConfigureAwait(false);

            var Release = SwitchCommand.Release(SwitchButton.L);
            await Connection.SendAsync(Release, token).ConfigureAwait(false);

            // Clear incase opening the gate took too long
            for (int i = 0; i < 6; ++i)
            {
                await BotRunner.Click(SwitchButton.B, 1_000, token).ConfigureAwait(false);
            }

            // Obtain Dodo code from offset and store it.
            byte[] bytes = await Connection.ReadBytesAsync(Offset, 0x5, token).ConfigureAwait(false);

            DodoCode = Encoding.UTF8.GetString(bytes, 0, 5);
            LogUtil.LogInfo($"Retrieved Dodo code: {DodoCode}.", Config.IP);

            // Wait for loading screen.
            while (await GetOverworldState(CoordinateAddress, token).ConfigureAwait(false) != OverworldState.Overworld)
            {
                await Task.Delay(0_500, token).ConfigureAwait(false);
            }
        }
Exemple #22
0
 public void Detach()
 {
     Connection.CurrentConnection.SendBytes(SwitchCommand.DetachController());
 }
Exemple #23
0
 public void SetScreen(bool on)
 {
     CurrentConnection.SendBytes(SwitchCommand.SetScreen(on));
 }
Exemple #24
0
        private static void ParseArgs(string[] args)
        {
            // -{Object}:NODEID {ACTION}
            //ex. -SWITCH:02 ON
            //ex. -SWITCH:03 OFF

            List<SwitchCommand> swCmdList = new List<SwitchCommand>();

            const string SWITCH = "-SWITCH";
            const string QUIT = "-Q";

            bool doQuit = false;
            Command curCommand = null;

            bool objectFound = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (!objectFound)
                {
                    if (args[i].StartsWith(SWITCH))
                    {
                        Console.WriteLine("ParseArgs: Found SWITCH Object.");
                        objectFound = true;
                        int colonIndex = args[i].LastIndexOf(':');
                        if (colonIndex < args[i].Length)
                        {
                            var nodeIdStr = args[i].Substring(colonIndex + 1);
                            int nodeID = 0;
                            if (Int32.TryParse(nodeIdStr, out nodeID))
                            {
                                Console.WriteLine(string.Format("ParseArgs: SWITCH NodeID:{0}.", nodeID));
                                curCommand = new SwitchCommand(TargetDevice.SWITCH, (byte)nodeID);
                            }
                        }
                    }
                    else if (args[i] == QUIT)
                    {
                        doQuit = true;
                    }

                }
                else
                {
                    objectFound = false;
                    if (curCommand != null)
                    {
                        SwitchCommand sc = curCommand as SwitchCommand;
                        if (sc != null)
                        {
                            switch (args[i])
                            {
                                case "ON":
                                    Console.WriteLine(string.Format("ParseArgs: SWITCH ACTION: {0}.", "ON"));
                                    sc.Action = SwitchAction.ON;
                                    break;
                                case "OFF":
                                    Console.WriteLine(string.Format("ParseArgs: SWITCH ACTION: {0}.", "OFF"));
                                    sc.Action = SwitchAction.OFF;
                                    break;
                                default:
                                    sc.Action = SwitchAction.OFF;
                                    break;
                            }
                            swCmdList.Add(sc);
                        }
                    }
                }
            }

            foreach (var cmd in swCmdList)
            {
                DoSwitchAction(cmd);
                Thread.Sleep(1000);
            }

            if (doQuit)
            {
                zw.ShutdownGracefully();
                exitEvent.Set();
            }
        }
Exemple #25
0
        public async Task <bool> SpinUntilChangedSurprise(int waitms, CancellationToken token)
        {
            const int fastSleep    = 10;     // between commands
            const int defaultSleep = 50;     // original
            const int delay        = 100;    // per stick command
            const int m            = 25_000; // magnitude of stick movement
            var       sw           = new Stopwatch();

            bool changed   = false;
            var  searching = await Connection.ReadBytesAsync(SurpriseTradeSearchOffset, 4, token).ConfigureAwait(false);

            await Connection.SendAsync(SwitchCommand.Configure(SwitchConfigureParameter.mainLoopSleepTime, fastSleep), token).ConfigureAwait(false);

            sw.Start();
            do
            {
                // Spin the Left Stick in a circle counter-clockwise, starting from 0deg (polar) in increments of 90deg.
                if (!await SpinCircle().ConfigureAwait(false))
                {
                    continue;
                }
                changed = true;
                break;
            } while (sw.ElapsedMilliseconds < waitms);

            async Task <bool> SpinCircle()
            {
                return(await Step(m, 0).ConfigureAwait(false) || // →
                       await Step(0, m).ConfigureAwait(false) || // ↑
                       await Step(-m, 0).ConfigureAwait(false) || // ←
                       await Step(0, -m).ConfigureAwait(false));  // ↓

                async Task <bool> Step(short x, short y)
                {
                    var now = sw.ElapsedMilliseconds;

                    await SetStick(SwitchStick.LEFT, x, y, 2 *fastSleep, token).ConfigureAwait(false);

                    if (await ReadIsChanged(SurpriseTradeSearchOffset, searching, token).ConfigureAwait(false))
                    {
                        return(true);
                    }

                    // wait the rest of this step's delay
                    var wait = delay - (sw.ElapsedMilliseconds - now);

                    if (wait > 0)
                    {
                        await Task.Delay((int)wait, token).ConfigureAwait(false);
                    }
                    return(false);
                }
            }

            // Gracefully clean up
            await Connection.SendAsync(SwitchCommand.ResetStick(SwitchStick.LEFT), token).ConfigureAwait(false);

            await Task.Delay(fastSleep, token).ConfigureAwait(false);

            await Connection.SendAsync(SwitchCommand.Configure(SwitchConfigureParameter.mainLoopSleepTime, defaultSleep), token).ConfigureAwait(false);

            await Task.Delay(defaultSleep, token).ConfigureAwait(false);

            return(changed);
        }
Exemple #26
0
 public MainViewModel()
 {
     StartCommand = new SwitchCommand<MainViewModel, SearchViewModel>(this, () => true);
 }
Exemple #27
0
        static int Main(string[] commandLineArgs)
        {
            if (commandLineArgs.Length == 0)
            {
                ShowConsoleMessage(string.Empty, true);
                return((int)ReturnCode.Invalid);
            }

            AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);

            // Create a list of switch type and whether requires or not.
            Dictionary <SwitchType, bool> commandSwitchOption = new Dictionary <SwitchType, bool>();

            commandSwitchOption.Add(SwitchType.Operation, true);
            commandSwitchOption.Add(SwitchType.Help, true);

            // Create a list of switch commands as passed on the command line
            List <SwitchCommand> switchCommandList = new List <SwitchCommand>();

            // Processing all command arguments
            foreach (string argument in commandLineArgs)
            {
                // Check for a valid switch syntax
                if (!argument.StartsWith("/", StringComparison.OrdinalIgnoreCase) && !argument.StartsWith("-", StringComparison.OrdinalIgnoreCase))
                {
                    ShowConsoleMessage(string.Format(CultureInfo.InvariantCulture, "\nError : Invalid switch '{0}'. Please check help for valid switches.\n", argument), true);
                    return((int)ReturnCode.Invalid);
                }

                // Check for a valid switch command and value separator character
                string[] arrArgSplit = argument.Split(new char[] { ':', '=' }, 2);
                if (arrArgSplit.Length != 2)
                {
                    ShowConsoleMessage(string.Format(CultureInfo.InvariantCulture, "\nError : Invalid switch and value pattern '{0}'.\n", argument), false);
                    return((int)ReturnCode.Invalid);
                }

                // Create a valid switch command object. Show error if there is an problem.
                try
                {
                    SwitchCommand switchCommand = new SwitchCommand(arrArgSplit[0].Substring(1), arrArgSplit[1]);
                    switchCommandList.Add(switchCommand);
                }
                catch
                {
                    ShowConsoleMessage(string.Format(CultureInfo.InvariantCulture, "\nError : Invalid switch '{0}'\n", arrArgSplit[0].Substring(1)), true);
                    return((int)ReturnCode.Invalid);
                }
            }

            // Fetch the mandatory switches
            IEnumerable <SwitchType> mandatorySwitchTypes = commandSwitchOption.Where(switchOption => switchOption.Value).Select(switchOption => switchOption.Key);

            int countMandatory = (from SwitchCommand commandSwitch in switchCommandList
                                  join SwitchType switchType in mandatorySwitchTypes on commandSwitch.Switch equals switchType
                                  select commandSwitch.Switch).Count();

            if (countMandatory == 0)
            {
                ShowConsoleMessage(string.Format(CultureInfo.InvariantCulture, "\nError : Incorrect number of mandatory parameters.\n"), true);
                return((int)ReturnCode.Invalid);
            }

            return(ProcessCommands(switchCommandList));
        }
Exemple #28
0
        public void DashSwitches(string id, string state)
        {
            IHalationCommand cmd = new SwitchCommand(Halation.CurrentSelectedLine, this.GetIndent(Halation.CurrentSelectedLine), Halation.currentCodePackage, id, state);

            HalationInvoker.Dash(Halation.currentScriptName, cmd);
        }
 void OnPlayerSwitchedCharacter(SwitchCommand arg)
 {
     Debug.LogFormat("{0} wants to switch to {1}.", arg.Player.name, arg.SwitchTarget.name);
     _battleSystem.RegisterPlayerCommand(arg);
 }