using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Linq; using System.Xml.Linq; using System.Diagnostics; namespace libThermoControl { public static class Configuration { private const string config_file = "config.xml"; private const string temp_file = "current_temp.bin"; public static int CurrentTemp { get { return ReadTemp(); } set { WriteTemp(value); } } public static readonly string THERMISTAT_DEVICE = ""; // 60 public static readonly int MIN_TEMP = 0; // 60 public static readonly int MAX_TEMP = 0; // 90 public static readonly int DEFAULT_TEMP = 0; // 70 public static readonly string DEFAULT_MODE = ""; // cool public static readonly string DEFAULT_FAN_SPEED = ""; // auto_fan [Conditional("CONFIG_UNITTEST")] public static void UnitTest() { } static Configuration() { // load configuration //using (FileStream fs = new FileStream(config_file, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ //} XDocument xdoc = XDocument.Load(config_file); Type p = typeof(Configuration); var fields = new List(p.GetFields(BindingFlags.Public | BindingFlags.Static)); foreach (var field in fields) { //Console.WriteLine("Name: '{0}' value: '{1}'", field.Name, xdoc); //var lv1s = from lv1 in xdoc.Descendants("level1") // select lv1.Attribute("name").Value; //var t = xdoc.Root.DescendantNodesAndSelf().ToList(); var o = xdoc.Root.Elements(field.Name); var list = o.ToList(); if (list.Count == 0) { Console.WriteLine("Name: '{0}' Default: '{1}' Configured: '{1}'", field.Name, field.GetValue(null).ToString()); } else { var t = xdoc.Root.Elements(field.Name).ToList().FirstOrDefault().Value; Console.WriteLine("Name: '{0}' Default: '{1}' Configured: '{2}'", field.Name, field.GetValue(null).ToString(), t); field.SetValue(null, Convert.ChangeType(t,field.FieldType)); } } // get the current temp from file //ReadTemp(); } static void WriteTemp(int temp) { using (FileStream fs = new FileStream(temp_file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) { using (BinaryWriter bw = new BinaryWriter(fs)) { bw.Write((byte)temp); bw.Flush(); bw.Close(); } } } static int ReadTemp() { int temp = 0; if (!File.Exists(temp_file)) { WriteTemp(Configuration.DEFAULT_TEMP); } else { FileInfo fi = new FileInfo(temp_file); if (fi.Length == 0) { WriteTemp(Configuration.DEFAULT_TEMP); } } using (FileStream fs = new FileStream(temp_file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read)) { using (BinaryReader br = new BinaryReader(fs)) { temp = br.ReadByte(); br.Close(); } } return temp; } } }