Adding a REST like web api and introducing Json.NET

Adds the ability to handle simple REST like api calls to the Webserver.

If a POST request is received by the webserver it calls HttpServer::HandlePostRequest

"Get" Action Example:
http://localhost:8085/Sensor?action=Get&id=/ltc/example/0

This will return a JSON response containing either the value of the Sensor
or an error message.

Example response:
If it succeeded:
	{ "result" : "ok", "value" : "42" }
If it failed:
	{ "result" : "fail" , "message" : "Some error message" }

"Set" Action Example:
http://localhost:8085/Sensor?action=Set&id=/ltc/example/0&value=42.0

This will try to set the Control value of the specified Sensor.

Example response:
If it succeeded:
        { "result" : "ok" }
If it failed:
        { "result" : "fail" , "message" : "Some error message" }

The TestScripts folder contains 3 python scripts that demonstrate the
usage of the WebServer and the WMI provider.
This commit is contained in:
Marcus Tillmanns
2017-09-18 23:49:48 +02:00
parent a0db71e585
commit fc0cd04b53
7 changed files with 416 additions and 70 deletions
+210 -67
View File
@@ -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<string, string> ToDictionary(NameValueCollection col) {
IDictionary<string, string> dict = new Dictionary<string, string>();
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<string, string> 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";