Esempio n. 1
0
        private static async Task DisplayConsoleCommandMenu()
        {
            Logger.Log("Displaying console command window", LogLevels.Trace);
            Logger.Log($"------------------------- COMMAND WINDOW -------------------------", LogLevels.Input);
            Logger.Log($"{Constants.ConsoleShutdownKey} - Shutdown assistant.", LogLevels.Input);

            if (PiGpioController.IsAllowedToExecute)
            {
                Logger.Log($"{Constants.ConsoleRelayCommandMenuKey} - Display relay pin control menu.", LogLevels.Input);
                Logger.Log($"{Constants.ConsoleRelayCycleMenuKey} - Display relay cycle control menu.", LogLevels.Input);

                if (Config.EnableModules)
                {
                    Logger.Log($"{Constants.ConsoleModuleShutdownKey} - Invoke shutdown method on all currently running modules.", LogLevels.Input);
                }

                Logger.Log($"{Constants.ConsoleMorseCodeKey} - Morse code generator for the specified text.", LogLevels.Input);
            }

            Logger.Log($"{Constants.ConsoleTestMethodExecutionKey} - Run preconfigured test methods or tasks.", LogLevels.Input);

            if (WeatherClient != null)
            {
                Logger.Log($"{Constants.ConsoleWeatherInfoKey} - Get weather info of the specified location based on the pin code.", LogLevels.Input);
            }

            Logger.Log($"-------------------------------------------------------------------", LogLevels.Input);
            Logger.Log("Awaiting user input: \n", LogLevels.Input);

            int failedTriesCount = 0;
            int maxTries         = 3;

            while (true)
            {
                if (failedTriesCount > maxTries)
                {
                    Logger.Log($"Multiple wrong inputs. please start the command menu again  by pressing {Constants.ConsoleCommandMenuKey} key.", LogLevels.Warn);
                    return;
                }

                char pressedKey = Console.ReadKey().KeyChar;

                switch (pressedKey)
                {
                case Constants.ConsoleShutdownKey:
                    Logger.Log("Shutting down assistant...", LogLevels.Warn);
                    await Task.Delay(1000).ConfigureAwait(false);
                    await Exit(0).ConfigureAwait(false);

                    return;

                case Constants.ConsoleRelayCommandMenuKey when PiGpioController.IsAllowedToExecute:
                    Logger.Log("Displaying relay command menu...", LogLevels.Warn);
                    DisplayRelayCommandMenu();
                    return;

                case Constants.ConsoleRelayCycleMenuKey when PiGpioController.IsAllowedToExecute:
                    Logger.Log("Displaying relay cycle menu...", LogLevels.Warn);
                    await DisplayRelayCycleMenu().ConfigureAwait(false);

                    return;

                case Constants.ConsoleRelayCommandMenuKey when !PiGpioController.IsAllowedToExecute:
                case Constants.ConsoleRelayCycleMenuKey when !PiGpioController.IsAllowedToExecute:
                    Logger.Log("Assistant is running in an Operating system/Device which doesn't support GPIO pin controlling functionality.", LogLevels.Warn);
                    return;

                case Constants.ConsoleMorseCodeKey when PiGpioController.IsAllowedToExecute:
                    if (Controller == null)
                    {
                        return;
                    }

                    Logger.Log("Enter text to convert to Morse: ");
                    string morseCycle = Console.ReadLine();
                    GpioMorseTranslator?morseTranslator = PiGpioController.GetMorseTranslator();

                    if (morseTranslator == null || !morseTranslator.IsTranslatorOnline)
                    {
                        Logger.Warning("Morse translator is offline or unavailable.");
                        return;
                    }

                    await morseTranslator.RelayMorseCycle(morseCycle, Config.OutputModePins[0]).ConfigureAwait(false);

                    return;

                case Constants.ConsoleWeatherInfoKey:
                    Logger.Log("Please enter the pin code of the location: ");
                    int counter = 0;

                    int pinCode;
                    while (true)
                    {
                        if (counter > 4)
                        {
                            Logger.Log("Failed multiple times. aborting...");
                            return;
                        }

                        try {
                            pinCode = Convert.ToInt32(Console.ReadLine());
                            break;
                        }
                        catch {
                            counter++;
                            Logger.Log("Please try again!", LogLevels.Warn);
                            continue;
                        }
                    }

                    if (string.IsNullOrEmpty(Config.OpenWeatherApiKey))
                    {
                        Logger.Warning("Weather api key cannot be null.");
                        return;
                    }

                    if (WeatherClient == null)
                    {
                        Logger.Warning("Weather client is not initiated.");
                        return;
                    }

                    WeatherResponse?response = await WeatherClient.GetWeather(Config.OpenWeatherApiKey, pinCode, "in").ConfigureAwait(false);

                    if (response == null)
                    {
                        Logger.Warning("Failed to fetch weather response.");
                        return;
                    }

                    Logger.Log($"------------ Weather information for {pinCode}/{response.LocationName} ------------", LogLevels.Green);

                    if (response.Data != null)
                    {
                        Logger.Log($"Temperature: {response.Data.Temperature}", LogLevels.Green);
                        Logger.Log($"Humidity: {response.Data.Humidity}", LogLevels.Green);
                        Logger.Log($"Pressure: {response.Data.Pressure}", LogLevels.Green);
                    }

                    if (response.Wind != null)
                    {
                        Logger.Log($"Wind speed: {response.Wind.Speed}", LogLevels.Green);
                    }

                    if (response.Location != null)
                    {
                        Logger.Log($"Latitude: {response.Location.Latitude}", LogLevels.Green);
                        Logger.Log($"Longitude: {response.Location.Longitude}", LogLevels.Green);
                        Logger.Log($"Location name: {response.LocationName}", LogLevels.Green);
                    }

                    return;

                case Constants.ConsoleTestMethodExecutionKey:
                    Logger.Log("Executing test methods/tasks", LogLevels.Warn);
                    Logger.Log("Test method execution finished successfully!", LogLevels.Green);
                    return;

                case Constants.ConsoleModuleShutdownKey when Modules.Count > 0 && Config.EnableModules:
                    Logger.Log("Shutting down all modules...", LogLevels.Warn);
                    ModuleLoader.OnCoreShutdown();
                    return;

                case Constants.ConsoleModuleShutdownKey when Modules.Count <= 0:
                    Logger.Log("There are no modules to shutdown...");
                    return;

                default:
                    if (failedTriesCount > maxTries)
                    {
                        Logger.Log($"Unknown key was pressed. ({maxTries - failedTriesCount} tries left)", LogLevels.Warn);
                    }

                    failedTriesCount++;
                    continue;
                }
            }
        }
