diff --git a/GUI/SensorNode.cs b/GUI/SensorNode.cs index 778cae6..7038329 100644 --- a/GUI/SensorNode.cs +++ b/GUI/SensorNode.cs @@ -20,7 +20,7 @@ namespace OpenHardwareMonitor.GUI { private ISensor sensor; private PersistentSettings settings; private UnitManager unitManager; - private string format; + public string format; private bool plot = false; private Color? penColor = null; diff --git a/OpenHardwareMonitor.csproj b/OpenHardwareMonitor.csproj index 6dff957..d67db94 100644 --- a/OpenHardwareMonitor.csproj +++ b/OpenHardwareMonitor.csproj @@ -58,10 +58,15 @@ AllRules.ruleset + + packages\Newtonsoft.Json.10.0.3\lib\net20\Newtonsoft.Json.dll + True + + @@ -168,6 +173,7 @@ + Designer @@ -303,6 +309,7 @@ - + + - + \ No newline at end of file diff --git a/TestScripts/LiquidCool.py b/TestScripts/LiquidCool.py new file mode 100644 index 0000000..4ee3660 --- /dev/null +++ b/TestScripts/LiquidCool.py @@ -0,0 +1,104 @@ +################################################################ +# Install: +# * python -m pip install colorama +# * python -m pip install requests +# +# Usage: +# * MAKE SURE YOU READ THE WARNING +# * python LiquidCool.py +# +# Description: +# This script implements a simple load based control of two fans +# It first saves the original Fan settings, then starts +# monitoring the CPU and GPU load. It integrates those values +# to dampen the value changes somewhat. It then uses the maximum +# of the two values to set the fan speeds. +# +# Warning: This script is written as an example and may or may +# not kill your PC! Use at your own risk! +################################################################ + +import colorama +import json, requests +import time +import math + +url = 'http://127.0.0.1:8085' + +params = dict() + +pos = lambda x, y: '\x1b[%d;%dH' % (y, x) +clear = lambda : "\033[2J\033[1;1f" + +def getValue(sensorId): + params=dict(id=sensorId, action="Get") + resp = requests.post(url=url + "/Sensor", params = params, timeout=10); + result = json.loads(resp.text); + + if result["result"] != "ok": + raise Exception("Server returned error:\n " + result["message"].replace("\\n", "\n").replace("\\r", "")) + if result["value"] == None: + return None; + else: + return float(result["value"]) + +def setValue(sensorId, sensorValue): + if sensorValue == None: + sensorValue = "null" + params=dict(id=sensorId, action="Set", value=sensorValue) + resp = requests.post(url=url + "/Sensor", params = params, timeout=10); + result = json.loads(resp.text) + if result["result"] != "ok": + raise Exception("Server returned error:\n " + result["message"].replace("\\n", "\n").replace("\\r", "")) + +def draw_progressbar(x, y, description, progress): + p = '#'*math.floor(progress/5) + p1 = '-'*math.ceil((100-progress)/5) + print('{0}{1}[{2}{3}] {4}% '.format(pos(x,y), description, p, p1, math.floor(progress*100)/100), end='') + +def integrate(oldval, newval): + return float(oldval)*0.8 + float(newval) * 0.2 + +def main(): + colorama.init() + + print(clear()) + + try: + integratedCPU = getValue("/intelcpu/0/load/0"); + integratedGPU = getValue("/nvidiagpu/0/load/0"); + orgFan1 = getValue("/lpc/it8620e/control/0") + orgFan2 = getValue("/lpc/it8620e/control/1") + + while 1: + cpuLoad = getValue("/intelcpu/0/load/0"); + gpuLoad = getValue("/nvidiagpu/0/load/0"); + + integratedCPU = integrate(integratedCPU, cpuLoad) + integratedGPU = integrate(integratedGPU, gpuLoad) + fanVal = max(integratedCPU, integratedGPU) + fanVal = math.floor(fanVal*0.75) + + draw_progressbar(1, 1, "CPU: ", cpuLoad) + draw_progressbar(1, 2, "GPU: ", gpuLoad) + + draw_progressbar(1, 3, "IGPU: ", integratedCPU) + draw_progressbar(1, 4, "IGPU: ", integratedGPU) + + draw_progressbar(1, 5, "Fans: ", fanVal) + + setValue("/lpc/it8620e/control/0", fanVal); + setValue("/lpc/it8620e/control/1", fanVal); + + print(pos(1, 1)) + time.sleep(1) + except: + print(clear()) + setValue("/lpc/it8620e/control/0", orgFan1); + setValue("/lpc/it8620e/control/1", orgFan2); + raise + + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/TestScripts/basicrest.py b/TestScripts/basicrest.py new file mode 100644 index 0000000..5d484b3 --- /dev/null +++ b/TestScripts/basicrest.py @@ -0,0 +1,71 @@ +################################################################ +# Install: +# * python -m pip install requests +# +# Usage: +# * python basicrest.py +# +# Description: +# A simple test of the REST Like API +################################################################ + +import json, requests +import time + +url = 'http://127.0.0.1:8085' + +def findSensors(node): + sensors = {} + + if len(node["Children"]) > 0: + for child in node["Children"]: + sensors.update(findSensors(child)) + else: + if "Type" in node: + sensors[node["SensorId"]] = node + + return sensors + +def getValue(sensorId): + params=dict(id=sensorId, action="Get") + resp = requests.post(url=url + "/Sensor", params = params, timeout=10); + result = json.loads(resp.text); + + if result["result"] != "ok": + raise Exception("Server returned error:\n " + result["message"].replace("\\n", "\n").replace("\\r", "")) + if result["value"] == None: + return None; + else: + return float(result["value"]) + +def setValue(sensorId, sensorValue): + if sensorValue == None: + sensorValue = "null" + params=dict(id=sensorId, action="Set", value=sensorValue) + resp = requests.post(url=url + "/Sensor", params = params, timeout=10); + result = json.loads(resp.text) + if result["result"] != "ok": + raise Exception("Server returned error:\n " + result["message"].replace("\\n", "\n").replace("\\r", "")) + +def main(): + params = dict() + + print("Fetching all sensor ids:") + resp = requests.get(url=url + "/data.json", params=params, timeout=10) + data = json.loads(resp.text) + sensors = findSensors(data) + + for key, value in sensors.items(): + v = getValue(key) + print(key, ":", v); + + # Change the id to one of yours + print("Setting GPU Fan to full speed!") + setValue("/nvidiagpu/0/control/0", "100.0") + time.sleep(10); + print("Returning GPU Fan speed to default") + setValue("/nvidiagpu/0/control/0", None) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/TestScripts/basicwmi.py b/TestScripts/basicwmi.py new file mode 100644 index 0000000..08a22ad --- /dev/null +++ b/TestScripts/basicwmi.py @@ -0,0 +1,17 @@ +################################################################ +# Install: +# * python.exe -m pip install pypiwin32 +# * python.exe -m pip install wmi +# +# Usage: +# * !! Make sure openhardwaremonitor is running !! +# * python basicwmi.py +################################################################ + +import wmi + +hwmon = wmi.WMI(namespace="root\OpenHardwareMonitor") +sensors = hwmon.Sensor(SensorType="Control") + +for s in sensors: + print s diff --git a/Utilities/HttpServer.cs b/Utilities/HttpServer.cs index dfac102..f32a968 100644 --- a/Utilities/HttpServer.cs +++ b/Utilities/HttpServer.cs @@ -19,12 +19,17 @@ using System.Text; using System.Threading; using OpenHardwareMonitor.GUI; using OpenHardwareMonitor.Hardware; +using System.Web; +using System.Collections.Specialized; +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json.Linq; namespace OpenHardwareMonitor.Utilities { public class HttpServer { private HttpListener listener; - private int listenerPort, nodeCount; + private int listenerPort; private Thread listenerThread; private Node root; @@ -32,9 +37,6 @@ namespace OpenHardwareMonitor.Utilities { root = node; listenerPort = port; - //JSON node count. - nodeCount = 0; - try { listener = new HttpListener(); listener.IgnoreWriteExceptions = true; @@ -98,6 +100,126 @@ namespace OpenHardwareMonitor.Utilities { } } + public static IDictionary ToDictionary(NameValueCollection col) { + IDictionary dict = new Dictionary(); + foreach (var k in col.AllKeys) { + dict.Add(k, col[k]); + } + return dict; + } + + public SensorNode FindSensor(Node node, string id) { + if (node is SensorNode) { + SensorNode sNode = (SensorNode)node; + if (sNode.Sensor.Identifier.ToString() == id) + return sNode; + } + foreach (Node child in node.Nodes) { + SensorNode s = FindSensor(child, id); + if (s != null) { + return s; + } + } + return null; + } + + public void SetSensorControlValue(SensorNode sNode, string value) { + if(sNode.Sensor.Control == null) { + throw new ArgumentException("Specified sensor '" + sNode.Sensor.Identifier + "' can not be set"); + } + if (value == "null") { + sNode.Sensor.Control.SetDefault(); + } + else { + sNode.Sensor.Control.SetSoftware(float.Parse(value, CultureInfo.InvariantCulture)); + } + } + + /* + * Handles "/Sensor" requests. + * Parameters are taken from the query part of the URL. + * Get: + * http://localhost:8085/Sensor?action=Get&id=/some/node/path/0 + * The output is either: + * {"result":"fail","message":"Some error message"} + * or: + * {"result":"ok","value":42.0, "format":"{0:F2} RPM"} + * + * Set: + * http://localhost:8085/Sensor?action=Set&id=/some/node/path/0&value=42.0 + * http://localhost:8085/Sensor?action=Set&id=/some/node/path/0&value=null + * The output is either: + * {"result":"fail","message":"Some error message"} + * or: + * {"result":"ok"} + */ + private void HandleSensorRequest(HttpListenerRequest request, JObject result) { + IDictionary dict = ToDictionary(HttpUtility.ParseQueryString(request.Url.Query)); + + if (dict.ContainsKey("action")) { + if (dict.ContainsKey("id")) { + SensorNode sNode = FindSensor(root, dict["id"]); + + if(sNode == null) { + throw new ArgumentException("Unknown id " + dict["id"] + " specified"); + } + + if (dict["action"] == "Set") { + if (dict.ContainsKey("value")) { + SetSensorControlValue(sNode, dict["value"]); + } + else { + throw new ArgumentNullException("No value provided"); + } + } + else if (dict["action"] == "Get") { + result["value"] = sNode.Sensor.Value; + result["format"] = sNode.format; + } + else { + throw new ArgumentException("Unknown action type " + dict["action"]); + } + } + else { + throw new ArgumentNullException("No id provided"); + } + } + else { + throw new ArgumentNullException("No action provided"); + } + } + + /* + * Handles http POST requests in a REST like manner. + * Currently the only supported base URL is http://localhost:8085/Sensor. + */ + private string HandlePostRequest(HttpListenerRequest request) { + JObject result = new JObject(); + + result["result"] = "ok"; + + try { + if (request.Url.Segments.Length == 2) { + if (request.Url.Segments[1] == "Sensor") { + HandleSensorRequest(request, result); + } + else + throw new ArgumentException("Invalid URL ('" + request.Url.Segments[1] + "'), possible values: ['Sensor']"); + } + else + throw new ArgumentException("Empty URL, possible values: ['Sensor']"); + } + catch(Exception e) { + result["result"] = "fail"; + result["message"] = e.ToString(); + } +#if DEBUG + return result.ToString(Newtonsoft.Json.Formatting.Indented); +#else + return result.ToString(Newtonsoft.Json.Formatting.None); +#endif + } + private void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; if (listener == null || !listener.IsListening) @@ -113,26 +235,45 @@ namespace OpenHardwareMonitor.Utilities { HttpListenerRequest request = context.Request; - var requestedFile = request.RawUrl.Substring(1); - if (requestedFile == "data.json") { - SendJSON(context.Response); - return; + if (request.HttpMethod == "POST") { + string postResult = HandlePostRequest(request); + + Stream output = context.Response.OutputStream; + byte[] utfBytes = Encoding.UTF8.GetBytes(postResult); + + context.Response.AddHeader("Cache-Control", "no-cache"); + context.Response.ContentLength64 = utfBytes.Length; + context.Response.ContentType = "application/json"; + + output.Write(utfBytes, 0, utfBytes.Length); + output.Close(); } + else if(request.HttpMethod == "GET") { + var requestedFile = request.RawUrl.Substring(1); - if (requestedFile.Contains("images_icon")) { - ServeResourceImage(context.Response, - requestedFile.Replace("images_icon/", "")); - return; + if (requestedFile == "data.json") { + SendJSON(context.Response); + return; + } + + if (requestedFile.Contains("images_icon")) { + ServeResourceImage(context.Response, + requestedFile.Replace("images_icon/", "")); + return; + } + + // default file to be served + if (string.IsNullOrEmpty(requestedFile)) + requestedFile = "index.html"; + + string[] splits = requestedFile.Split('.'); + string ext = splits[splits.Length - 1]; + ServeResourceFile(context.Response, "Web." + requestedFile.Replace('/', '.'), ext); + } + else { + context.Response.StatusCode = 404; + context.Response.Close(); } - - // default file to be served - if (string.IsNullOrEmpty(requestedFile)) - requestedFile = "index.html"; - - string[] splits = requestedFile.Split('.'); - string ext = splits[splits.Length - 1]; - ServeResourceFile(context.Response, - "Web." + requestedFile.Replace('/', '.'), ext); } private void ServeResourceFile(HttpListenerResponse response, string name, @@ -148,7 +289,7 @@ namespace OpenHardwareMonitor.Utilities { if (names[i].Replace('\\', '.') == name) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { - response.ContentType = GetcontentType("." + ext); + response.ContentType = GetContentType("." + ext); response.ContentLength64 = stream.Length; byte[] buffer = new byte[512 * 1024]; int len; @@ -205,22 +346,28 @@ namespace OpenHardwareMonitor.Utilities { } private void SendJSON(HttpListenerResponse response) { + JObject json = new JObject(); - string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": ["; - nodeCount = 1; - JSON += GenerateJSON(root); - JSON += "]"; - JSON += ", \"Min\": \"Min\""; - JSON += ", \"Value\": \"Value\""; - JSON += ", \"Max\": \"Max\""; - JSON += ", \"ImageURL\": \"\""; - JSON += "}"; + int nodeIndex = 0; - var responseContent = JSON; + json["id"] = nodeIndex++; + json["Text"] = "Sensor"; + json["Min"] = "Min"; + json["Value"] = "Value"; + json["Max"] = "Max"; + json["ImageURL"] = ""; + + JArray children = new JArray(); + children.Add(GenerateJSONForNode(root, ref nodeIndex)); + json["Children"] = children; +#if DEBUG + var responseContent = json.ToString(Newtonsoft.Json.Formatting.Indented); +#else + var responseContent = json.ToString(Newtonsoft.Json.Formatting.None); +#endif byte[] buffer = Encoding.UTF8.GetBytes(responseContent); response.AddHeader("Cache-Control", "no-cache"); - response.ContentLength64 = buffer.Length; response.ContentType = "application/json"; @@ -234,49 +381,45 @@ namespace OpenHardwareMonitor.Utilities { response.Close(); } - private string GenerateJSON(Node n) { - string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text - + "\", \"Children\": ["; - nodeCount++; - - foreach (Node child in n.Nodes) - JSON += GenerateJSON(child) + ", "; - if (JSON.EndsWith(", ")) - JSON = JSON.Remove(JSON.LastIndexOf(",")); - JSON += "]"; + private JObject GenerateJSONForNode(Node n, ref int nodeIndex) { + JObject jsonNode = new JObject(); + jsonNode["id"] = nodeIndex++; + jsonNode["Text"] = n.Text; + jsonNode["Min"] = ""; + jsonNode["Value"] = ""; + jsonNode["Max"] = ""; if (n is SensorNode) { - JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\""; - JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\""; - JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\""; - JSON += ", \"ImageURL\": \"images/transparent.png\""; - } else if (n is HardwareNode) { - JSON += ", \"Min\": \"\""; - JSON += ", \"Value\": \"\""; - JSON += ", \"Max\": \"\""; - JSON += ", \"ImageURL\": \"images_icon/" + - GetHardwareImageFile((HardwareNode)n) + "\""; - } else if (n is TypeNode) { - JSON += ", \"Min\": \"\""; - JSON += ", \"Value\": \"\""; - JSON += ", \"Max\": \"\""; - JSON += ", \"ImageURL\": \"images_icon/" + - GetTypeImageFile((TypeNode)n) + "\""; + jsonNode["SensorId"] = ((SensorNode)n).Sensor.Identifier.ToString(); + jsonNode["Type"] = ((SensorNode)n).Sensor.SensorType.ToString(); + jsonNode["Min"] = ((SensorNode)n).Min; + jsonNode["Value"] = ((SensorNode)n).Value; + jsonNode["Max"] = ((SensorNode)n).Max; + jsonNode["ImageURL"] = "images/transparent.png"; + } + else if (n is HardwareNode) { + jsonNode["ImageURL"] = "images_icon/" + GetHardwareImageFile((HardwareNode)n); + } + else if (n is TypeNode) { + jsonNode["ImageURL"] = "images_icon/" + GetTypeImageFile((TypeNode)n); } else { - JSON += ", \"Min\": \"\""; - JSON += ", \"Value\": \"\""; - JSON += ", \"Max\": \"\""; - JSON += ", \"ImageURL\": \"images_icon/computer.png\""; + jsonNode["ImageURL"] = "images_icon/computer.png"; } - JSON += "}"; - return JSON; + JArray children = new JArray(); + foreach (Node child in n.Nodes) { + children.Add(GenerateJSONForNode(child, ref nodeIndex)); + } + + jsonNode["Children"] = children; + + return jsonNode; } private static void ReturnFile(HttpListenerContext context, string filePath) { context.Response.ContentType = - GetcontentType(Path.GetExtension(filePath)); + GetContentType(Path.GetExtension(filePath)); const int bufferSize = 1024 * 512; //512KB var buffer = new byte[bufferSize]; using (var fs = File.OpenRead(filePath)) { @@ -290,7 +433,7 @@ namespace OpenHardwareMonitor.Utilities { context.Response.OutputStream.Close(); } - private static string GetcontentType(string extension) { + private static string GetContentType(string extension) { switch (extension) { case ".avi": return "video/x-msvideo"; case ".css": return "text/css"; diff --git a/appveyor.yml b/appveyor.yml index 1e0198d..a102f20 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,7 +1,15 @@ image: Visual Studio 2015 +before_build: + - nuget restore + +configuration: + - Debug + - Release + build: project: OpenHardwareMonitor.sln artifacts: - path: 'Bin\Debug\' + - path: 'Bin\Release\' diff --git a/packages.config b/packages.config new file mode 100644 index 0000000..86df876 --- /dev/null +++ b/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file