public GpioConfigRoot LoadConfig() { if (!Directory.Exists(Constants.ConfigDirectory)) { Logger.Log("Such a folder doesn't exist, creating one..."); Directory.CreateDirectory(Constants.ConfigDirectory); } if (!File.Exists(Constants.GpioConfigPath) && !GenerateDefaultConfig()) { return(null); } string JSON; Logger.Log("Loading Gpio config...", Enums.LogLevels.Trace); ConfigSemaphore.Wait(); using (FileStream Stream = new FileStream(Constants.GpioConfigPath, FileMode.Open, FileAccess.Read)) { using (StreamReader ReadSettings = new StreamReader(Stream)) { JSON = ReadSettings.ReadToEnd(); } } GpioConfigRoot config = JsonConvert.DeserializeObject <GpioConfigRoot>(JSON); ConfigSemaphore.Release(); Logger.Log("Gpio configuration loaded successfully!", Enums.LogLevels.Trace); return(config); }
public bool GenerateDefaultConfig() { Logger.Log("GPIO config file doesnt exist. press c to continue generating default config or q to quit."); ConsoleKeyInfo?Key = Helpers.FetchUserInputSingleChar(TimeSpan.FromMinutes(1)); if (!Key.HasValue) { Logger.Log("No value has been entered, continuing to run the program..."); } else { switch (Key.Value.KeyChar) { case 'c': break; case 'q': System.Threading.Tasks.Task.Run(async() => await Core.Exit().ConfigureAwait(false)); return(false); default: Logger.Log("Unknown value entered! continuing to run the program..."); break; } } Logger.Log("Generating default GPIO Config..."); if (!Directory.Exists(Constants.ConfigDirectory)) { Logger.Log("Config directory doesnt exist, creating one..."); Directory.CreateDirectory(Constants.ConfigDirectory); } if (File.Exists(Constants.GpioConfigPath)) { return(true); } GpioConfigRoot Config = new GpioConfigRoot { GPIOData = new List <GpioPinConfig>() }; for (int i = 0; i <= 31; i++) { GpioPinConfig PinConfig = new GpioPinConfig() { IsOn = false, Mode = Enums.PinMode.Output, Pin = i }; Config.GPIOData.Add(PinConfig); } SaveGPIOConfig(Config); return(true); }
public GpioConfigRoot SaveGPIOConfig(GpioConfigRoot config) { if (!Directory.Exists(Constants.ConfigDirectory)) { Logger.Log("Config folder doesn't exist, creating one..."); Directory.CreateDirectory(Constants.ConfigDirectory); } string filePath = Constants.GpioConfigPath; string json = JsonConvert.SerializeObject(config, Formatting.Indented); string newFilePath = filePath + ".new"; ConfigSemaphore.Wait(); Core.ConfigWatcher.FileSystemWatcher.EnableRaisingEvents = false; try { File.WriteAllText(newFilePath, json); if (File.Exists(filePath)) { File.Replace(newFilePath, filePath, null); } else { File.Move(newFilePath, filePath); } } catch (Exception e) { Logger.Log(e); Core.ConfigWatcher.FileSystemWatcher.EnableRaisingEvents = true; return(config); } finally { ConfigSemaphore.Release(); } Core.ConfigWatcher.FileSystemWatcher.EnableRaisingEvents = true; Logger.Log("Saved config!", Enums.LogLevels.Trace); return(config); }