Esempio n. 2
0
        public async Task ExecuteAsync(Parameter parameter)
        {
            if (!IsInitSuccess)
            {
                return;
            }

            if (parameter.Parameters.Length > MaxParameterCount)
            {
                ShellOut.Error("Too many arguments.");
                return;
            }

            await Sync.WaitAsync().ConfigureAwait(false);

            MorseCore morseCore = GpioMorseTranslator.GetCore();
            string    morse     = string.Empty;

            try {
                if (OnExecuteFunc != null)
                {
                    if (OnExecuteFunc.Invoke(parameter))
                    {
                        return;
                    }
                }

                switch (parameter.ParameterCount)
                {
                case 1 when !string.IsNullOrEmpty(parameter.Parameters[0]):
                    morse = morseCore.ConvertToMorseCode(parameter.Parameters[0]);

                    if (string.IsNullOrEmpty(morse) || !morseCore.IsValidMorse(morse))
                    {
                        ShellOut.Error("Failed to verify generated morse code.");
                        return;
                    }

                    ShellOut.Info(">>> " + morse);
                    return;

                case 2 when !string.IsNullOrEmpty(parameter.Parameters[0]) && !string.IsNullOrEmpty(parameter.Parameters[1]):
                    morse = morseCore.ConvertToMorseCode(parameter.Parameters[0]);

                    if (string.IsNullOrEmpty(morse) || !morseCore.IsValidMorse(morse))
                    {
                        ShellOut.Error("Failed to verify generated morse code.");
                        return;
                    }

                    ShellOut.Info(">>> " + morse);
                    GpioMorseTranslator?translator = PiGpioController.GetMorseTranslator();

                    if (translator == null || !translator.IsTranslatorOnline)
                    {
                        ShellOut.Error("Morse translator might be offline.");
                        return;
                    }

                    if (!int.TryParse(parameter.Parameters[1], out int relayNumber))
                    {
                        ShellOut.Error("Relay number argument is invalid.");
                        return;
                    }

                    if (!PinController.IsValidPin(PiGpioController.AvailablePins.OutputPins[relayNumber]))
                    {
                        ShellOut.Error("The specified pin is invalid.");
                        return;
                    }

                    await translator.RelayMorseCycle(morse, PiGpioController.AvailablePins.OutputPins[relayNumber]);

                    ShellOut.Info("Completed!");
                    return;

                default:
                    ShellOut.Error("Command seems to be in incorrect syntax.");
                    return;
                }
            }
            catch (Exception e) {
                ShellOut.Exception(e);
                return;
            }
            finally {
                Sync.Release();
            }
        }