diff --git a/.gitignore b/.gitignore index dca30eb..e457544 100644 --- a/.gitignore +++ b/.gitignore @@ -37,22 +37,13 @@ AlexaComp/bin AlexaComp/obj AlexaComp/pathDir.xml -AlexaComp/AlexaCompTESTS.cs -AlexaComp/SavedMethods.cs -Deprecated/ -AlexaComp/_SubProjects/CompatibilityTool/bin/Debug/Images -AlexaComp/_SubProjects/CompatibilityTool/bin/Debug/Layouts -AlexaComp/_SubProjects/CompatibilityTool/bin/Debug/x86 -AlexaComp/_SubProjects/CompatibilityTool/bin/Debug/x64 -AlexaComp/HardwareDevice.cs -AlexaComp/LightingController.cs AlexaComp/Setup *packages/ *node_modules/ -*config.json -Setup1/ +config.json setup.exe *package.zip +*Config.cs # Visual Studio 2015/2017 cache/options directory .vs/ @@ -60,10 +51,10 @@ setup.exe *.code-workspace # Config -AlexaComp/App.config *.pfx Lambda/Main_Lambda/Device_Linking_Email/config.py AlexaComp/testCommands.txt AlexaComp/CompatibilityTool/obj/Debug/CompatibilityTool.csprojAssemblyReference.cache AlexaComp/CompatibilityTool/obj/Debug/CompatibilityTool.csprojAssemblyReference.cache *.cache +AlexaComp/GlobalSuppressions.cs diff --git a/AlexaComp/AlexaComp.cs b/AlexaComp/AlexaComp.cs index 9ed2336..1177f3e 100644 --- a/AlexaComp/AlexaComp.cs +++ b/AlexaComp/AlexaComp.cs @@ -1,14 +1,14 @@ using System; -using System.Configuration; -using System.Threading; -using System.Net; -using System.Text.RegularExpressions; +using System.Diagnostics; +using System.Windows.Forms; -using log4net; using log4net.Config; -// TODO : Documentation -// TODO : Add region tags to files where appropriate. +using AlexaComp.Core; +using AlexaComp.Forms; +using AlexaComp.Core.Requests; +using AlexaComp.Core.Controllers; + /** Documentation format * Description * @param @@ -17,85 +17,73 @@ */ namespace AlexaComp { - class AlexaComp : AlexaCompCore{ + class AlexaComp : AlexaCompCore { [STAThread] static void Main(string[] args) { + Stopwatch timer = new Stopwatch(); + timer.Start(); XmlConfigurator.Configure(); AppDomain.CurrentDomain.UnhandledException += (s, e) => { var exception = (Exception)e.ExceptionObject; - clog(exception.ToString(), "FATAL"); + Clog(exception.ToString(), "FATAL"); throw exception; }; - clog("Exception Handler Registered"); + + Clog("Exception Handler Registered"); _log.Info("Start Program"); - // Parse cli args - foreach (string arg in args) { - if ("-LogSensors".Contains(arg)) { - Thread LogSensorsThread = new Thread(new ParameterizedThreadStart(AlexaCompHARDWARE.getAllSensors)); - LogSensorsThread.Start(false); - } - if ("-GetPrograms".Contains(arg)) { - - } - if ("-AddProgram".Contains(arg)) { - if ("--AddProgramLiteral".Contains(arg)) { - - } - } - } - // Log Assembly and Environment Information System.Reflection.Assembly Assembly = System.Reflection.Assembly.GetEntryAssembly(); - clog("Assembly.GetName()"); - clog(" GetName - " + Assembly.GetName().ToString()); - clog(" Name - " + Assembly.GetName().Name); - clog(" Version - " + Assembly.GetName().Version); - clog(" VersionCompatibility - " + Assembly.GetName().VersionCompatibility); - clog(" FullName - " + Assembly.FullName); - clog(" HostContext - " + Assembly.HostContext.ToString()); - clog(" IsFullyTrusted - " + Assembly.IsFullyTrusted.ToString()); - clog("System.Environment"); - clog(" OSVersion - " + Environment.OSVersion); - clog(" Version - " + Environment.Version); - clog(" CurrentManagedThreadID - " + Environment.CurrentManagedThreadId.ToString()); - clog(" Is64BitOS - " + Environment.Is64BitOperatingSystem.ToString()); - clog(" Is64BitProcess - " + Environment.Is64BitProcess.ToString()); - clog(" WorkingSet - " + Environment.WorkingSet.ToString()); - clog("Target Framework - " + AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName); - clog("Executable Path - " + exePath.ToString()); - clog("PathToDebug - " + pathToDebug); - clog("PathToProject - " + pathToProject); + Clog("Assembly.GetName()"); + Clog(" GetName - " + Assembly.GetName().ToString()); + Clog(" Name - " + Assembly.GetName().Name); + Clog(" Version - " + Assembly.GetName().Version); + Clog(" VersionCompatibility - " + Assembly.GetName().VersionCompatibility); + Clog(" FullName - " + Assembly.FullName); + Clog(" HostContext - " + Assembly.HostContext.ToString()); + Clog(" IsFullyTrusted - " + Assembly.IsFullyTrusted.ToString()); + Clog("System.Environment"); + Clog(" OSVersion - " + Environment.OSVersion); + Clog(" Version - " + Environment.Version); + Clog(" CurrentManagedThreadID - " + Environment.CurrentManagedThreadId.ToString()); + Clog(" Is64BitOS - " + Environment.Is64BitOperatingSystem.ToString()); + Clog(" Is64BitProcess - " + Environment.Is64BitProcess.ToString()); + Clog(" WorkingSet - " + Environment.WorkingSet.ToString()); + Clog("Target Framework - " + AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName); + Clog("Executable Path - " + exePath.ToString()); + Clog("PathToDebug - " + pathToDebug); + Clog("PathToProject - " + pathToProject); - getExternalIP(); - - LoadingScreenThread.Start(); - } - - - /* - * Reads all user configured values into the settingsDict. - */ - public static void readConfig(){ - foreach (string key in ConfigurationManager.AppSettings.AllKeys){ - settingsDict[key] = GetConfigValue(key); + if (!IsConnectedToInternet()) { + Clog("No Internet Connection Detected... Quitting...", "FATAL"); + MessageBox.Show("No Internet Connection Detected, Stopping AlexaComp...", + "AlexaComp", + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + StopApplication(); } - } - /* - * Gets the user's public IP address. - */ - public static void getExternalIP() { - string data = new WebClient().DownloadString("http://checkip.dyndns.org/"); - Match match = Regex.Match(data, @"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"); // Regex match for IP - if (match.Success) { - clog("Public IP - " + match); - } else { - clog("IP Regex Match Unsuccessful.", "ERROR"); + // Set Internal IP for port mapping and server + try { + string host = GetInternalIP(); + Clog("Internal IP Found - " + host); + ServerConfig.HOST = host; + } catch (Exception) { + Clog("No Network Adapters With IPv4 Addresses Detected, Cannot Start Server... Quitting...", "FATAL"); + MessageBox.Show("No Network Adapters With IPv4 Addresses Detected, Cannot Start Server. Stopping AlexaComp...", + "AlexaComp", + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + StopApplication(); } + + GetExternalIP(); + + Clog("Initializing Hardware Sensors"); + + loadingScreenThread.Start(timer); } } } - diff --git a/AlexaComp/AlexaComp.csproj b/AlexaComp/AlexaComp.csproj index 053ce05..9f49dbf 100644 --- a/AlexaComp/AlexaComp.csproj +++ b/AlexaComp/AlexaComp.csproj @@ -32,7 +32,7 @@ Ari Madian true 0 - 1.0.2.0 + 1.0.3.0 false true true @@ -170,9 +170,20 @@ + + + + + + + + + + + Form @@ -187,8 +198,6 @@ - - @@ -197,6 +206,7 @@ LoadingScreenForm.cs + @@ -269,9 +279,7 @@ File - - - + diff --git a/AlexaComp/AlexaCompCore.cs b/AlexaComp/AlexaCompCore.cs index 0a93303..9d3fe9a 100644 --- a/AlexaComp/AlexaCompCore.cs +++ b/AlexaComp/AlexaCompCore.cs @@ -2,15 +2,15 @@ using System.Collections.Generic; using System.Configuration; using AlexaComp.Controllers; -using System.Diagnostics; using System.Linq; -using System.Text; +using System.Text.RegularExpressions; +using System.Net; using System.Threading; -using System.IO; -using System.Security.Cryptography; using log4net; -using log4net.Config; + +using AlexaComp.Core; +using System.Net.Sockets; namespace AlexaComp { @@ -18,7 +18,9 @@ namespace AlexaComp { // TODO : Implement input validation on all functions. // TODO : Create format validation functions. - class AlexaCompCore { + #pragma warning disable CA1052 // Static holder types should be Static or NotInheritable + public class AlexaCompCore { + #pragma warning restore CA1052 // Static holder types should be Static or NotInheritable #region Properties public static string exePath = System.Reflection.Assembly.GetEntryAssembly().Location; @@ -28,10 +30,10 @@ class AlexaCompCore { // Threads public static Thread AppWindowThread = new Thread(AlexaCompGUI.StartAppWindow) { Name = "AppWindowThread" }; - public static Thread ServerThread = new Thread(AlexaCompSERVER.startServer) { Name = "ServerThread" }; + public static Thread ServerThread = new Thread(AlexaCompSERVER.StartServer) { Name = "ServerThread" }; public static Thread ServerLoopThread = new Thread(AlexaCompSERVER.ServerLoop) { Name = "ServerLoopThread" }; - public static Thread LoadingScreenThread = new Thread(LoadingScreenForm.startLoadingScreen) { Name = "LoadingScreenThread" }; - public static Thread LightingControlThread = new Thread(LightingController.startLightingThread) { Name = "LightingControlThread" }; + public static Thread loadingScreenThread = new Thread(new ParameterizedThreadStart(LoadingScreenForm.StartLoadingScreen)); + public static Thread LightingControlThread = new Thread(LightingController.StartLightingThread) { Name = "LightingControlThread" }; // Misc public static bool updateLogBoxFlag = false; @@ -41,9 +43,10 @@ class AlexaCompCore { #endregion + public static Dictionary Devices = new Dictionary(); #region Methods - public static void clog(string tolog, string customLevel = "INFO") { + public static void Clog(string tolog, string customLevel = "INFO") { switch (customLevel) { case "ERROR": _log.Error(tolog); break; case "INFO" : _log.Info(tolog); break; @@ -54,23 +57,41 @@ class AlexaCompCore { Console.WriteLine(tolog); } - public static void stopApplication() { - clog("CLOSING PROGRAM"); + public static void StopApplication() { + Clog("CLOSING PROGRAM"); stopProgramFlag = true; - AlexaCompSERVER.stopServer(); - AlexaCompSERVER.delPortMap(); + try { + AlexaCompSERVER.StopServer(); + } catch (NullReferenceException) { + Clog("NullReferenceException Caught When Stopping Server"); + } catch (Exception e) { + Clog("Exception Caught When Stopping Server \n" + e); + } + + try { + AlexaCompSERVER.DelPortMap(); + } catch (NullReferenceException) { + Clog("NullReferenceException Caught When Deleting Port Maps"); + } catch (Exception e) { + Clog("Exception Caught When Deleting Port Maps\n" + e); + } + Clog("Exiting..."); Environment.Exit(1); } - public static bool validateRGB(RGBColor color) { - int[] rgbArr = colorMethods.RGBToArr(color); - foreach (var value in rgbArr) { - if (255 < value || value < 0) { - clog("Invalid RGB - Value Greater Than 255, or Less Than 0."); - return false; + public static bool IsConnectedToInternet(bool log = true) { + Clog("Checking For Internet Connection..."); + try { + using (var client = new WebClient()) + using (client.OpenRead("http://clients3.google.com/generate_204")) { + if (log) { Clog("Internet Connection DOES exist."); } + return true; } } - return true; + catch { + if (log) { Clog("Internet Connection DOES NOT exist."); } + return false; + } } /// @@ -86,6 +107,40 @@ class AlexaCompCore { return ConfigurationManager.AppSettings[key]; } + + /* + * Gets the user's public IP address. + */ + public static void GetExternalIP() { + string data = new WebClient().DownloadString("http://checkip.dyndns.org/"); + Match match = Regex.Match(data, @"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"); // Regex match for IP + if (match.Success) { + Clog("Public IP - " + match); + } + else { + Clog("IP Regex Match Unsuccessful.", "ERROR"); + } + } + + public static string GetInternalIP() { + var host = Dns.GetHostEntry(Dns.GetHostName()); + foreach (var ip in host.AddressList) { + if (ip.AddressFamily == AddressFamily.InterNetwork) { + return ip.ToString(); + } + } + throw new Exception(); + } + + /* + * Reads all user configured values into the settingsDict. + */ + public static void ReadConfig() { + foreach (string key in ConfigurationManager.AppSettings.AllKeys) { + settingsDict[key] = GetConfigValue(key); + } + } + #endregion } } diff --git a/AlexaComp/AlexaCompHARDWARE.cs b/AlexaComp/AlexaCompHARDWARE.cs deleted file mode 100644 index c3df26e..0000000 --- a/AlexaComp/AlexaCompHARDWARE.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -using OpenHardwareMonitor.Hardware; -using log4net; -using log4net.Config; - -using AlexaComp.Core; - -namespace AlexaComp{ - class AlexaCompHARDWARE : AlexaCompCore{ - - #region Properties - private const string failMessage = "There was an error, please check the Alexa Comp log file."; - public static List partNames = new List() { "GPU", "CPU", "RAM", "MAINBOARD", "HDD", "FANCONTROLLER" }; - public static Dictionary> partDict = new Dictionary>() { - { "GPU", new Dictionary {{"TEMP", ""}, {"LOAD", ""}, {"CLOCK_CORE", ""}, {"CLOCK_RAM", ""}}}, - { "CPU", new Dictionary {{"TEMP", ""}, {"LOAD", ""}, {"CLOCK_CORE", ""}}}, - { "RAM", new Dictionary {{"USED", "Used Memory"}, {"AVAILABLE", "Available Memory"}}}, - { "MAINBOARD", new Dictionary {}} - }; - #endregion - - #region Methods - public static string partStat(string part, string stat, string tertiary){ - UpdateVisitor updateVisitor = new UpdateVisitor(); - Computer computer = new Computer(); - computer.Open(); - partOneHot(computer, part); - computer.Accept(updateVisitor); - try { - Console.WriteLine(partDict[part][stat]); - } catch (KeyNotFoundException e) { - clog("KeyNotFoundException during attempt to get part stat " + e.Message); - Response res = new Response(false, failMessage, "", ""); - return "null"; - } - - int hwLength = computer.Hardware.Length; - for (int i = 0; i < hwLength; i++){ - for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++){ - foreach (ISensor sensor in computer.Hardware[i].Sensors) { - if (sensor.Name == partDict[part][stat]) { - if (getSensorType(sensor) == tertiary) { - return sensor.Value.ToString() + " Mega Hertz"; - } - } - } - } - computer.Close(); - return "null"; - } - return "null"; - } - - public static string getSensorType(ISensor sensor) { - return sensor.SensorType.ToString(); - } - - public static void assignSensors() { - foreach (string part in partNames) { - UpdateVisitor updateVisitor = new UpdateVisitor(); - Computer computer = new Computer(); - computer.Open(); - partOneHot(computer, part); - computer.Accept(updateVisitor); - for (int i = 0; i < computer.Hardware.Length; i++) { - for (int k = 0; k < computer.Hardware.Length; k++) { - for (int j = 0; j < computer.Hardware[k].Sensors.Length; j++) { - var currentSensor = computer.Hardware[k].Sensors[j]; - if (currentSensor.SensorType == SensorType.Temperature) { // If sensor is a temp sensor - try { - partDict[part]["TEMP"] = currentSensor.Name; - } catch (KeyNotFoundException) {} - } - - // TODO: Implement switch case - if (currentSensor.SensorType == SensorType.Clock) { - Console.WriteLine("Clock Sensor"); - if (currentSensor.Name.Contains("Core")) { - Console.WriteLine("Core Clock Sensor"); - partDict[part]["CLOCK_CORE"] = currentSensor.Name; - } else if (currentSensor.Name.Contains("Memory")) { - Console.WriteLine("Ram Clock Sensor"); - partDict[part]["CLOCK_RAM"] = currentSensor.Name; - } - } - - if (currentSensor.SensorType == SensorType.Load) { // If sensor is a load sensor - try { - partDict[part]["LOAD"] = currentSensor.Name; - } - catch (KeyNotFoundException) {} - } else if (currentSensor.SensorType == SensorType.Load && // Else if the hardware is a CPU get total load, not core loads. - part == "CPU" && "Total".Contains(currentSensor.Name)) { - partDict[part]["LOAD"] = currentSensor.Name; - } - } - } - computer.Close(); - } - } - foreach(KeyValuePair> pair in partDict) { - Console.WriteLine("Part - " + pair.Key); - foreach (KeyValuePair pair2 in pair.Value) { - Console.WriteLine(" " + pair2.Key + " - " + pair2.Value); - } - } - } - - // Clicking log all sensors button quickly triggers nullreferenceexception in this method - public static void partOneHot(Computer comp, string part){ - if (part == "GPU") { comp.GPUEnabled = true; } - else if (part == "CPU") { comp.CPUEnabled = true; } - else if (part == "RAM") { comp.RAMEnabled = true; } - else if (part == "MAINBOARD") { comp.MainboardEnabled = true; } - else if (part == "HDD") { comp.HDDEnabled = true; } - else if (part == "FANCONTROLLER") { comp.FanControllerEnabled = true; } - } - - public static void getAllSensors(object openOnComplete){ - bool openOnCompleteBool = (bool)openOnComplete; - ILog _SensorListLogger = LogManager.GetLogger("SensorListAppender"); - XmlConfigurator.Configure(); - foreach (string part in partNames){ - UpdateVisitor updateVisitor = new UpdateVisitor(); - Computer computer = new Computer(); - computer.Open(); - partOneHot(computer, part); - computer.Accept(updateVisitor); - for (int i = 0; i < computer.Hardware.Length; i++){ // For part - _SensorListLogger.Info(part + " - " + computer.Hardware[i].Name + - " - Hardware Length " + computer.Hardware.Length.ToString()); - for (int k = 0; k < computer.Hardware.Length; k++) { // For hardware in part - var currentHardware = computer.Hardware[k]; - _SensorListLogger.Info(string.Format(" Hardware {0}/ {1} - " + currentHardware.Name, k + 1, computer.Hardware.Length.ToString())); - _SensorListLogger.Info(" Sensors Length - " + currentHardware.Sensors.Length.ToString()); - for (int j = 0; j < computer.Hardware[k].Sensors.Length; j++){ // For sensor in hardware - _SensorListLogger.Info("\t" + computer.Hardware[k].Sensors[j].Name + " - " + - computer.Hardware[k].Sensors[j].SensorType + " - " + - computer.Hardware[k].Sensors[j].Value); - } - } - computer.Close(); - } - } - if (openOnCompleteBool){ - System.Diagnostics.Process.Start(AlexaComp.pathToDebug + "\\SensorList.txt"); - } - } - - public static int loadFormat(float? loadFloat) { return (int)loadFloat; } - public static int tempFormat(float? tempFloat) { return (int)tempFloat; } - #endregion - } - - public class UpdateVisitor : IVisitor{ - public void VisitComputer(IComputer computer){ - computer.Traverse(this); - } - public void VisitHardware(IHardware hardware){ - hardware.Update(); - foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this); - } - public void VisitSensor(ISensor sensor) { } - public void VisitParameter(IParameter parameter) { } - } -} diff --git a/AlexaComp/AlexaCompREQUEST.cs b/AlexaComp/AlexaCompREQUEST.cs deleted file mode 100644 index 88ce690..0000000 --- a/AlexaComp/AlexaCompREQUEST.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System; -using System.Xml; -using System.Diagnostics; -using System.Runtime.InteropServices; -using AlexaComp.Controllers; -using System.Threading; - -using AlexaComp.Forms; -using AlexaComp.Core; - -namespace AlexaComp { - class AlexaCompREQUEST : AlexaCompCore { - - [DllImport("user32.dll")] - private static extern bool ExitWindowsEx(uint uFlags, uint dwReason); - - [DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)] - public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent); - - private const string failMessage = "There was an error, please check the Alexa Comp log file."; - public static void processRequest(Request req) { - switch (req.COMMAND) { - case "LAUNCH": launchRequest(req); break; - case "COMPUTERCOMMAND": commandRequest(req); break; - case "GETCOMPSTAT": compStatRequest(req); break; - case "AUDIOCOMMAND": audioRequest(req); break; - case "RGBCOMMAND": RGBRequest(req); break; // TODO : Implement RGBCommand - case "OPENDEVTOOLS": devToolsIntent(); break; - } - req.logTimeElapsed(); - } - - public static void devToolsIntent() { - Thread AdvancedSettingsThread = new Thread(AdvancedSettingsForm.startAdvToolsThread) { - Name = "AdvancedSettingsThread" - }; - AdvancedSettingsThread.Start(); - } - - - public static void RGBRequest(Request req) { - RGBColor priColor = new RGBColor(255, 0, 0); - RGBColor secColor = new RGBColor(0, 0, 255); - // if (req.SECONDARY != null) { priColor = new RGBColor(req.SECONDARY); } else { priColor = null; }; - // if (req.TERTIARY != null) { secColor = new RGBColor(req.TERTIARY); } else { secColor = null; }; - LightingController.lightingProcess(priColor, secColor, req.PRIMARY); - } - - static void audioRequest(Request req) { - try { - switch (req.PRIMARY) { - // All are working - case "PLAYPAUSE": AudioController.togglePlayPause(); break; - case "NEXTTRACK": AudioController.nextTrack(); break; - case "PREVTRACK": AudioController.prevTrack(); break; - case "SETVOLUME": AudioController.setVolume(Convert.ToInt32(req.SECONDARY)); break; - case "VOLUMEUP": AudioController.volUp(); break; - case "VOLUMEDOWN": AudioController.volDown(); break; - case "TOGGLEMUTE": break; // TODO: Implement Mute Functionality - } - Response res = new Response(true, "Done!"); - } catch (Exception e) { - clog(e.ToString()); - Response res = new Response(false, "Oops! Something went wrong..."); - } - } - - static void launchRequest(Request req) { - if (req.PRIMARY == "SHUTDOWN") { - AlexaCompSERVER.stopServer(); - Process.Start("shutdown", "/s /t .5"); - } - - // For starting a - try { - string programPath = GetProgramPath(req.PRIMARY); - clog("ProgramPath - " + programPath); - clog("req Program - " + req.PRIMARY); - Process.Start(GetProgramPath(req.PRIMARY)); - clog("Program Launched"); - Response res = new Response(true, "Program Launched!", "", ""); - AlexaCompSERVER.stopServer(); // Restart Server to Handle Next Request - } - catch (NullReferenceException) { - clog("NullReferenceException caught during attempt to launch program, " + - "null most likely returned from GetProgramPath."); - Response res = new Response(false, failMessage); - AlexaCompSERVER.stopServer(); - } - catch (System.ComponentModel.Win32Exception e) { - clog("Win32Exception Caught during attempt to launch program " + e.Message); - Response res = new Response(false, failMessage); - AlexaCompSERVER.stopServer(); - }catch (InvalidOperationException e) { - clog("InvalidOperationException Caught during attempt to launch program " + e.Message); - Response res = new Response(false, failMessage); - AlexaCompSERVER.stopServer(); - } - } - - static void commandRequest(Request req) { - clog("CommandResuest"); - clog(req.PRIMARY); - switch (req.PRIMARY) { - case "SHUTDOWN": stopApplication(); Process.Start("shutdown", "/s /t .5"); break; // To Test - case "LOCK": - Process.Start(@"C:\WINDOWS\system32\rundll32.exe", "user32.dll,LockWorkStation"); break; // Working - case "RESTART": stopApplication(); Process.Start("shutdown", "/r /t .5"); break; // To Test - case "SLEEP": SetSuspendState(false, true, true); break; // To Test - case "LOGOFF": ExitWindowsEx(0, 0); break; // To Test - case "HIBERNATE": SetSuspendState(true, true, true); break; // To Test - } - } - - static void compStatRequest(Request req) { - // TODO : Fix Compstat System - // TODO : Implement switch case - if (req.PRIMARY == "RAM") { - Response res = new Response(true, "5.3 Gigabites", "", ""); - } - else if (req.PRIMARY == "GPU") { - Response res = new Response(true, "38 degrees celcius", "", ""); - } else { - Console.WriteLine(AlexaCompHARDWARE.partStat(req.PRIMARY, req.SECONDARY, req.TERTIARY)); - Response res = new Response(true, AlexaCompHARDWARE.partStat(req.PRIMARY, req.SECONDARY, req.TERTIARY), "", ""); - } - } - - static string GetProgramPath(string program) { - XmlDocument doc = new XmlDocument(); - doc.Load("pathDir.xml"); - clog("pathDIR loaded"); - if (doc.SelectSingleNode("//path[@programName='" + program + "']") is XmlElement elem) { - string path = elem.GetAttribute("programPath"); - clog("Path - " + path); - return path; - } - else { - clog("null returned"); - return null; - } - } - } -} diff --git a/AlexaComp/AlexaCompSERVER.cs b/AlexaComp/AlexaCompSERVER.cs index 69de020..f5c4f20 100644 --- a/AlexaComp/AlexaCompSERVER.cs +++ b/AlexaComp/AlexaCompSERVER.cs @@ -22,21 +22,21 @@ class AlexaCompSERVER : AlexaCompCore { public static TcpClient client; private static NetworkStream nwStream; - public static int PORT = int.Parse(GetConfigValue("PORT")); - public static string AUTH = GetConfigValue("AUTH"); - public static string HOST = "10.0.0.59"; + public static int PORT = ServerConfig.PORT; + public static string AUTH = ServerConfig.LambdaAuth; + public static string HOST = ServerConfig.HOST; private static INatDevice device; #endregion #region Methods - public static void startServer() { + public static void StartServer() { try { IPAddress host = IPAddress.Parse(HOST); server = new TcpListener(host, PORT); server.Start(); // Start Server - clog("Server Started"); - clog("Listening..."); + Clog("Server Started"); + Clog("Listening..."); if (stopProgramFlag == true) { return; } @@ -50,56 +50,59 @@ class AlexaCompSERVER : AlexaCompCore { AlexaComp._log.Debug(ex); } - acceptClient(); + AcceptClient(); } - public static void acceptClient() { + public static void AcceptClient() { try { client = server.AcceptTcpClient(); // Accept Client Connection + Stopwatch reqTimer = new Stopwatch(); + reqTimer.Start(); try { nwStream = client.GetStream(); // Get Incoming Data byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); // Read Data string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); // Convert Data to String - clog(dataReceived); - deserializeRequest(dataReceived); + Clog(dataReceived); + DeserializeRequest(dataReceived, reqTimer); } catch (NullReferenceException ex) { AlexaComp._log.Debug(ex); } catch (ObjectDisposedException ex) { AlexaComp._log.Debug(ex); } } - catch (SocketException) { clog("SocketException Caught when accepting client"); } - catch (NullReferenceException) { clog("NullReferenceException Caught when accepting client"); } + catch (SocketException) { Clog("SocketException Caught when accepting client"); } + catch (NullReferenceException) { Clog("NullReferenceException Caught when accepting client"); } catch (InvalidOperationException) { - clog("InvalidOperationException Caught when trying to accept tcp Client, most likely server not listening."); - startServer(); + Clog("InvalidOperationException Caught when trying to accept tcp Client, most likely server not listening."); + StartServer(); } } - public static void deserializeRequest(string data) { + public static void DeserializeRequest(string data, Stopwatch timer) { Request req = JsonConvert.DeserializeObject(data); + req.sw = timer; string reqString = String.Format("New Request - [Command: {0}, Primary: {1}, Secondary: {2}, Tertiary: {3}]", req.COMMAND, req.PRIMARY, req.SECONDARY, req.TERTIARY); - clog(reqString); + Clog(reqString); if (req.AUTH != AUTH) { - clog("Auth Invalid"); + Clog("Auth Invalid"); newServerFlag = true; - clog("destoryServerFlag set to true"); + Clog("destoryServerFlag set to true"); } else { - clog("Auth Valid."); - AlexaCompREQUEST.processRequest(req); - stopServer(); + Clog("Auth Valid."); + req.ProcessRequest(req); + //StopServer(); } } - public static void stopServer() { - clog("Stopping Server"); + public static void StopServer() { + Clog("Stopping Server"); try { client.Close(); - clog("Client closed"); + Clog("Client closed"); server.Stop(); - clog("Server Stopped"); + Clog("Server Stopped"); } catch (NullReferenceException ex) { AlexaComp._log.Debug(ex); @@ -107,7 +110,7 @@ class AlexaCompSERVER : AlexaCompCore { if (stopProgramFlag == false) { newServerFlag = true; - clog("newServerFlag Raised"); + Clog("newServerFlag Raised"); } } @@ -116,8 +119,8 @@ class AlexaCompSERVER : AlexaCompCore { * @param json - The json string to send back to the lambda instance, usually sent from a request object. * @param customStream - If defined, sends the response over a provided network stream instead of the most current stream. */ - public static void sendToLambda(string json, NetworkStream customStream) { - clog("Sending Back To Lambda - " + json); + public static void SendToLambda(string json, NetworkStream customStream = null) { + Clog("Sending Back To Lambda - " + json); byte[] message = Encoding.UTF8.GetBytes(json); int messageLength = Encoding.UTF8.GetBytes(json).Length; if (customStream != null) { @@ -132,39 +135,39 @@ class AlexaCompSERVER : AlexaCompCore { /* * Start the device discovery process */ - public static void forwardPort() { - NatUtility.DeviceFound += new EventHandler(onDeviceFound); - NatUtility.DeviceLost += new EventHandler(onDeviceLost); - clog("Starting Port Forwarding Device Discovery"); + public static void ForwardPort() { + NatUtility.DeviceFound += new EventHandler(OnDeviceFound); + NatUtility.DeviceLost += new EventHandler(OnDeviceLost); + Clog("Starting Port Forwarding Device Discovery"); NatUtility.StartDiscovery(); } /* * When device is found, forward the port set up in App.config. */ - public static void onDeviceFound(object sender, DeviceEventArgs args) { + public static void OnDeviceFound(object sender, DeviceEventArgs args) { Console.WriteLine("Port Forwarding Device Found"); device = args.Device; device.CreatePortMap(new Mapping(Protocol.Tcp, PORT, PORT)); // Forward Port - clog("Port - " + PORT.ToString() + " - Forwarded Successfully"); + Clog("Port - " + PORT.ToString() + " - Forwarded Successfully"); foreach (Mapping portMap in device.GetAllMappings()) { // Log all portmaps - clog("Port Map - " + portMap.ToString()); + Clog("Port Map - " + portMap.ToString()); } } /* * Do when device is lost. */ - public static void onDeviceLost(object sender, DeviceEventArgs args) { + public static void OnDeviceLost(object sender, DeviceEventArgs args) { device = args.Device; - clog("Forwarding Device Lost"); + Clog("Forwarding Device Lost"); } /* * Deletes all port maps. */ - public static void delPortMap() { + public static void DelPortMap() { try { device.DeletePortMap(new Mapping(Protocol.Tcp, PORT, PORT)); } catch (MappingException ex) { @@ -181,8 +184,8 @@ class AlexaCompSERVER : AlexaCompCore { while (true){ Thread.Sleep(150); if (newServerFlag) { - Thread StartServerThread = new Thread(startServer) { - Name = "startServerThread" + Thread StartServerThread = new Thread(StartServer) { + Name = "ServerThread" }; StartServerThread.Start(); newServerFlag = false; diff --git a/AlexaComp/App.config b/AlexaComp/App.config new file mode 100644 index 0000000..556bf80 --- /dev/null +++ b/AlexaComp/App.config @@ -0,0 +1,48 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/AlexaComp/Core/Config.example.cs b/AlexaComp/Core/Config.example.cs new file mode 100644 index 0000000..ed93a19 --- /dev/null +++ b/AlexaComp/Core/Config.example.cs @@ -0,0 +1,17 @@ +namespace AlexaComp.Core { + + public static class MDBConfig{ + public const string APIURI = ""; + public const string APIAUTH = ""; + } + + public static class LambdaConfig{ + public const string LambdaAuth = ""; + } + + public static class ServerConfig { + public const int PORT; + public static string HOST; + public const string LambdaAuth = ""; + } +} diff --git a/AlexaComp/Core/Controllers/AudioController.cs b/AlexaComp/Core/Controllers/AudioController.cs index 3a171ad..d43bbd8 100644 --- a/AlexaComp/Core/Controllers/AudioController.cs +++ b/AlexaComp/Core/Controllers/AudioController.cs @@ -3,13 +3,13 @@ using AudioSwitcher.AudioApi.CoreAudio; namespace AlexaComp { - class AudioController { + class AudioController : AlexaCompCore { private static CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice; // Play/ Pause, Next and previous track. [DllImport("user32.dll")] - public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo); + public static extern void Keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo); private const int KEYEVENTF_EXTENTEDKEY = 1; private const int KEYEVENTF_KEYUP = 0; @@ -17,32 +17,36 @@ class AudioController { private const int PLAY_PAUSE = 0xB3; private const int PREV_TRACK = 0xB1; - public static void togglePlayPause() { - keybd_event(PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); + public static void TogglePlayPause() { + Keybd_event(PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); } - public static void prevTrack() { - keybd_event(PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); + public static void PrevTrack() { + Keybd_event(PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); } - public static void nextTrack() { - keybd_event(NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); + public static void NextTrack() { + Keybd_event(NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); } - public static void setVolume(int percent) { + public static void SetVolume(int percent) { defaultPlaybackDevice.Volume = percent; } - public static void volDown() { + public static void VolDown() { defaultPlaybackDevice.Volume -= 5; } - public static void volUp() { + public static void VolUp() { defaultPlaybackDevice.Volume += 5; } - public static void toggleMute() { - // To Implement + public static void ToggleMute() { + if (defaultPlaybackDevice.IsMuted) { + defaultPlaybackDevice.Mute(false); // Unmute + } else { + defaultPlaybackDevice.Mute(true); // Mute + } } } } diff --git a/AlexaComp/Core/Controllers/HardwareController.cs b/AlexaComp/Core/Controllers/HardwareController.cs new file mode 100644 index 0000000..e94bc08 --- /dev/null +++ b/AlexaComp/Core/Controllers/HardwareController.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Diagnostics; + +using OpenHardwareMonitor; +using OpenHardwareMonitor.Hardware; + +namespace AlexaComp.Core.Controllers { + public class HardwareController : AlexaCompCore { + + public static List partNames = new List() { "GPU", "CPU", "RAM", "MAINBOARD", "HDD", "FANCONTROLLER" }; + + public static Dictionary> partDict = new Dictionary>() { + { "GPU", new Dictionary {{"TEMP", ""}, {"LOAD", ""}, {"CLOCK_CORE", ""}, {"CLOCK_RAM", ""}}}, + { "CPU", new Dictionary {{"TEMP", ""}, {"LOAD", ""}, {"CLOCK_CORE", ""}}}, + { "RAM", new Dictionary {{"USED", "Used Memory"}, {"AVAILABLE", "Available Memory"}}}, + { "MAINBOARD", new Dictionary {}} + }; + + public static void InitSensors() { + Stopwatch loop = new Stopwatch(); + Stopwatch method = new Stopwatch(); + method.Start(); + Devices.Clear(); + foreach (string part in partNames) { + loop.Start(); + UpdateVisitor updateVisitor = new UpdateVisitor(); + Computer computer = new Computer(); + computer.Open(); + PartOneHot(computer, part); + computer.Accept(updateVisitor); + for (int i = 0; i < computer.Hardware.Length; i++) { + for (int k = 0; k < computer.Hardware.Length; k++) { + var currentHardware = computer.Hardware[k]; + + Hardware nHardware = new Hardware(currentHardware.HardwareType.ToString(), part) { + Name = currentHardware.Name + }; + + for (int j = 0; j < computer.Hardware[k].Sensors.Length; j++) { + var currentSensor = computer.Hardware[k].Sensors[j]; + // Console.WriteLine(" nSensor -- " + currentSensor.Name + " - " + currentSensor.SensorType.ToString() + " - " + currentSensor.Value.ToString()); + Sensor_ nSensor = new Sensor_(currentSensor.Name, currentSensor.SensorType.ToString(), currentSensor) { + Value = (float)currentSensor.Value + }; + nHardware.Sensors[currentSensor.Name] = nSensor; + } + + Devices[GenKey(currentHardware.HardwareType.ToString())] = nHardware; + loop.Stop(); + Clog(String.Format("HW Initialization -- {0} initialized in {1} ms. {2} Sensors found.", part, loop.ElapsedMilliseconds, nHardware.SensorsLength())); + loop.Reset(); + } + computer.Close(); + } + } + method.Stop(); + Clog(String.Format("Hardware Initialized in {0} ms.", method.ElapsedMilliseconds)); + LogHardware(); + } + + public static void RefreshHardware(Hardware obj) { + obj.Sensors.Clear(); + UpdateVisitor updateVisitor = new UpdateVisitor(); + Computer computer = new Computer(); + computer.Open(); + PartOneHot(computer, obj.GenericName); + computer.Accept(updateVisitor); + for (int i = 0; i < computer.Hardware.Length; i++) { + for (int k = 0; k < computer.Hardware.Length; k++) { + var currentHardware = computer.Hardware[k]; + + for (int j = 0; j < currentHardware.Sensors.Length; j++) { + var currentSensor = currentHardware.Sensors[j]; + Sensor_ nSensor = new Sensor_(currentSensor.Name, currentSensor.SensorType.ToString(), currentSensor) { + Value = (float)currentSensor.Value + }; + obj.Sensors[currentSensor.Name] = nSensor; + } + } + computer.Close(); + } + } + + public static string GenKey(string hwType) { + int outKey = 0; + while (true) { + if (Devices.ContainsKey(hwType + outKey.ToString())) { + outKey++; + } + else { + break; + } + } + return hwType + outKey.ToString(); + } + + public static void PartOneHot(Computer comp, string part) { + if (part == "GPU") { comp.GPUEnabled = true; } + else if (part == "CPU") { comp.CPUEnabled = true; } + else if (part == "RAM") { comp.RAMEnabled = true; } + else if (part == "MAINBOARD") { comp.MainboardEnabled = true; } + else if (part == "HDD") { comp.HDDEnabled = true; } + else if (part == "FANCONTROLLER") { comp.FanControllerEnabled = true; } + } + + public static void LogHardware() { + foreach (KeyValuePair pair in Devices) { + Clog(pair.Value.ToString()); + string[] sensorLines = pair.Value.SensorsToString(" ").Split( + new[] { "\r\n", "\r", "\n" }, + StringSplitOptions.None + ); + foreach (string sensor in sensorLines) { + Clog(sensor); + } + } + } + + public static int LoadFormat(float? loadFloat) { return (int)loadFloat; } + public static int TempFormat(float? tempFloat) { return (int)tempFloat; } + + /* + public static string partStat(string part, string stat, string tertiary) { + UpdateVisitor updateVisitor = new UpdateVisitor(); + Computer computer = new Computer(); + computer.Open(); + partOneHot(computer, part); + computer.Accept(updateVisitor); + try { + Console.WriteLine(partDict[part][stat]); + } + catch (KeyNotFoundException e) { + clog("KeyNotFoundException during attempt to get part stat " + e.Message); + Response res = new Response(false, failMessage, "", ""); + return "null"; + } + + int hwLength = computer.Hardware.Length; + for (int i = 0; i < hwLength; i++) { + for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++) { + foreach (ISensor sensor in computer.Hardware[i].Sensors) { + if (sensor.Name == partDict[part][stat]) { + if (getSensorType(sensor) == tertiary) { + return sensor.Value.ToString() + " Mega Hertz"; + } + } + } + } + computer.Close(); + return "null"; + } + return "null"; + }*/ + } + + public class UpdateVisitor : IVisitor { + public void VisitComputer(IComputer computer) { + computer.Traverse(this); + } + public void VisitHardware(IHardware hardware) { + hardware.Update(); + foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this); + } + public void VisitSensor(ISensor sensor) { } + public void VisitParameter(IParameter parameter) { } + } +} diff --git a/AlexaComp/Core/Controllers/LightingController.cs b/AlexaComp/Core/Controllers/LightingController.cs index 5a54b25..1799bb3 100644 --- a/AlexaComp/Core/Controllers/LightingController.cs +++ b/AlexaComp/Core/Controllers/LightingController.cs @@ -27,11 +27,11 @@ class LightingController : AlexaCompCore { /// /// Loads and logs all devices. /// - public static void startLightingThread() { - loadDevices(); - clog("RGB Devices Loaded, Printing..."); + public static void StartLightingThread() { + LoadDevices(); + Clog("RGB Devices Loaded, Printing..."); foreach (var device in surface.Devices) { - clog(String.Format("RGB Device Found - {0} {1} - Type: {2}", + Clog(String.Format("RGB Device Found - {0} {1} - Type: {2}", device.DeviceInfo.Manufacturer, device.DeviceInfo.Model, device.DeviceInfo.DeviceType)); @@ -42,9 +42,9 @@ class LightingController : AlexaCompCore { /// /// Loads all devices into the surface object. /// - public static void loadDevices() { + public static void LoadDevices() { surface.Exception += args => AlexaComp._log.Info(args.Exception.Message); - clog("Loading RGB Devices"); + Clog("Loading RGB Devices"); //surface.LoadDevices(AsusDeviceProvider.Instance); surface.LoadDevices(LogitechDeviceProvider.Instance); @@ -55,21 +55,22 @@ class LightingController : AlexaCompCore { surface.LoadDevices(RazerDeviceProvider.Instance); } - public static void lightingProcess(RGBColor color1, RGBColor color2, string effect = "", int speed_ = -20, double granularity_ = -0.1, int speed2 = -1) { + public static void LightingProcess(RGBColor color1, RGBColor color2, string effect = "", int speed_ = -20, double granularity_ = -0.1, int speed2 = -1) { if (color1 == null) { color1 = new RGBColor(-1, -1, -1); } if (color2 == null) { color2 = new RGBColor(-1, -1, -1); } switch (effect) { case "": break; - /* TO TEST */case "STATICCOLOR": lightingThread = new Thread(unused => LightingEffects.staticColor(R: color1.R, G: color1.G, B: color1.B)); break; - /* TO TEST */case "ERROREFFECT": lightingThread = new Thread(unused => LightingEffects.errorEffect(speed: speed_)); break; - /* TO TEST */case "BREATHINGEFFECT": lightingThread = new Thread(unused => LightingEffects.breathingEffect(R: color1.R, G: color1.G, B: color1.B, speed: speed_, brightnessStep: granularity_)); break; - /* WORKING */case "RAINBOWFADEEFFECT": lightingThread = new Thread(unused => LightingEffects.fadingEffect()); break; - /* TO TEST */case "PULSEEFFECT": lightingThread = new Thread(unused => LightingEffects.pulseEffect(R: color1.R, G: color1.G, B: color1.B, effectSpeed: speed_, fadeSpeed: speed2, brightnessStep: granularity_)); break; + /* TO TEST */case "STATICCOLOR": lightingThread = new Thread(unused => LightingEffects.StaticColor(R: color1.R, G: color1.G, B: color1.B)); break; + /* TO TEST */case "ERROREFFECT": lightingThread = new Thread(unused => LightingEffects.ErrorEffect(speed: speed_)); break; + /* TO TEST */case "BREATHINGEFFECT": lightingThread = new Thread(unused => LightingEffects.BreathingEffect(R: color1.R, G: color1.G, B: color1.B, speed: speed_, brightnessStep: granularity_)); break; + /* WORKING */case "RAINBOWFADEEFFECT": lightingThread = new Thread(unused => LightingEffects.FadingEffect()); break; + /* TO TEST */case "PULSEEFFECT": lightingThread = new Thread(unused => LightingEffects.PulseEffect(R: color1.R, G: color1.G, B: color1.B, effectSpeed: speed_, fadeSpeed: speed2, brightnessStep: granularity_)); break; // case "ALTERNATINGEFFECT": lightingThread = new Thread(unused => LightingEffects.alternatingEffect()); break; // case "BLINKINGEFFECT": lightingThread = new Thread(unused => LightingEffects.blinkingEffect(color: color1, speed: speed_)); break; - /* WORKING */case "ALLLEDOFF": lightingThread = new Thread(unused => LightingEffects.allLedOff()); break; + /* WORKING */case "ALLLEDOFF": lightingThread = new Thread(unused => LightingEffects.AllLedOff()); break; } + lightingThread.Name = "LightingEffectThread"; lightingThread.Start(); } @@ -97,13 +98,13 @@ public class LightingEffects : LightingController { /// // TODO : Implement color cieling. Only default color values work. // If values are 255, 255, 255, they are added to and subtracted from an equal ammount. - public static void breathingEffect(int R = 1, int G = 1, int B = 1, int speed = 20, double brightnessStep = 0.01) { + public static void BreathingEffect(int R = 1, int G = 1, int B = 1, int speed = 20, double brightnessStep = 0.01) { if (R < 0) { R = 1; } if (G < 0) { G = 1; } if (B < 0) { B = 1; } if (speed < 0) { speed = 20; } if (brightnessStep < 0) { brightnessStep = 0.01; } - clog(String.Format("RGB -- Breathing Animation Set -- Color: {0}, {1}, {2} - Speed: {3} - Brightness Step: {4}", + Clog(String.Format("RGB -- Breathing Animation Set -- Color: {0}, {1}, {2} - Speed: {3} - Brightness Step: {4}", R, G, B, speed, brightnessStep)); while (true) { ILedGroup ledGroup = new ListLedGroup(surface.Leds); @@ -125,7 +126,7 @@ public class LightingEffects : LightingController { /// How quickly the color fades after the pulse /// The granularity of the brightness adjustments // TODO : Fix. Has same color issue as breathingAnimation. - public static void pulseEffect(int R, int G, int B, int effectSpeed = 100, int fadeSpeed = 10, double brightnessStep = 0.01) { + public static void PulseEffect(int R, int G, int B, int effectSpeed = 100, int fadeSpeed = 10, double brightnessStep = 0.01) { if (R < 0) { B = 255; } if (G < 0) { B = 255; } if (B < 0) { B = 255; } @@ -169,7 +170,7 @@ public class LightingEffects : LightingController { ///
/// /// - public static void blinkingEffect(RGBColor color, int speed = 400) { + public static void BlinkingEffect(RGBColor color, int speed = 400) { if (color == null) { color = new RGBColor(255, 255, 255); } if (speed < 0) { speed = 400; } // alternatingEffect(color, new RGBColor(0, 0, 0), speed); @@ -178,11 +179,8 @@ public class LightingEffects : LightingController { /// /// Sets all leds to a static color /// - public static void staticColor(int R = 255, int G = 255, int B = 255) { - if (R < 0) { R = 255; } - if (G < 0) { G = 255; } - if (B < 0) { B = 255; } - clog(String.Format("RGB -- Setting Static Color -- Color: {0}, {1}, {2}", R, G, B)); + public static void StaticColor(int R = 255, int G = 255, int B = 255) { + Clog(String.Format("RGB -- Setting Static Color -- Color: {0}, {1}, {2}", R, G, B)); ILedGroup ledGroup = new ListLedGroup(surface.Leds); while (true) { ledGroup.Brush = new SolidColorBrush(new Color(R, G, B)); @@ -202,30 +200,21 @@ public class LightingEffects : LightingController { /// Slowest Reccomended - Speed: 100 at hueStep: 0.001 /// /// - public static void fadingEffect(int speed = 50, double hueStep = 0.01) { - clog(String.Format("Setting Rainbow Fade Effect -- Speed: {0} - Hue Step: {1}", speed, hueStep)); + public static void FadingEffect(int speed = 50, double hueStep = 0.01) { + Clog(String.Format("Setting Rainbow Fade Effect -- Speed: {0} - Hue Step: {1}", speed, hueStep)); ILedGroup ledGroup = new ListLedGroup(surface.Leds); while (true) { for (double j = 0; j < 1; j += hueStep) { - RGBColor c = colorMethods.HSLToRGB(j, 1.0, 0.5); + RGBColor c = ColorMethods.HSLToRGB(j, 1.0, 0.5); ledGroup.Brush = new SolidColorBrush(new Color(c.R, c.G, c.B)); Thread.Sleep(speed); } } } - /// - /// Turns all leds off - /// - public static void allLedOff() { - clog("Setting All LED Off Effect"); - ILedGroup ledGroup = new ListLedGroup(surface.Leds); - ledGroup.Brush = new SolidColorBrush(new Color(0, 0, 0)); - } - - public static void errorEffect(int speed = 1) { + public static void ErrorEffect(int speed = 1) { if (speed < 0) { speed = 1; } - clog("RGB Error Effect Started."); + Clog("RGB Error Effect Started."); ILedGroup ledGroup = new ListLedGroup(surface.Leds); for (int j = 0; j <= 2; j++) { for (int i = 0; i <= 255; i++) { @@ -238,13 +227,22 @@ public class LightingEffects : LightingController { } } } + + /// + /// Turns all leds off + /// + public static void AllLedOff() { + Clog("Setting All LED Off Effect"); + ILedGroup ledGroup = new ListLedGroup(surface.Leds); + ledGroup.Brush = new SolidColorBrush(new Color(0, 0, 0)); + } } } /// /// Methods that convert color values. /// - class colorMethods : AlexaCompCore { + class ColorMethods : AlexaCompCore { /// /// From: https://geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm @@ -313,7 +311,7 @@ class colorMethods : AlexaCompCore { return new RGBColor(Convert.ToByte(r * 255), Convert.ToByte(g * 255.0f), Convert.ToByte(b * 255.0f)); } catch (OverflowException) { - clog("Overflow Exception caught during attempt to return RGB object from HSLToRGB."); + Clog("Overflow Exception caught during attempt to return RGB object from HSLToRGB."); return null; } } @@ -367,7 +365,7 @@ class RGBColor { public RGBColor (System.Drawing.Color color) => new RGBColor(color.R, color.B, color.G); public RGBColor(string[] color) => new RGBColor(Convert.ToInt32(color[0]), Convert.ToInt32(color[1]), Convert.ToInt32(color[2])); - public void setColorByIndex(int index, int value) { + public void SetColorByIndex(int index, int value) { switch (index) { case 0: R = value; break; case 1: G = value; break; @@ -375,12 +373,12 @@ class RGBColor { } } - public Color toRGBNETColor() => new Color(R, G, B); + public Color ToRGBNETColor() => new Color(R, G, B); - public void printObj() { + public void PrintObj() { Console.WriteLine(String.Format("RGBColor Object -- R: {0}, G: {1}, B: {2}", R, G, B)); } - public int[] sliceColor() => new int[3] { R, G, B }; + public int[] SliceColor() => new int[3] { R, G, B }; } } \ No newline at end of file diff --git a/AlexaComp/Core/Controllers/MDBController.cs b/AlexaComp/Core/Controllers/MDBController.cs new file mode 100644 index 0000000..a1f2c36 --- /dev/null +++ b/AlexaComp/Core/Controllers/MDBController.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AlexaComp.Core.Controllers { + class MDBController { + } +} diff --git a/AlexaComp/Core/Hardware.cs b/AlexaComp/Core/Hardware.cs new file mode 100644 index 0000000..243897f --- /dev/null +++ b/AlexaComp/Core/Hardware.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +using AlexaComp.Core.Controllers; + +namespace AlexaComp.Core { + public class Hardware : AlexaCompCore { + + #region Properties + public string Manufacturer; + public string Name; + public string Type; + public string GenericName; + + public Dictionary Sensors = new Dictionary(); + #endregion + + #region Constructors + public Hardware(string Type, string GenericName) { + this.Type = Type; + this.GenericName = GenericName; + } + + public Hardware(string Type, string Manufacturer, string Name, string GenericName) { + this.Type = Type; + this.Manufacturer = Manufacturer; + this.Name = Name; + this.GenericName = GenericName; + } + #endregion + + #region Methods + public void RefreshSensors() { + HardwareController.RefreshHardware(this); + } + + public string GetSensorValue(string sensorName) { + Sensor_ sensor = Sensors[sensorName]; + return sensor.Value.ToString(); + } + + public string SensorsToString(string prefix = "") { + StringBuilder sb = new StringBuilder(); + foreach(KeyValuePair pair in Sensors) { + sb.Append(prefix); + sb.Append(pair.Value.ToString() + "\n"); + } + try { + sb.Length--; // Remove last \n + } catch (ArgumentOutOfRangeException) { } + return sb.ToString(); + } + + public int SensorsLength() => Sensors.Count; + + public override string ToString() { + return string.Format("Hardware Object -- Name: {0}, Type: {1}, Sensor Length: {2}", Name, Type, SensorsLength()); + } + #endregion + } +} \ No newline at end of file diff --git a/AlexaComp/Core/Options.cs b/AlexaComp/Core/Options.cs deleted file mode 100644 index ee95180..0000000 --- a/AlexaComp/Core/Options.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace AlexaComp.Core{ - class Options { - public Request req; - public System.Net.Sockets.NetworkStream nwStream; - - public Options(Request req_, System.Net.Sockets.NetworkStream nwStream_) { - req = req_; - nwStream = nwStream_; - } - } -} \ No newline at end of file diff --git a/AlexaComp/Core/ProgramInventory.cs b/AlexaComp/Core/ProgramInventory.cs index 01dc75c..4281031 100644 --- a/AlexaComp/Core/ProgramInventory.cs +++ b/AlexaComp/Core/ProgramInventory.cs @@ -6,32 +6,39 @@ using System.Xml; using System.Text; using System.Threading.Tasks; +using System.Diagnostics; namespace AlexaComp.Core { - class ProgramInventory { + class ProgramInventory : AlexaCompCore { - private static string rootPath = @"C:\Program Files (x86)"; + private static readonly string rootPath = @"C:\Program Files (x86)"; + private static int numMatches = 0; - public static void scanDir(string dir = @"C:\Program Files (x86)") { + public static void ScanDir(string dir = @"C:\Program Files (x86)") { + Stopwatch timer = new Stopwatch(); + timer.Start(); + Clog("Scanning for .exes in - " + dir); string[] allfiles = Directory.GetDirectories(dir); Console.WriteLine("Files Length - " + allfiles.Length.ToString()); - Console.ReadLine(); foreach (string subdir in allfiles) { // Console.WriteLine("Running Scan - Depth: 1"); - checkForMatches(subdir); + CheckForMatches(subdir); // Console.WriteLine("Running Scan - Depth: 2"); string[] files = Directory.GetDirectories(subdir); foreach (string subsubdir in files) { // Console.WriteLine("Checking For Matches In - " + subsubdir); - checkForMatches(subsubdir); + CheckForMatches(subsubdir); } } + timer.Stop(); + Clog(String.Format("Scanned dir in {0} ms. Found {1} matches.", timer.ElapsedMilliseconds, numMatches)); + numMatches = 0; } - public static void checkForMatches(string path) { + public static void CheckForMatches(string path) { string[] exes = Directory.GetFileSystemEntries(Path.Combine(rootPath, path), "*.exe", SearchOption.TopDirectoryOnly); // If there is only one .exe in the directory @@ -40,6 +47,7 @@ class ProgramInventory { FileInfo info = new FileInfo(file); string[] splitExePath = path.Split('\\').ToArray(); Console.WriteLine("EXE MATCH FOUND: " + splitExePath[splitExePath.Length - 1] + " -- " + info.Name); + numMatches++; } } @@ -49,22 +57,9 @@ class ProgramInventory { string[] splitExePath = path.Split('\\').ToArray(); if (splitExePath[splitExePath.Length - 1].Replace(" ", "").ToLower() == Path.GetFileNameWithoutExtension(info.Name).ToLower()) { Console.WriteLine("EXE MATCH FOUND: " + splitExePath[splitExePath.Length - 1] + " -- " + info.Name); + numMatches++; } } } - - public static string TryGetElementValue(XElement parentEl, string key) { - var foundEl = parentEl.Element(key); - - if (foundEl != null) { - return foundEl.Value; - } - - return null; - } - - public static string multStr(int n) { - return ""; - } } } diff --git a/AlexaComp/Core/Request.cs b/AlexaComp/Core/Request.cs index a420e79..60864f9 100644 --- a/AlexaComp/Core/Request.cs +++ b/AlexaComp/Core/Request.cs @@ -1,9 +1,11 @@ using System.Diagnostics; +using AlexaComp.Core.Requests; + namespace AlexaComp.Core { [DebuggerDisplay("[AlexaComp Request Object -- {{COMMAND: {COMMAND}, PRIMARY: {PRIMARY}, SECONDARY: {SECONDARY}, TERTIARY: {TERTIARY}}}]")] - class Request : AlexaCompCore { + public class Request : AlexaCompCore { #region Properties public string AUTH { get; set; } public string COMMAND { get; set; } @@ -11,29 +13,60 @@ class Request : AlexaCompCore { public string SECONDARY { get; set; } public string TERTIARY { get; set; } public string SESSID { get; set; } + public string COLOR1 { get; set; } + public string COLOR2 { get; set; } public Stopwatch sw = new Stopwatch(); #endregion #region Constructors + /* public Request() { sw.Start(); - } + processRequest(this); + }*/ - public Request(string AUTH_, string COMMAND_, string PRIMARY_ = "", string SECONDARY_ = "", string TERTIARY_ = "") { - sw.Start(); - AUTH = AUTH_; - COMMAND = COMMAND_; - PRIMARY = PRIMARY_; - SECONDARY = SECONDARY_; - TERTIARY = TERTIARY_; + public Request(string AUTH, string COMMAND, string PRIMARY = "", string SECONDARY = "", string TERTIARY = "") { + this.AUTH = AUTH; + this.COMMAND = COMMAND; + this.PRIMARY = PRIMARY; + this.SECONDARY = SECONDARY; + this.TERTIARY = TERTIARY; } #endregion #region Methods - public void logTimeElapsed() { + public void LogTimeElapsed() { + Clog("Request Constructed"); sw.Stop(); - clog("Request Completed, Time Elapsed(ms) - " + sw.ElapsedMilliseconds.ToString()); + Clog("Request Completed, Time Elapsed(ms) - " + sw.ElapsedMilliseconds.ToString()); + } + + public void ProcessRequest(Request req) { + if (AUTH != "testAuth") { + AlexaCompSERVER.StopServer(); + } else { Clog("IS Test Request"); } + switch (req.COMMAND) { + case "LAUNCH": + Launch unused = new Launch(req.PRIMARY); + break; + case "COMPUTERCOMMAND": + SystemCommand unused2 = new SystemCommand(req.PRIMARY); + break; + case "GETCOMPSTAT": + CompStat unused3 = new CompStat(req.PRIMARY, req.SECONDARY, req.TERTIARY); + break; + case "AUDIOCOMMAND": + AudioCommand unused4 = new AudioCommand(req.PRIMARY, req.SECONDARY); + break; + case "RGBCOMMAND": + RGBCommand unused5 = new RGBCommand(req.PRIMARY, req.COLOR1, req.COLOR2); + break; + case "OPENDEVTOOLS": + OpenDevTools unused6 = new OpenDevTools(); + break; + } + req.LogTimeElapsed(); } /* diff --git a/AlexaComp/Core/RequestTypes/AudioCommand.cs b/AlexaComp/Core/RequestTypes/AudioCommand.cs new file mode 100644 index 0000000..af26126 --- /dev/null +++ b/AlexaComp/Core/RequestTypes/AudioCommand.cs @@ -0,0 +1,60 @@ +using System; + +namespace AlexaComp.Core.Requests { + + public class AudioCommand : AlexaCompCore { + + #region Properties + private string command; + private int setVolAmt; + + #endregion + + #region Constructors + public AudioCommand(string command, string setVolAmt = "0") { + this.command = command; + this.setVolAmt = Convert.ToInt32(setVolAmt); + + try{ + process(); + } catch (Exception e) { + Clog(e.ToString()); + } + } + #endregion + + #region Methods + public void process() { + switch (command) { + case "PLAYPAUSE": + AudioController.TogglePlayPause(); + break; + + case "NEXTTRACK": + AudioController.NextTrack(); + break; + + case "PREVTRACK": + AudioController.PrevTrack(); + break; + + case "SETVOLUME": + AudioController.SetVolume(this.setVolAmt); + break; + + case "VOLUMEUP": + AudioController.VolUp(); + break; + + case "VOLUMEDOWN": + AudioController.VolDown(); + break; + + case "TOGGLEMUTE": + AudioController.ToggleMute(); + break; + } + } + #endregion + } +} \ No newline at end of file diff --git a/AlexaComp/Core/RequestTypes/CompStat.cs b/AlexaComp/Core/RequestTypes/CompStat.cs new file mode 100644 index 0000000..5dafb58 --- /dev/null +++ b/AlexaComp/Core/RequestTypes/CompStat.cs @@ -0,0 +1,33 @@ +using System; + +namespace AlexaComp.Core.Requests { + public class CompStat : AlexaCompCore { + + private string part; + private string stat; + private string TERTIARY; + + public CompStat(string part_, string stat_, string TERTIARY_) { + part = part_; + stat = stat_; + TERTIARY = TERTIARY_; + process(); + } + + public void process() { + // TODO : Fix Compstat System + // TODO : Implement switch case + if (this.part == "RAM") { + Response res = new Response(true, "5.3 Gigabites"); + } + else if (this.part == "GPU") { + Response res = new Response(true, "38 degrees celcius"); + } else { + Devices[part].RefreshSensors(); + string result = Devices[part].Sensors[stat].Value.ToString(); + Console.WriteLine(result); + Response res = new Response(true, result); + } + } + } +} \ No newline at end of file diff --git a/AlexaComp/Core/RequestTypes/Launch.cs b/AlexaComp/Core/RequestTypes/Launch.cs new file mode 100644 index 0000000..77fdf2f --- /dev/null +++ b/AlexaComp/Core/RequestTypes/Launch.cs @@ -0,0 +1,56 @@ +using System; +using System.Xml; +using System.Diagnostics; + +using AlexaComp.Core; + +namespace AlexaComp.Core.Requests { + public class Launch : AlexaCompCore { + + private string programName; + + public Launch(string programName_) { + Clog("LaunchCommand Constructed"); + programName = programName_; + process(); + } + + public void process() { + try { + string programPath = GetProgramPath(programName); + Clog("ProgramPath - " + programPath); + Clog("req Program - " + programName); + Process.Start(GetProgramPath(programName)); + Clog("Program Launched"); + Response res = new Response(true, "Program Launched!", "", ""); + } + catch (NullReferenceException) { + Clog("NullReferenceException caught during attempt to launch program, " + + "null most likely returned from GetProgramPath."); + Response res = new Response(false, ""); + } + catch (System.ComponentModel.Win32Exception e) { + Clog("Win32Exception Caught during attempt to launch program " + e.Message); + Response res = new Response(false, ""); + }catch (InvalidOperationException e) { + Clog("InvalidOperationException Caught during attempt to launch program " + e.Message); + Response res = new Response(false, ""); + } + } + + static string GetProgramPath(string program) { + XmlDocument doc = new XmlDocument(); + doc.Load("pathDir.xml"); + Clog("pathDIR loaded"); + if (doc.SelectSingleNode("//path[@programName='" + program + "']") is XmlElement elem) { + string path = elem.GetAttribute("programPath"); + Clog("Path - " + path); + return path; + } + else { + Clog("null returned"); + return null; + } + } + } +} \ No newline at end of file diff --git a/AlexaComp/Core/RequestTypes/OpenDevTools.cs b/AlexaComp/Core/RequestTypes/OpenDevTools.cs new file mode 100644 index 0000000..03e4dfb --- /dev/null +++ b/AlexaComp/Core/RequestTypes/OpenDevTools.cs @@ -0,0 +1,23 @@ +using System.Threading; + +using AlexaComp.Forms; + +namespace AlexaComp.Core.Requests { + + public class OpenDevTools : AlexaCompCore { + + public OpenDevTools(){ + Clog("OpenDevTools Constructed"); + process(); + } + + public void process() { + Thread AdvancedSettingsThread = new Thread(AdvancedSettingsForm.startAdvToolsThread) { + Name = "AdvancedSettingsThread" + }; + Clog("Starting Window..."); + AdvancedSettingsThread.Start(); + Clog("Window Started"); + } + } +} \ No newline at end of file diff --git a/AlexaComp/Core/RequestTypes/RGBCommand.cs b/AlexaComp/Core/RequestTypes/RGBCommand.cs new file mode 100644 index 0000000..c3ff63e --- /dev/null +++ b/AlexaComp/Core/RequestTypes/RGBCommand.cs @@ -0,0 +1,31 @@ +using AlexaComp.Controllers; + +namespace AlexaComp.Core.Requests { + + public class RGBCommand : AlexaCompCore { + + public string effect; + + public string color1; + + public string color2; + + public RGBCommand(string effect_, string color1_, string color2_ = null) { + Clog("RGBCommand Constructed"); + effect = effect_; + color1 = color1_; + color2 = color2_; + process(); + } + + public void process() { + Clog("Processing..."); + RGBColor priColor = new RGBColor(255, 255, 255); + RGBColor secColor = new RGBColor(0, 0, 255); + // if (req.SECONDARY != null) { priColor = new RGBColor(req.SECONDARY); } else { priColor = null; }; + // if (req.TERTIARY != null) { secColor = new RGBColor(req.TERTIARY); } else { secColor = null; }; + LightingController.StartLightingThread(); + LightingController.LightingProcess(priColor, secColor, effect); + } + } +} \ No newline at end of file diff --git a/AlexaComp/Core/RequestTypes/SystemCommand.cs b/AlexaComp/Core/RequestTypes/SystemCommand.cs new file mode 100644 index 0000000..51f5c46 --- /dev/null +++ b/AlexaComp/Core/RequestTypes/SystemCommand.cs @@ -0,0 +1,60 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace AlexaComp.Core.Requests { + + public class SystemCommand : AlexaCompCore { + + #region DllImports + [DllImport("user32.dll")] + private static extern bool ExitWindowsEx(uint uFlags, uint dwReason); + + [DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent); + #endregion + + #region Properties + private string command; + #endregion + + #region Constructors + + public SystemCommand(string command_) { + command = command_; + process(); + } + + #endregion + + public void process() { + Clog("CommandResuest"); + Clog(this.command); + switch (this.command) { + case "SHUTDOWN": + StopApplication(); Process.Start("shutdown", "/s /t .5"); + break; // To Test + + case "LOCK": + Process.Start(@"C:\WINDOWS\system32\rundll32.exe", "user32.dll,LockWorkStation"); + break; // Working + + case "RESTART": + StopApplication(); Process.Start("shutdown", "/r /t .5"); + break; // To Test + + case "SLEEP": + SetSuspendState(false, true, true); + break; // To Test + + case "LOGOFF": + ExitWindowsEx(0, 0); + break; // To Test + + case "HIBERNATE": + SetSuspendState(true, true, true); + break; // To Test + } + } + } +} \ No newline at end of file diff --git a/AlexaComp/Core/Response.cs b/AlexaComp/Core/Response.cs index 36c4967..b5ede94 100644 --- a/AlexaComp/Core/Response.cs +++ b/AlexaComp/Core/Response.cs @@ -14,24 +14,23 @@ class Response : AlexaCompCore { #endregion #region Constructors - public Response(bool passorfail_, string message_, string primary_ = "", string secondary_ = "") { - passorfail = passorfail_; - message = message_; - primary = primary_; - secondary = secondary_; - + public Response(bool passorfail, string message, string primary = "", string secondary = "") { + this.passorfail = passorfail; + this.message = message; + this.primary = primary; + this.secondary = secondary; json = Newtonsoft.Json.JsonConvert.SerializeObject(this); Console.WriteLine(json); } #endregion #region Methods - public void sendResponse(System.Net.Sockets.NetworkStream customStream) { + public void SendResponse(System.Net.Sockets.NetworkStream customStream) { if (customStream != null) { - AlexaCompSERVER.sendToLambda(json, customStream); + AlexaCompSERVER.SendToLambda(json, customStream); } else { - AlexaCompSERVER.sendToLambda(json, null); + AlexaCompSERVER.SendToLambda(json); } } #endregion diff --git a/AlexaComp/Core/Sensor_.cs b/AlexaComp/Core/Sensor_.cs new file mode 100644 index 0000000..bd8ebd4 --- /dev/null +++ b/AlexaComp/Core/Sensor_.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using OpenHardwareMonitor; +using OpenHardwareMonitor.Collections; +using OpenHardwareMonitor.Hardware; + +namespace AlexaComp.Core { + public class Sensor_ { + + #region Properties + static readonly Dictionary Units = new Dictionary { + {SensorType.Voltage, "V"}, + {SensorType.Clock, "MHz"}, + {SensorType.Temperature, "°C"}, + {SensorType.Load, "%"}, + {SensorType.Fan, "RPM"}, + {SensorType.Flow, "L/h"}, + {SensorType.Control, "%"}, + {SensorType.Level, "%"}, + {SensorType.Factor, "1"}, + {SensorType.Power, "W"}, + {SensorType.Data, "GB"} + }; + + public string Name; + public float Value; + public string SensorPath; + public string Type; + public ISensor OriginSensor; + #endregion + + #region Constructors + public Sensor_(string Name, string Type) { + this.Name = Name; + this.Type = Type; + } + + public Sensor_(string Name, string Type, ISensor Origin) { + this.Name = Name; + this.Type = Type; + OriginSensor = Origin; + } + #endregion + + #region Methods + public string getUnit() { + return Units[OriginSensor.SensorType]; + } + + public static string GetSensorType(ISensor sensor) { + return sensor.SensorType.ToString(); + } + + public override string ToString() { + return string.Format("Sensor Object -- Name: {0}, Type: {1}, Value: {2}", Name, Type, Value.ToString()); + } + #endregion + } +} diff --git a/AlexaComp/Forms/AdvancedSettingsForm.cs b/AlexaComp/Forms/AdvancedSettingsForm.cs index 3a6e498..95538a8 100644 --- a/AlexaComp/Forms/AdvancedSettingsForm.cs +++ b/AlexaComp/Forms/AdvancedSettingsForm.cs @@ -43,13 +43,13 @@ public partial class AdvancedSettingsForm : Form { if (PRIMARY == null) { PRIMARY = ""; } if (SECONDARY == null) { SECONDARY = ""; } if (TERTIARY == null) { TERTIARY = ""; } - AlexaCompCore.clog(String.Format("Custom Request Submitted - COMMAND: {0}, PRIMARY: {1}, SECONDARY: {2}, TERTIARY: {3}", + AlexaCompCore.Clog(String.Format("Custom Request Submitted - COMMAND: {0}, PRIMARY: {1}, SECONDARY: {2}, TERTIARY: {3}", COMMAND, PRIMARY, SECONDARY, TERTIARY)); Request custReq = new Request("testAuth", COMMAND.ToString(), PRIMARY.ToString(), SECONDARY.ToString(), TERTIARY.ToString()); - AlexaCompREQUEST.processRequest(custReq); + custReq.ProcessRequest(custReq); } diff --git a/AlexaComp/Forms/AlexaCompGUI.cs b/AlexaComp/Forms/AlexaCompGUI.cs index 08289b6..064dcb0 100644 --- a/AlexaComp/Forms/AlexaCompGUI.cs +++ b/AlexaComp/Forms/AlexaCompGUI.cs @@ -12,10 +12,10 @@ public partial class AlexaCompGUI : Form { public static void StartAppWindow() { Application.Run(new AlexaCompGUI()); - AlexaCompCore.clog("StartAppWinodw Thread Started"); + AlexaCompCore.Clog("StartAppWinodw Thread Started"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - AlexaCompCore.clog("StartAppWindow Task Completed"); + AlexaCompCore.Clog("StartAppWindow Task Completed"); } public AlexaCompGUI() { @@ -47,18 +47,11 @@ public partial class AlexaCompGUI : Form { // logSensorsThread.Start(true); } - private void RGBSubmitButton_Click(object sender, EventArgs e) { - string[] opt1 = new string[] { "255", "255", "255" }; - string[] opt2 = new string[] { "0", "0", "0" }; - Request requ = new Request("testAuth", "RGBCOMMAND", "RAINBOWFADEEFFECT"); - AlexaCompREQUEST.processRequest(requ); - } - /* * Opens the AlexaComp log file. */ private void openLogFileButton_Click(object sender, EventArgs e) { - AlexaCompCore.clog("OpenLogFileButtonClicked"); + AlexaCompCore.Clog("OpenLogFileButtonClicked"); System.Diagnostics.Process.Start(AlexaComp.pathToDebug + "\\AlexaCompLOG.log"); } @@ -102,7 +95,7 @@ public partial class AlexaCompGUI : Form { // Console.WriteLine("Name - " + programName + " -- " + programPath); } - AlexaCompCore.clog("Data List Reloaded"); + AlexaCompCore.Clog("Data List Reloaded"); // Reset column width foreach (ColumnHeader column in dataListView.Columns) { column.Width = -1; } } @@ -133,17 +126,17 @@ public partial class AlexaCompGUI : Form { programName = programName.Replace(" ", string.Empty).ToUpper(); // Format string string log = "{Name: " + programName + ", Path: " + programPath + "}"; - AlexaCompCore.clog("Add Program - " + log); + AlexaCompCore.Clog("Add Program - " + log); XmlDocumentFragment frag = doc.CreateDocumentFragment(); frag.InnerXml = ""; - AlexaCompCore.clog("Add new program - " + frag.InnerXml); + AlexaCompCore.Clog("Add new program - " + frag.InnerXml); doc.DocumentElement.AppendChild(frag); doc.Save(AlexaCompCore.pathToDebug + "\\pathDir.xml"); doc.Save(AlexaCompCore.pathToProject + "\\pathDir.xml"); - AlexaCompCore.clog("pathDir appended"); + AlexaCompCore.Clog("pathDir appended"); dataListView_Load(); // Reset program list @@ -175,10 +168,10 @@ public partial class AlexaCompGUI : Form { if (e != null) { base.OnFormClosing(e); } - AlexaCompCore.clog("CLOSING PROGRAM"); + AlexaCompCore.Clog("CLOSING PROGRAM"); AlexaCompCore.stopProgramFlag = true; - AlexaCompSERVER.stopServer(); - AlexaCompSERVER.delPortMap(); + AlexaCompSERVER.StopServer(); + AlexaCompSERVER.DelPortMap(); Environment.Exit(1); } @@ -189,7 +182,7 @@ public partial class AlexaCompGUI : Form { protected override void OnResize(EventArgs e) { base.OnResize(e); if (this.WindowState == FormWindowState.Minimized) { - AlexaCompCore.clog("Minimized to system tray"); + AlexaCompCore.Clog("Minimized to system tray"); Hide(); notifyIcon.Visible = true; this.ShowInTaskbar = false; diff --git a/AlexaComp/Forms/LoadingScreenForm.cs b/AlexaComp/Forms/LoadingScreenForm.cs index d6076ff..9315726 100644 --- a/AlexaComp/Forms/LoadingScreenForm.cs +++ b/AlexaComp/Forms/LoadingScreenForm.cs @@ -8,56 +8,62 @@ using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; +using System.Diagnostics; + +using AlexaComp.Core; +using AlexaComp.Core.Controllers; namespace AlexaComp { public partial class LoadingScreenForm : Form { - public LoadingScreenForm() { + public LoadingScreenForm(Stopwatch timer) { InitializeComponent(); Thread.Sleep(300); - Thread loadingThread = new Thread(startLoading); + Thread loadingThread = new Thread(unused => StartLoading(timer)); loadingThread.Start(); } - public static void startLoadingScreen() { + public static void StartLoadingScreen(object timer) { try { - Application.Run(new LoadingScreenForm()); + Application.Run(new LoadingScreenForm((Stopwatch)timer)); } catch (ObjectDisposedException) { Console.WriteLine("Caught object disposed exception"); } - } - private void startLoading() { - updateProgress("Reading Config File"); - AlexaComp.readConfig(); + private void StartLoading(Stopwatch timer) { + UpdateProgress("Reading Config File"); + AlexaComp.ReadConfig(); - updateProgress("Creating Port Map", 400); - AlexaCompSERVER.forwardPort(); + UpdateProgress("Creating Port Map", 400); + AlexaCompSERVER.ForwardPort(); - updateProgress("Scanning for RGB Devices"); + UpdateProgress("Scanning for RGB Devices"); AlexaComp.LightingControlThread.Start(); - updateProgress("Assigning Sensors"); - AlexaCompHARDWARE.assignSensors(); + UpdateProgress("Assigning Sensors"); + HardwareController.InitSensors(); - updateProgress("Getting Installed Programs"); - //AlexaComp.inventoryPrograms(); + UpdateProgress("Getting Installed Programs"); + ProgramInventory.ScanDir(); - updateProgress("Starting Server"); + UpdateProgress("Starting Server"); AlexaCompCore.ServerThread.Start(); - updateProgress("Starting Server Loop"); + UpdateProgress("Starting Server Loop"); AlexaCompCore.ServerLoopThread.Start(); - updateProgress("Starting AleComp", 400); - closeSplashScreen(); + UpdateProgress("Starting AlexaComp", 400); + CloseSplashScreen(); AlexaComp.AppWindowThread.Start(); + timer.Stop(); + AlexaCompCore.Clog(String.Format("Application Window started in {0} ms.", timer.ElapsedMilliseconds)); } - private void updateProgress(string message, int wait = 300) { + private void UpdateProgress(string message, int wait = 300) { try { + AlexaCompCore.Clog(message); progressLabel.Invoke(new MethodInvoker(delegate { progressLabel.Text = message; })); } catch (InvalidOperationException) { @@ -65,7 +71,7 @@ public partial class LoadingScreenForm : Form { // Thread.Sleep(wait); } - private void closeSplashScreen() { + private void CloseSplashScreen() { this.Invoke(new MethodInvoker(delegate { this.Close(); })); } diff --git a/AlexaComp/Tests/TestFunctions.cs b/AlexaComp/Tests/TestFunctions.cs index 3a28bdf..a3a637b 100644 --- a/AlexaComp/Tests/TestFunctions.cs +++ b/AlexaComp/Tests/TestFunctions.cs @@ -21,37 +21,37 @@ class TestFunctions : AlexaCompCore{ } public static void testRGBEffects() { - clog("Testing Error Effect"); - LightingController.LightingEffects.errorEffect(); + Clog("Testing Error Effect"); + LightingController.LightingEffects.ErrorEffect(); } public static void testColorConversions() { - clog("Testing Color Value Conversion Methods..."); + Clog("Testing Color Value Conversion Methods..."); // RGB to Hex - if (colorMethods.RGBToHex(new RGBColor(255, 0, 255)) == "FF00FF") { - clog(" RGB To Hex Conversion Passed"); + if (ColorMethods.RGBToHex(new RGBColor(255, 0, 255)) == "FF00FF") { + Clog(" RGB To Hex Conversion Passed"); } else { addFailedTest("RGB To Hex Conversion"); } // Integer Array to RGB Object int[] intArr = new int[] {255, 0, 255}; - if (colorMethods.ArrToRGB(intArr).Equals(new RGBColor(255, 0, 255))) { - clog(" Integer Array to RGB Object Conversion Passed"); + if (ColorMethods.ArrToRGB(intArr).Equals(new RGBColor(255, 0, 255))) { + Clog(" Integer Array to RGB Object Conversion Passed"); } else { addFailedTest("Int Array to RGB"); } // Hex String to RGB Object without # - if (colorMethods.HexToRGB("FF00FF").Equals(new RGBColor(255, 0, 255))) { - clog(" Hex to RGB Object ( w/o # ) Conversion Passed"); + if (ColorMethods.HexToRGB("FF00FF").Equals(new RGBColor(255, 0, 255))) { + Clog(" Hex to RGB Object ( w/o # ) Conversion Passed"); } else { addFailedTest("Hex to RGB Object ( w/o # )"); } // Hex String to RGB Object with # - if (colorMethods.HexToRGB("#FF00FF").Equals(new RGBColor(255, 0, 255))) { - clog(" Hex to RGB Object ( w/ # ) Conversion Passed"); + if (ColorMethods.HexToRGB("#FF00FF").Equals(new RGBColor(255, 0, 255))) { + Clog(" Hex to RGB Object ( w/ # ) Conversion Passed"); } else { addFailedTest("Hex to RGB Object ( w/ # )"); @@ -68,46 +68,46 @@ class TestFunctions : AlexaCompCore{ Console.WriteLine("Testing togglePlayPause"); Console.WriteLine(" Pausing"); - AudioController.togglePlayPause(); + AudioController.TogglePlayPause(); Thread.Sleep(1300); Console.WriteLine(" Playing"); - AudioController.togglePlayPause(); // Restart Music + AudioController.TogglePlayPause(); // Restart Music Console.WriteLine("Testing prevTrack"); - AudioController.prevTrack(); + AudioController.PrevTrack(); Thread.Sleep(1300); Console.WriteLine("Testing nextTrack"); - AudioController.nextTrack(); + AudioController.NextTrack(); Thread.Sleep(1300); Console.WriteLine("Testing volDown"); - AudioController.volDown(); + AudioController.VolDown(); Thread.Sleep(1300); Console.WriteLine("Testing volUp"); - AudioController.volUp(); + AudioController.VolUp(); Thread.Sleep(1300); Console.WriteLine("Testing setVolume"); Console.WriteLine(" Stepping Up"); for (int vol = 0; vol <= 100; vol += 10) { // Step Up Console.WriteLine(" Step Up - " + vol.ToString()); - AudioController.setVolume(vol); + AudioController.SetVolume(vol); Thread.Sleep(500); } Console.WriteLine(" Stepping Down"); for (int vol = 100; vol >= 50; vol -= 10) { // Step Down Console.WriteLine(" Step Down - " + vol.ToString()); - AudioController.setVolume(vol); + AudioController.SetVolume(vol); Thread.Sleep(500); } Console.WriteLine("Testing toggleMute"); - AudioController.toggleMute(); // Mute + AudioController.ToggleMute(); // Mute Thread.Sleep(1300); - AudioController.toggleMute(); // Unmute + AudioController.ToggleMute(); // Unmute } public static void testCommandFunctions() { diff --git a/AlexaComp/packages.config b/AlexaComp/packages.config index 967b9c6..12d700a 100644 --- a/AlexaComp/packages.config +++ b/AlexaComp/packages.config @@ -36,6 +36,5 @@ - \ No newline at end of file