From c5b9a7ec091369d3198c30daf8fada9c6436caa4 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 11:44:00 +0200 Subject: [PATCH 01/24] made rh engine classes public --- Client/Client.csproj | 1 + Client/Program.cs | 1 + RH-Engine/Command.cs | 2 +- RH-Engine/JSONParser.cs | 2 +- RH-Engine/Program.cs | 19 +------------------ 5 files changed, 5 insertions(+), 20 deletions(-) diff --git a/Client/Client.csproj b/Client/Client.csproj index dd9af6e..4ade6d5 100644 --- a/Client/Client.csproj +++ b/Client/Client.csproj @@ -12,6 +12,7 @@ + diff --git a/Client/Program.cs b/Client/Program.cs index 7b722f5..9853e51 100644 --- a/Client/Program.cs +++ b/Client/Program.cs @@ -1,6 +1,7 @@ using System; using Hardware; using Hardware.Simulators; +using RH_Engine; namespace Client { diff --git a/RH-Engine/Command.cs b/RH-Engine/Command.cs index 3ef3bc1..0f53e73 100644 --- a/RH-Engine/Command.cs +++ b/RH-Engine/Command.cs @@ -4,7 +4,7 @@ using System; namespace RH_Engine { - class Command + public class Command { public const string STANDARD_HEAD = "Head"; public const string STANDARD_GROUND = "GroundPlane"; diff --git a/RH-Engine/JSONParser.cs b/RH-Engine/JSONParser.cs index 8621aff..292c524 100644 --- a/RH-Engine/JSONParser.cs +++ b/RH-Engine/JSONParser.cs @@ -3,7 +3,7 @@ using System; namespace RH_Engine { - class JSONParser + public class JSONParser { /// /// returns all the users from the given response diff --git a/RH-Engine/Program.cs b/RH-Engine/Program.cs index 63c86fb..e67206a 100644 --- a/RH-Engine/Program.cs +++ b/RH-Engine/Program.cs @@ -10,7 +10,7 @@ namespace RH_Engine { public delegate void HandleSerial(string message); - class Program + public class Program { private static PC[] PCs = { //new PC("DESKTOP-M2CIH87", "Fabian"), @@ -161,23 +161,6 @@ namespace RH_Engine }); Console.WriteLine("id of head " + GetId(Command.STANDARD_HEAD, stream, mainCommand)); - - //command = mainCommand.AddModel("car", "data\\customModels\\TeslaRoadster.fbx"); - //WriteTextMessage(stream, command); - - //command = mainCommand.addPanel(); - // WriteTextMessage(stream, command); - // string response = ReadPrefMessage(stream); - // Console.WriteLine("add Panel response: \n\r" + response); - // string uuidPanel = JSONParser.getPanelID(response); - // WriteTextMessage(stream, mainCommand.ClearPanel(uuidPanel)); - // Console.WriteLine(ReadPrefMessage(stream)); - // WriteTextMessage(stream, mainCommand.bikeSpeed(uuidPanel, 2.42)); - // Console.WriteLine(ReadPrefMessage(stream)); - // WriteTextMessage(stream, mainCommand.ColorPanel(uuidPanel)); - // Console.WriteLine("Color panel: " + ReadPrefMessage(stream)); - // WriteTextMessage(stream, mainCommand.SwapPanel(uuidPanel)); - // Console.WriteLine("Swap panel: " + ReadPrefMessage(stream)); } /// From 7b05fcc8982fa5349a645b1294c09446223bf0ad Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:01:53 +0200 Subject: [PATCH 02/24] added engineconnect as singleton --- Client/EngineConnect.cs | 97 +++++++++++++++++++++++++++++++ RH-Engine/ServerResponseReader.cs | 2 +- 2 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 Client/EngineConnect.cs diff --git a/Client/EngineConnect.cs b/Client/EngineConnect.cs new file mode 100644 index 0000000..78dc20c --- /dev/null +++ b/Client/EngineConnect.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Text; +using RH_Engine; +using System.Net.Sockets; + +namespace Client +{ + public delegate void HandleSerial(string message); + + public sealed class EngineConnect + { + private static EngineConnect instance = null; + private static readonly object padlock = new object(); + + + private static PC[] PCs = { + //new PC("DESKTOP-M2CIH87", "Fabian"), + //new PC("T470S", "Shinichi"), + //new PC("DESKTOP-DHS478C", "semme"), + new PC("HP-ZBOOK-SEM", "Sem"), + //new PC("DESKTOP-TV73FKO", "Wouter"), + new PC("DESKTOP-SINMKT1", "Ralf van Aert"), + //new PC("NA", "Bart") + }; + + private static ServerResponseReader serverResponseReader; + private static string sessionId = string.Empty; + private static string tunnelId = string.Empty; + private static string routeId = string.Empty; + private static string panelId = string.Empty; + private static string bikeId = string.Empty; + + private static Dictionary serialResponses = new Dictionary(); + + + EngineConnect() + { + + } + + public static EngineConnect INSTANCE + { + get + { + lock (padlock) + { + if (instance == null) + { + instance = new EngineConnect(); + } + }return instance; + } + } + + public static void Connect() + { + TcpClient client = new TcpClient("145.48.6.10", 6666); + + CreateConnection(client.GetStream()); + } + + /// + /// connects to the server and creates the tunnel + /// + /// the network stream to use + private static void CreateConnection(NetworkStream stream) + { + initReader(stream); + + WriteTextMessage(stream, "{\r\n\"id\" : \"session/list\",\r\n\"serial\" : \"list\"\r\n}"); + + // wait until we have got a sessionId + while (sessionId == string.Empty) { } + + string tunnelCreate = "{\"id\" : \"tunnel/create\", \"data\" : {\"session\" : \"" + sessionId + "\"}}"; + + WriteTextMessage(stream, tunnelCreate); + + // wait until we have a tunnel id + while (tunnelId == string.Empty) { } + Console.WriteLine("got tunnel id! sending commands..."); + sendCommands(stream, tunnelId); + } + } + + /// + /// initializes and starts the reading of the responses from the vr server + /// + /// the networkstream + private static void initReader(NetworkStream stream) + { + serverResponseReader = new ServerResponseReader(stream); + serverResponseReader.callback = HandleResponse; + serverResponseReader.StartRead(); + } +} diff --git a/RH-Engine/ServerResponseReader.cs b/RH-Engine/ServerResponseReader.cs index 85e7f00..feeef05 100644 --- a/RH-Engine/ServerResponseReader.cs +++ b/RH-Engine/ServerResponseReader.cs @@ -7,7 +7,7 @@ namespace RH_Engine { public delegate void OnResponse(string response); - class ServerResponseReader + public class ServerResponseReader { public OnResponse callback { From d06d621b13d897ce72b52e4d90818561ba90d6d6 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:13:59 +0200 Subject: [PATCH 03/24] added necessary methods and added method sig to cw of engineconnect --- Client/EngineConnect.cs | 97 ------------------------------- RH-Engine/ServerResponseReader.cs | 2 +- 2 files changed, 1 insertion(+), 98 deletions(-) delete mode 100644 Client/EngineConnect.cs diff --git a/Client/EngineConnect.cs b/Client/EngineConnect.cs deleted file mode 100644 index 78dc20c..0000000 --- a/Client/EngineConnect.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using RH_Engine; -using System.Net.Sockets; - -namespace Client -{ - public delegate void HandleSerial(string message); - - public sealed class EngineConnect - { - private static EngineConnect instance = null; - private static readonly object padlock = new object(); - - - private static PC[] PCs = { - //new PC("DESKTOP-M2CIH87", "Fabian"), - //new PC("T470S", "Shinichi"), - //new PC("DESKTOP-DHS478C", "semme"), - new PC("HP-ZBOOK-SEM", "Sem"), - //new PC("DESKTOP-TV73FKO", "Wouter"), - new PC("DESKTOP-SINMKT1", "Ralf van Aert"), - //new PC("NA", "Bart") - }; - - private static ServerResponseReader serverResponseReader; - private static string sessionId = string.Empty; - private static string tunnelId = string.Empty; - private static string routeId = string.Empty; - private static string panelId = string.Empty; - private static string bikeId = string.Empty; - - private static Dictionary serialResponses = new Dictionary(); - - - EngineConnect() - { - - } - - public static EngineConnect INSTANCE - { - get - { - lock (padlock) - { - if (instance == null) - { - instance = new EngineConnect(); - } - }return instance; - } - } - - public static void Connect() - { - TcpClient client = new TcpClient("145.48.6.10", 6666); - - CreateConnection(client.GetStream()); - } - - /// - /// connects to the server and creates the tunnel - /// - /// the network stream to use - private static void CreateConnection(NetworkStream stream) - { - initReader(stream); - - WriteTextMessage(stream, "{\r\n\"id\" : \"session/list\",\r\n\"serial\" : \"list\"\r\n}"); - - // wait until we have got a sessionId - while (sessionId == string.Empty) { } - - string tunnelCreate = "{\"id\" : \"tunnel/create\", \"data\" : {\"session\" : \"" + sessionId + "\"}}"; - - WriteTextMessage(stream, tunnelCreate); - - // wait until we have a tunnel id - while (tunnelId == string.Empty) { } - Console.WriteLine("got tunnel id! sending commands..."); - sendCommands(stream, tunnelId); - } - } - - /// - /// initializes and starts the reading of the responses from the vr server - /// - /// the networkstream - private static void initReader(NetworkStream stream) - { - serverResponseReader = new ServerResponseReader(stream); - serverResponseReader.callback = HandleResponse; - serverResponseReader.StartRead(); - } -} diff --git a/RH-Engine/ServerResponseReader.cs b/RH-Engine/ServerResponseReader.cs index feeef05..17e86ba 100644 --- a/RH-Engine/ServerResponseReader.cs +++ b/RH-Engine/ServerResponseReader.cs @@ -31,7 +31,7 @@ namespace RH_Engine } else { - Console.WriteLine("Starting loop for reading"); + Console.WriteLine("[SERVERRESPONSEREADER] Starting loop for reading"); while (true) { string res = ReadPrefMessage(Stream); From 3ca3c1ad78b732f3645eae38fec377c2bd378d3a Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:17:57 +0200 Subject: [PATCH 04/24] added engineconnection to client --- Client/Client.cs | 5 ++ Client/EngineConnection.cs | 171 +++++++++++++++++++++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 Client/EngineConnection.cs diff --git a/Client/Client.cs b/Client/Client.cs index 123d222..3701599 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -14,6 +14,7 @@ namespace Client private bool connected; private byte[] totalBuffer = new byte[1024]; private int totalBufferReceived = 0; + private EngineConnection engineConnection; public Client() : this("localhost", 5555) @@ -26,6 +27,10 @@ namespace Client this.client = new TcpClient(); this.connected = false; client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); + + engineConnection = EngineConnection.INSTANCE; + engineConnection.Connect(); + } private void OnConnect(IAsyncResult ar) diff --git a/Client/EngineConnection.cs b/Client/EngineConnection.cs new file mode 100644 index 0000000..463dabc --- /dev/null +++ b/Client/EngineConnection.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Text; +using RH_Engine; +using System.Net.Sockets; + +namespace Client +{ + public delegate void HandleSerial(string message); + + public sealed class EngineConnection + { + private static EngineConnection instance = null; + private static readonly object padlock = new object(); + + + private static PC[] PCs = { + //new PC("DESKTOP-M2CIH87", "Fabian"), + //new PC("T470S", "Shinichi"), + //new PC("DESKTOP-DHS478C", "semme"), + new PC("HP-ZBOOK-SEM", "Sem"), + //new PC("DESKTOP-TV73FKO", "Wouter"), + new PC("DESKTOP-SINMKT1", "Ralf van Aert"), + //new PC("NA", "Bart") + }; + + private static ServerResponseReader serverResponseReader; + private static string sessionId = string.Empty; + private static string tunnelId = string.Empty; + private static string routeId = string.Empty; + private static string panelId = string.Empty; + private static string bikeId = string.Empty; + + private static NetworkStream stream; + + private static Dictionary serialResponses = new Dictionary(); + + public bool Connected = false; + + EngineConnection() + { + + } + + public static EngineConnection INSTANCE + { + get + { + lock (padlock) + { + if (instance == null) + { + instance = new EngineConnection(); + } + } + return instance; + } + } + + public void Connect() + { + TcpClient client = new TcpClient("145.48.6.10", 6666); + stream = client.GetStream(); + CreateConnection(); + } + + /// + /// connects to the server and creates the tunnel + /// + /// the network stream to use + private void CreateConnection() + { + initReader(); + + WriteTextMessage( "{\r\n\"id\" : \"session/list\",\r\n\"serial\" : \"list\"\r\n}"); + + // wait until we have got a sessionId + while (sessionId == string.Empty) { } + + string tunnelCreate = "{\"id\" : \"tunnel/create\", \"data\" : {\"session\" : \"" + sessionId + "\"}}"; + + WriteTextMessage(tunnelCreate); + + // wait until we have a tunnel id + while (tunnelId == string.Empty) { } + Write("got tunnel id! sending commands..."); + + } + /// + /// initializes and starts the reading of the responses from the vr server + /// + /// the networkstream + private void initReader() + { + serverResponseReader = new ServerResponseReader(stream); + serverResponseReader.callback = HandleResponse; + serverResponseReader.StartRead(); + Connected = true; + } + + /// + /// callback method that handles responses from the server + /// + /// the response message from the server + public void HandleResponse(string message) + { + string id = JSONParser.GetID(message); + + // because the first messages don't have a serial, we need to check on the id + if (id == "session/list") + { + sessionId = JSONParser.GetSessionID(message, PCs); + } + else if (id == "tunnel/create") + { + tunnelId = JSONParser.GetTunnelID(message); + if (tunnelId == null) + { + Write("could not find a valid tunnel id!"); + return; + } + } + + if (message.Contains("serial")) + { + //Console.WriteLine("GOT MESSAGE WITH SERIAL: " + message + "\n\n\n"); + string serial = JSONParser.GetSerial(message); + //Console.WriteLine("Got serial " + serial); + if (serialResponses.ContainsKey(serial)) serialResponses[serial].Invoke(message); + } + } + + /// + /// method that sends the speciefied message with the specified serial, and executes the given action upon receivind a reply from the server with this serial. + /// + /// the networkstream to use + /// the message to send + /// the serial to check for + /// the code to be executed upon reveiving a reply from the server with the specified serial + public void SendMessageAndOnResponse(string message, string serial, HandleSerial action) + { + serialResponses.Add(serial, action); + WriteTextMessage(message); + } + + /// + /// writes a message to the server + /// + /// the network stream to use + /// the message to send + public void WriteTextMessage(string message) + { + byte[] msg = Encoding.ASCII.GetBytes(message); + byte[] res = new byte[msg.Length + 4]; + + Array.Copy(BitConverter.GetBytes(msg.Length), 0, res, 0, 4); + Array.Copy(msg, 0, res, 4, msg.Length); + + stream.Write(res); + + Write("sent message " + message); + } + public void Write(string msg) + { + Console.WriteLine( "[ENGINECONNECT] " + msg); + } + + } + + +} From 0dc4bb6fade21f28c777b194f9d6e5bbdcffacd9 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:23:53 +0200 Subject: [PATCH 05/24] connected engine to client --- Client/Client.cs | 6 ++++++ Client/EngineConnection.cs | 2 +- RH-Engine/JSONParser.cs | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index 3701599..3dc361e 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Net.Sockets; using System.Text; +using System.Threading; using ProftaakRH; namespace Client @@ -27,7 +28,12 @@ namespace Client this.client = new TcpClient(); this.connected = false; client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); + initEngine(); + } + + private void initEngine() + { engineConnection = EngineConnection.INSTANCE; engineConnection.Connect(); diff --git a/Client/EngineConnection.cs b/Client/EngineConnection.cs index 463dabc..ff9b5e2 100644 --- a/Client/EngineConnection.cs +++ b/Client/EngineConnection.cs @@ -83,7 +83,7 @@ namespace Client // wait until we have a tunnel id while (tunnelId == string.Empty) { } - Write("got tunnel id! sending commands..."); + Write("got tunnel id! " + tunnelId); } /// diff --git a/RH-Engine/JSONParser.cs b/RH-Engine/JSONParser.cs index 292c524..c8e0c9b 100644 --- a/RH-Engine/JSONParser.cs +++ b/RH-Engine/JSONParser.cs @@ -36,7 +36,7 @@ namespace RH_Engine { if (d.clientinfo.host == pc.host && d.clientinfo.user == pc.user) { - Console.WriteLine("connecting to {0}, on {1} with id {2}", pc.user, pc.host, d.id); + Console.WriteLine("[JSONPARSER] connecting to {0}, on {1} with id {2}", pc.user, pc.host, d.id); return d.id; } } From 4388b39be53a1c5e2326a0482444d96bbdb183e4 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:27:31 +0200 Subject: [PATCH 06/24] only connects when username and password are entered --- Client/Client.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index 3dc361e..0472236 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -28,14 +28,14 @@ namespace Client this.client = new TcpClient(); this.connected = false; client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); - initEngine(); + } private void initEngine() { engineConnection = EngineConnection.INSTANCE; - engineConnection.Connect(); + if (!engineConnection.Connected) engineConnection.Connect(); } @@ -154,7 +154,9 @@ namespace Client byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(username, password)); + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + initEngine(); } } } From 0cd3753b7663490f15710cb3eb2015c7fce744af Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:30:40 +0200 Subject: [PATCH 07/24] properly added engineconnection to client --- Client/Client.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index 0472236..e65204f 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Net.Sockets; using System.Text; -using System.Threading; using ProftaakRH; namespace Client @@ -28,15 +27,14 @@ namespace Client this.client = new TcpClient(); this.connected = false; client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); - + initEngine(); } private void initEngine() { engineConnection = EngineConnection.INSTANCE; if (!engineConnection.Connected) engineConnection.Connect(); - } private void OnConnect(IAsyncResult ar) @@ -154,9 +152,8 @@ namespace Client byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(username, password)); - - this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); initEngine(); + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); } } } From 341723d1d13b40882ddcfa4ec205a909d3e66542 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 12:59:04 +0200 Subject: [PATCH 08/24] added maincommand to engineconnection --- Client/EngineConnection.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Client/EngineConnection.cs b/Client/EngineConnection.cs index ff9b5e2..965673b 100644 --- a/Client/EngineConnection.cs +++ b/Client/EngineConnection.cs @@ -34,6 +34,7 @@ namespace Client private static NetworkStream stream; private static Dictionary serialResponses = new Dictionary(); + private Command mainCommand; public bool Connected = false; @@ -84,6 +85,7 @@ namespace Client // wait until we have a tunnel id while (tunnelId == string.Empty) { } Write("got tunnel id! " + tunnelId); + mainCommand = new Command(tunnelId); } /// From 6f1ab57fe4e3f1cbdefc6773858b6972f027c7a7 Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 13:00:13 +0200 Subject: [PATCH 09/24] saving in binairy format took forever --- Server/Client.cs | 3 +-- Server/SaveData.cs | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Server/Client.cs b/Server/Client.cs index 5e385be..78abf58 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -123,7 +123,6 @@ namespace Server Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); break; } - Array.Copy(message, 5, payloadbytes, 0, message.Length - 5); dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payloadbytes)); saveData.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes)); @@ -131,7 +130,7 @@ namespace Server else if (DataParser.isRawData(message)) { Console.WriteLine(BitConverter.ToString(message)); - saveData.WriteDataRAW(ByteArrayToString(message)); + saveData.WriteDataRAW(message); } diff --git a/Server/SaveData.cs b/Server/SaveData.cs index 0286bde..ffaaf90 100644 --- a/Server/SaveData.cs +++ b/Server/SaveData.cs @@ -22,20 +22,33 @@ namespace Server /// /// Every line is a new data entry /// - + public void WriteDataJSON(string data) { - using (StreamWriter sw = File.AppendText(this.path + "/json"+filename+".txt")) + using (StreamWriter sw = File.AppendText(this.path + "/json" + filename + ".txt")) { sw.WriteLine(data); } } - public void WriteDataRAW(string data) + public void WriteDataRAW(byte[] data) { - using (StreamWriter sw = File.AppendText(this.path + "/raw" + filename + ".txt")) + int length = 0; + try { - sw.WriteLine(data); + FileInfo fi = new FileInfo(this.path + "/raw" + filename + ".bin"); + length = (int)fi.Length; + } + catch + { + + } + using (BinaryWriter sw = new BinaryWriter(File.Open(this.path + "/raw" + filename + ".bin", FileMode.Create))) + { + + Console.WriteLine("head position " + sw.Seek(length, SeekOrigin.End)); + sw.Write(data); + sw.Flush(); } } } From 82f2d6b71c513ff03d59b2ff4bb64676690dff5c Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 14:17:26 +0200 Subject: [PATCH 10/24] saving bike and bpm data in separate files --- Server/Client.cs | 15 +++++++++++++-- Server/SaveData.cs | 29 ++++++++++++++++++++++++----- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/Server/Client.cs b/Server/Client.cs index 78abf58..30d7efc 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -129,8 +129,19 @@ namespace Server } else if (DataParser.isRawData(message)) { - Console.WriteLine(BitConverter.ToString(message)); - saveData.WriteDataRAW(message); + Console.WriteLine(BitConverter.ToString(payloadbytes)); + if (payloadbytes.Length == 8) + { + saveData.WriteDataRAWBike(payloadbytes); + } + else if (payloadbytes.Length == 2) + { + saveData.WriteDataRAWBPM(payloadbytes); + } + else + { + Console.WriteLine("received raw data with weird lenght " + BitConverter.ToString(payloadbytes)); + } } diff --git a/Server/SaveData.cs b/Server/SaveData.cs index ffaaf90..be5412b 100644 --- a/Server/SaveData.cs +++ b/Server/SaveData.cs @@ -31,22 +31,41 @@ namespace Server } } - public void WriteDataRAW(byte[] data) + public void WriteDataRAWBPM(byte[] data) { int length = 0; try { - FileInfo fi = new FileInfo(this.path + "/raw" + filename + ".bin"); + FileInfo fi = new FileInfo(this.path + "/rawBPM" + filename + ".bin"); length = (int)fi.Length; } catch { - + // do nothing } - using (BinaryWriter sw = new BinaryWriter(File.Open(this.path + "/raw" + filename + ".bin", FileMode.Create))) + using (BinaryWriter sw = new BinaryWriter(File.Open(this.path + "/rawBPM" + filename + ".bin", FileMode.Create))) { + sw.Seek(length, SeekOrigin.End); + sw.Write(data); + sw.Flush(); + } + } - Console.WriteLine("head position " + sw.Seek(length, SeekOrigin.End)); + public void WriteDataRAWBike(byte[] data) + { + int length = 0; + try + { + FileInfo fi = new FileInfo(this.path + "/rawBike" + filename + ".bin"); + length = (int)fi.Length; + } + catch + { + // do nothing + } + using (BinaryWriter sw = new BinaryWriter(File.Open(this.path + "/rawBike" + filename + ".bin", FileMode.Create))) + { + sw.Seek(length, SeekOrigin.End); sw.Write(data); sw.Flush(); } From a65c36b8d12d07a6d9e752bd6c63539a813cd9a1 Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 14:24:38 +0200 Subject: [PATCH 11/24] fix bug and more efficient code --- Server/Client.cs | 4 +--- Server/SaveData.cs | 42 +++++++++++++++++++++--------------------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/Server/Client.cs b/Server/Client.cs index 30d7efc..fc4baca 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -123,9 +123,7 @@ namespace Server Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); break; } - dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payloadbytes)); - saveData.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes)); - + saveData?.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes)); } else if (DataParser.isRawData(message)) { diff --git a/Server/SaveData.cs b/Server/SaveData.cs index be5412b..4163471 100644 --- a/Server/SaveData.cs +++ b/Server/SaveData.cs @@ -32,18 +32,36 @@ namespace Server } public void WriteDataRAWBPM(byte[] data) + { + if (data.Length != 2) + { + throw new ArgumentException("data should have length of 2"); + } + WriteRawData(data, this.path + "/rawBPM" + filename + ".bin"); + } + + public void WriteDataRAWBike(byte[] data) + { + if (data.Length != 8) + { + throw new ArgumentException("data should have length of 8"); + } + WriteRawData(data, this.path + "/rawBike" + filename + ".bin"); + } + + private void WriteRawData(byte[] data, string fileLocation) { int length = 0; try { - FileInfo fi = new FileInfo(this.path + "/rawBPM" + filename + ".bin"); + FileInfo fi = new FileInfo(fileLocation); length = (int)fi.Length; } catch { // do nothing } - using (BinaryWriter sw = new BinaryWriter(File.Open(this.path + "/rawBPM" + filename + ".bin", FileMode.Create))) + using (BinaryWriter sw = new BinaryWriter(File.Open(fileLocation, FileMode.Create))) { sw.Seek(length, SeekOrigin.End); sw.Write(data); @@ -51,24 +69,6 @@ namespace Server } } - public void WriteDataRAWBike(byte[] data) - { - int length = 0; - try - { - FileInfo fi = new FileInfo(this.path + "/rawBike" + filename + ".bin"); - length = (int)fi.Length; - } - catch - { - // do nothing - } - using (BinaryWriter sw = new BinaryWriter(File.Open(this.path + "/rawBike" + filename + ".bin", FileMode.Create))) - { - sw.Seek(length, SeekOrigin.End); - sw.Write(data); - sw.Flush(); - } - } + } } From d6b938668f18171953fd954d17051812422fc1df Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 14:33:15 +0200 Subject: [PATCH 12/24] added reconnecting to the vr server when no tunnel id is found --- Client/Client.cs | 12 ++++++++++-- Client/EngineConnection.cs | 12 ++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index e65204f..5b4c873 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -27,16 +27,24 @@ namespace Client this.client = new TcpClient(); this.connected = false; client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); - - initEngine(); } private void initEngine() { engineConnection = EngineConnection.INSTANCE; + engineConnection.OnNoTunnelId = retryEngineConnection; if (!engineConnection.Connected) engineConnection.Connect(); } + private void retryEngineConnection() + { + Console.WriteLine("Could not connect to the VR engine. Please make sure you are running the simulation!"); + Console.WriteLine("Press any key to retry connection"); + Console.ReadKey(); + + engineConnection.CreateConnection(); + } + private void OnConnect(IAsyncResult ar) { this.client.EndConnect(ar); diff --git a/Client/EngineConnection.cs b/Client/EngineConnection.cs index 965673b..8b62c10 100644 --- a/Client/EngineConnection.cs +++ b/Client/EngineConnection.cs @@ -7,20 +7,22 @@ using System.Net.Sockets; namespace Client { public delegate void HandleSerial(string message); + public delegate void HandleNoTunnelId(); public sealed class EngineConnection { private static EngineConnection instance = null; private static readonly object padlock = new object(); + public HandleNoTunnelId OnNoTunnelId; private static PC[] PCs = { //new PC("DESKTOP-M2CIH87", "Fabian"), //new PC("T470S", "Shinichi"), //new PC("DESKTOP-DHS478C", "semme"), - new PC("HP-ZBOOK-SEM", "Sem"), + new PC("HP-ZBOOK-SEM", "Sem") //new PC("DESKTOP-TV73FKO", "Wouter"), - new PC("DESKTOP-SINMKT1", "Ralf van Aert"), + //new PC("DESKTOP-SINMKT1", "Ralf van Aert"), //new PC("NA", "Bart") }; @@ -62,6 +64,7 @@ namespace Client { TcpClient client = new TcpClient("145.48.6.10", 6666); stream = client.GetStream(); + initReader(); CreateConnection(); } @@ -69,9 +72,8 @@ namespace Client /// connects to the server and creates the tunnel /// /// the network stream to use - private void CreateConnection() + public void CreateConnection() { - initReader(); WriteTextMessage( "{\r\n\"id\" : \"session/list\",\r\n\"serial\" : \"list\"\r\n}"); @@ -119,6 +121,8 @@ namespace Client if (tunnelId == null) { Write("could not find a valid tunnel id!"); + OnNoTunnelId?.Invoke(); + Connected = false; return; } } From 97f9d863aa07b7af85b11097a361d83469c76d67 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 15:10:47 +0200 Subject: [PATCH 13/24] fix --- Client/EngineConnection.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Client/EngineConnection.cs b/Client/EngineConnection.cs index 8b62c10..655e073 100644 --- a/Client/EngineConnection.cs +++ b/Client/EngineConnection.cs @@ -86,7 +86,10 @@ namespace Client // wait until we have a tunnel id while (tunnelId == string.Empty) { } - Write("got tunnel id! " + tunnelId); + if (tunnelId != null) + { + Write("got tunnel id! " + tunnelId); + } mainCommand = new Command(tunnelId); } From bd8994ad5b2db24ae1af97ef1876246c0c7a7527 Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 15:12:10 +0200 Subject: [PATCH 14/24] added start and stop session --- Client/Client.cs | 21 ++++++++++++++++++++- Client/DataParser.cs | 20 +++++++++++++++++++- Server/Client.cs | 13 ++++++++++--- Server/SaveData.cs | 10 ++++------ 4 files changed, 53 insertions(+), 11 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index e65204f..ca6b53f 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -15,6 +15,7 @@ namespace Client private byte[] totalBuffer = new byte[1024]; private int totalBufferReceived = 0; private EngineConnection engineConnection; + private bool sessionRunning = false; public Client() : this("localhost", 5555) @@ -40,7 +41,7 @@ namespace Client private void OnConnect(IAsyncResult ar) { this.client.EndConnect(ar); - Console.WriteLine("Verbonden!"); + Console.WriteLine("TCP client Verbonden!"); this.stream = this.client.GetStream(); @@ -91,6 +92,16 @@ namespace Client tryLogin(); } break; + case DataParser.START_SESSION: + this.sessionRunning = true; + byte[] startSession = DataParser.getStartSessionJson(); + stream.BeginWrite(startSession, 0, startSession.Length, new AsyncCallback(OnWrite), null); + break; + case DataParser.STOP_SESSION: + this.sessionRunning = false; + byte[] stopSession = DataParser.getStopSessionJson(); + stream.BeginWrite(stopSession, 0, stopSession.Length, new AsyncCallback(OnWrite), null); + break; default: Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); break; @@ -118,6 +129,10 @@ namespace Client //maybe move this to other place public void BPM(byte[] bytes) { + if (!sessionRunning) + { + return; + } if (bytes == null) { throw new ArgumentNullException("no bytes"); @@ -128,6 +143,10 @@ namespace Client public void Bike(byte[] bytes) { + if (!sessionRunning) + { + return; + } if (bytes == null) { throw new ArgumentNullException("no bytes"); diff --git a/Client/DataParser.cs b/Client/DataParser.cs index c83b86a..fd1c7e8 100644 --- a/Client/DataParser.cs +++ b/Client/DataParser.cs @@ -3,6 +3,7 @@ using Newtonsoft.Json.Serialization; using System; using System.Globalization; using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; using System.Text; namespace Client @@ -10,7 +11,9 @@ namespace Client public class DataParser { public const string LOGIN = "LOGIN"; - public const string LOGIN_RESPONSE = "LOGIN_RESPONSE"; + public const string LOGIN_RESPONSE = "LOGIN RESPONSE"; + public const string START_SESSION = "START SESSION"; + public const string STOP_SESSION = "STOP SESSION"; /// /// makes the json object with LOGIN identifier and username and password /// @@ -161,6 +164,21 @@ namespace Client return getJsonMessage(Encoding.ASCII.GetBytes(message)); } + public static byte[] getStartSessionJson() + { + return getJsonMessage(START_SESSION, null); + } + + public static byte[] getStopSessionJson() + { + return getJsonMessage(STOP_SESSION, null); + } + + public static byte[] getSetResistanceJson() + { + return null; + } + } } diff --git a/Server/Client.cs b/Server/Client.cs index fc4baca..1b357be 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -105,7 +105,8 @@ namespace Server this.username = username; byte[] response = DataParser.getLoginResponse("OK"); stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null); - this.saveData = new SaveData(Directory.GetCurrentDirectory() + "/" + username, sessionStart.ToString("yyyy-MM-dd HH-mm-ss")); + byte[] startSession = DataParser.getStartSessionJson(); + stream.BeginWrite(startSession, 0, startSession.Length, new AsyncCallback(OnWrite), null); } else { @@ -119,6 +120,12 @@ namespace Server stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null); } break; + case DataParser.START_SESSION: + this.saveData = new SaveData(Directory.GetCurrentDirectory() + "/" + this.username + "/" + sessionStart.ToString("yyyy-MM-dd HH-mm-ss")); + break; + case DataParser.STOP_SESSION: + this.saveData = null; + break; default: Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); break; @@ -130,11 +137,11 @@ namespace Server Console.WriteLine(BitConverter.ToString(payloadbytes)); if (payloadbytes.Length == 8) { - saveData.WriteDataRAWBike(payloadbytes); + saveData?.WriteDataRAWBike(payloadbytes); } else if (payloadbytes.Length == 2) { - saveData.WriteDataRAWBPM(payloadbytes); + saveData?.WriteDataRAWBPM(payloadbytes); } else { diff --git a/Server/SaveData.cs b/Server/SaveData.cs index 4163471..15fd0d4 100644 --- a/Server/SaveData.cs +++ b/Server/SaveData.cs @@ -8,11 +8,9 @@ namespace Server class SaveData { private string path; - private string filename; - public SaveData(string path, string filename) + public SaveData(string path) { this.path = path; - this.filename = filename; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); @@ -25,7 +23,7 @@ namespace Server public void WriteDataJSON(string data) { - using (StreamWriter sw = File.AppendText(this.path + "/json" + filename + ".txt")) + using (StreamWriter sw = File.AppendText(this.path + "/json" + ".txt")) { sw.WriteLine(data); } @@ -37,7 +35,7 @@ namespace Server { throw new ArgumentException("data should have length of 2"); } - WriteRawData(data, this.path + "/rawBPM" + filename + ".bin"); + WriteRawData(data, this.path + "/rawBPM" + ".bin"); } public void WriteDataRAWBike(byte[] data) @@ -46,7 +44,7 @@ namespace Server { throw new ArgumentException("data should have length of 8"); } - WriteRawData(data, this.path + "/rawBike" + filename + ".bin"); + WriteRawData(data, this.path + "/rawBike" + ".bin"); } private void WriteRawData(byte[] data, string fileLocation) From 599b79ceee69c3ff8701b75917547b0bf3fadaa2 Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 15:26:34 +0200 Subject: [PATCH 15/24] correctly implemented IHandler --- Client/DataParser.cs | 38 +++++++++++++++++++++-------------- ProftaakRH/BLEHandler.cs | 2 +- ProftaakRH/BikeSimulator.cs | 40 +++---------------------------------- ProftaakRH/IHandler.cs | 11 ++++++++++ 4 files changed, 38 insertions(+), 53 deletions(-) create mode 100644 ProftaakRH/IHandler.cs diff --git a/Client/DataParser.cs b/Client/DataParser.cs index fd1c7e8..5289c63 100644 --- a/Client/DataParser.cs +++ b/Client/DataParser.cs @@ -14,6 +14,7 @@ namespace Client public const string LOGIN_RESPONSE = "LOGIN RESPONSE"; public const string START_SESSION = "START SESSION"; public const string STOP_SESSION = "STOP SESSION"; + public const string SET_RESISTANCE = "SET RESISTANCE"; /// /// makes the json object with LOGIN identifier and username and password /// @@ -62,6 +63,15 @@ namespace Client return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01); } + private static byte[] getJsonMessage(string mIdentifier) + { + dynamic json = new + { + identifier = mIdentifier, + }; + return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01); + } + public static byte[] getLoginResponse(string mStatus) { return getJsonMessage(LOGIN_RESPONSE, new { status = mStatus }); @@ -153,30 +163,28 @@ namespace Client return getMessage(payload, 0x01); } - /// - /// constructs a message with the message and clientId - /// - /// - /// - /// the message ready for sending - public static byte[] getJsonMessage(string message) - { - return getJsonMessage(Encoding.ASCII.GetBytes(message)); - } - public static byte[] getStartSessionJson() { - return getJsonMessage(START_SESSION, null); + return getJsonMessage(START_SESSION); } public static byte[] getStopSessionJson() { - return getJsonMessage(STOP_SESSION, null); + return getJsonMessage(STOP_SESSION); } - public static byte[] getSetResistanceJson() + public static byte[] getSetResistanceJson(float mResistance) { - return null; + dynamic data = new + { + resistance = mResistance + }; + return getJsonMessage(SET_RESISTANCE, data); + } + + public static float getResistanceFromJson(byte[] json) + { + return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.resistance; } diff --git a/ProftaakRH/BLEHandler.cs b/ProftaakRH/BLEHandler.cs index 6baf843..56de648 100644 --- a/ProftaakRH/BLEHandler.cs +++ b/ProftaakRH/BLEHandler.cs @@ -11,7 +11,7 @@ namespace Hardware /// /// BLEHandler class that handles connection and traffic to and from the bike /// - public class BLEHandler + public class BLEHandler : IHandler { List dataReceivers; private BLE bleBike; diff --git a/ProftaakRH/BikeSimulator.cs b/ProftaakRH/BikeSimulator.cs index daea355..3d11209 100644 --- a/ProftaakRH/BikeSimulator.cs +++ b/ProftaakRH/BikeSimulator.cs @@ -98,32 +98,7 @@ namespace Hardware.Simulators return hartByte; } - //Generate an ANT message for resistance - public byte[] GenerateResistance(float percentage) - { - byte[] antMessage = new byte[13]; - antMessage[0] = 0x4A; - antMessage[1] = 0x09; - antMessage[2] = 0x4E; - antMessage[3] = 0x05; - antMessage[4] = 0x30; - for (int i = 5; i < 11; i++) - { - antMessage[i] = 0xFF; - } - antMessage[11] = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0); - //antMessage[11] = 50; //hardcoded for testing - byte checksum = 0; - for (int i = 0; i < 12; i++) - { - checksum ^= antMessage[i]; - } - - antMessage[12] = checksum;//reminder that i am dumb :P - - return antMessage; - } //Calculates the needed variables //Input perlin value @@ -143,20 +118,11 @@ namespace Hardware.Simulators } //Set resistance in simulated bike - public void setResistance(byte[] bytes) + public void setResistance(float percentage) { - //TODO check if message is correct - if (bytes.Length == 13) - { - this.resistance = Convert.ToDouble(bytes[11]) / 2; - } + this.resistance = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0); } - } - - //Interface for receiving a message on the simulated bike - interface IHandler - { - void setResistance(byte[] bytes); } + } diff --git a/ProftaakRH/IHandler.cs b/ProftaakRH/IHandler.cs new file mode 100644 index 0000000..c1ce11e --- /dev/null +++ b/ProftaakRH/IHandler.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ProftaakRH +{ + interface IHandler + { + void setResistance(float percentage); + } +} From adea08cfb7b0027eae40239c818b2b5d7d2f18c1 Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 16:22:26 +0200 Subject: [PATCH 16/24] server can set resistance --- Client/Client.cs | 16 ++++++++++++++++ Client/Program.cs | 14 +++++++++----- ProftaakRH/BLEHandler.cs | 8 ++++++++ ProftaakRH/IHandler.cs | 2 +- ProftaakRH/Main.cs | 2 +- Server/Client.cs | 18 ++++++++++-------- 6 files changed, 45 insertions(+), 15 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index ca6b53f..d52c349 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -16,6 +16,7 @@ namespace Client private int totalBufferReceived = 0; private EngineConnection engineConnection; private bool sessionRunning = false; + private IHandler handler = null; public Client() : this("localhost", 5555) @@ -102,6 +103,16 @@ namespace Client byte[] stopSession = DataParser.getStopSessionJson(); stream.BeginWrite(stopSession, 0, stopSession.Length, new AsyncCallback(OnWrite), null); break; + case DataParser.SET_RESISTANCE: + if (this.handler == null) + { + Console.WriteLine("handler is null"); + } + else + { + this.handler.setResistance(DataParser.getResistanceFromJson(payloadbytes)); + } + break; default: Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); break; @@ -174,5 +185,10 @@ namespace Client initEngine(); this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); } + + public void setHandler(IHandler handler) + { + this.handler = handler; + } } } diff --git a/Client/Program.cs b/Client/Program.cs index 9853e51..f8dd547 100644 --- a/Client/Program.cs +++ b/Client/Program.cs @@ -1,7 +1,6 @@ using System; using Hardware; using Hardware.Simulators; -using RH_Engine; namespace Client { @@ -20,13 +19,18 @@ namespace Client { } - //BLEHandler bLEHandler = new BLEHandler(client); + BLEHandler bLEHandler = new BLEHandler(client); - //bLEHandler.Connect(); + bLEHandler.Connect(); - BikeSimulator bikeSimulator = new BikeSimulator(client); + client.setHandler(bLEHandler); - bikeSimulator.StartSimulation(); + + //BikeSimulator bikeSimulator = new BikeSimulator(client); + + //bikeSimulator.StartSimulation(); + + //client.setHandler(bikeSimulator); while (true) { diff --git a/ProftaakRH/BLEHandler.cs b/ProftaakRH/BLEHandler.cs index 56de648..269b0a1 100644 --- a/ProftaakRH/BLEHandler.cs +++ b/ProftaakRH/BLEHandler.cs @@ -25,11 +25,13 @@ namespace Hardware public BLEHandler(IDataReceiver dataReceiver) { this.dataReceivers = new List { dataReceiver }; + } public BLEHandler(List dataReceivers) { this.dataReceivers = dataReceivers; + } public void addDataReceiver(IDataReceiver dataReceiver) @@ -43,6 +45,7 @@ namespace Hardware public void Connect() { BLE bleBike = new BLE(); + Thread.Sleep(1000); // We need some time to list available devices // List available devices @@ -170,6 +173,11 @@ namespace Hardware /// The precentage of resistance to set public void setResistance(float percentage) { + if (!this.Running) + { + Console.WriteLine("BLE is not running"); + return; + } byte[] antMessage = new byte[13]; antMessage[0] = 0x4A; antMessage[1] = 0x09; diff --git a/ProftaakRH/IHandler.cs b/ProftaakRH/IHandler.cs index c1ce11e..4f52042 100644 --- a/ProftaakRH/IHandler.cs +++ b/ProftaakRH/IHandler.cs @@ -4,7 +4,7 @@ using System.Text; namespace ProftaakRH { - interface IHandler + public interface IHandler { void setResistance(float percentage); } diff --git a/ProftaakRH/Main.cs b/ProftaakRH/Main.cs index 5ffcab4..41780f0 100644 --- a/ProftaakRH/Main.cs +++ b/ProftaakRH/Main.cs @@ -14,7 +14,7 @@ namespace ProftaakRH IDataReceiver dataReceiver = new DataConverter(); BLEHandler bLEHandler = new BLEHandler(dataReceiver); BikeSimulator bikeSimulator = new BikeSimulator(dataReceiver); - bikeSimulator.setResistance(bikeSimulator.GenerateResistance(1f)); + bikeSimulator.setResistance(1); bikeSimulator.StartSimulation(); diff --git a/Server/Client.cs b/Server/Client.cs index 1b357be..d486793 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -103,21 +103,17 @@ namespace Server { Console.WriteLine("Log in"); this.username = username; - byte[] response = DataParser.getLoginResponse("OK"); - stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null); - byte[] startSession = DataParser.getStartSessionJson(); - stream.BeginWrite(startSession, 0, startSession.Length, new AsyncCallback(OnWrite), null); + sendMessage(DataParser.getLoginResponse("OK")); + sendMessage(DataParser.getStartSessionJson()); } else { - byte[] response = DataParser.getLoginResponse("wrong username or password"); - stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null); + sendMessage(DataParser.getLoginResponse("wrong username or password")); } } else { - byte[] response = DataParser.getLoginResponse("invalid json"); - stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null); + sendMessage(DataParser.getLoginResponse("invalid json")); } break; case DataParser.START_SESSION: @@ -142,6 +138,7 @@ namespace Server else if (payloadbytes.Length == 2) { saveData?.WriteDataRAWBPM(payloadbytes); + sendMessage(DataParser.getSetResistanceJson(50)); } else { @@ -152,6 +149,11 @@ namespace Server } + private void sendMessage(byte[] message) + { + stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + private bool verifyLogin(string username, string password) { return username == password; From 3e5f6e46c4076bad28c797d79fbc23859eb3e742 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 30 Sep 2020 16:22:57 +0200 Subject: [PATCH 17/24] progress on validation --- Client/Client.cs | 6 ++++- Client/Client.csproj | 2 ++ Client/Program.cs | 3 ++- Hashing/Hasher.cs | 51 +++++++++++++++++++++++++++++++++++++++ Hashing/Hashing.projitems | 14 +++++++++++ Hashing/Hashing.shproj | 13 ++++++++++ ProftaakRH/ProftaakRH.sln | 7 ++++++ Server/Client.cs | 44 ++++++++++++++++++++++++++++++++- Server/Server.csproj | 2 ++ 9 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 Hashing/Hasher.cs create mode 100644 Hashing/Hashing.projitems create mode 100644 Hashing/Hashing.shproj diff --git a/Client/Client.cs b/Client/Client.cs index 5b4c873..d718b1f 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -158,7 +158,11 @@ namespace Client Console.WriteLine("enter password"); string password = Console.ReadLine(); - byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(username, password)); + string hashUser = Hashing.Hasher.Encrypt(username); + string hashPassword = Hashing.Hasher.Encrypt(password); + Console.WriteLine("hashed to " + hashUser + " " + hashPassword); + + byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword)); initEngine(); this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); diff --git a/Client/Client.csproj b/Client/Client.csproj index 4ade6d5..6aa0290 100644 --- a/Client/Client.csproj +++ b/Client/Client.csproj @@ -15,4 +15,6 @@ + + diff --git a/Client/Program.cs b/Client/Program.cs index 9853e51..331d8a6 100644 --- a/Client/Program.cs +++ b/Client/Program.cs @@ -2,6 +2,8 @@ using Hardware; using Hardware.Simulators; using RH_Engine; +using System.Security.Cryptography; +using System.Text; namespace Client { @@ -12,7 +14,6 @@ namespace Client Console.WriteLine("Hello World!"); //connect fiets? - Client client = new Client(); diff --git a/Hashing/Hasher.cs b/Hashing/Hasher.cs new file mode 100644 index 0000000..aaea498 --- /dev/null +++ b/Hashing/Hasher.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using System.Text; + +namespace Hashing +{ + class Hasher + { + static string key = "ProftaakRH-B4"; + public static string Encrypt(string text) + { + using (var md5 = new MD5CryptoServiceProvider()) + { + using (var tdes = new TripleDESCryptoServiceProvider()) + { + tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); + tdes.Mode = CipherMode.ECB; + tdes.Padding = PaddingMode.PKCS7; + + using (var transform = tdes.CreateEncryptor()) + { + byte[] textBytes = UTF8Encoding.UTF8.GetBytes(text); + byte[] bytes = transform.TransformFinalBlock(textBytes, 0, textBytes.Length); + return Convert.ToBase64String(bytes, 0, bytes.Length); + } + } + } + } + + public static string Decrypt(string cipher) + { + using (var md5 = new MD5CryptoServiceProvider()) + { + using (var tdes = new TripleDESCryptoServiceProvider()) + { + tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); + tdes.Mode = CipherMode.ECB; + tdes.Padding = PaddingMode.PKCS7; + + using (var transform = tdes.CreateDecryptor()) + { + byte[] cipherBytes = Convert.FromBase64String(cipher); + byte[] bytes = transform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length); + return UTF8Encoding.UTF8.GetString(bytes); + } + } + } + } + } +} diff --git a/Hashing/Hashing.projitems b/Hashing/Hashing.projitems new file mode 100644 index 0000000..127b36a --- /dev/null +++ b/Hashing/Hashing.projitems @@ -0,0 +1,14 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 70277749-d423-4871-b692-2efc5a6ed932 + + + Hashing + + + + + \ No newline at end of file diff --git a/Hashing/Hashing.shproj b/Hashing/Hashing.shproj new file mode 100644 index 0000000..e427bd6 --- /dev/null +++ b/Hashing/Hashing.shproj @@ -0,0 +1,13 @@ + + + + 70277749-d423-4871-b692-2efc5a6ed932 + 14.0 + + + + + + + + diff --git a/ProftaakRH/ProftaakRH.sln b/ProftaakRH/ProftaakRH.sln index f2df07f..42a23ed 100644 --- a/ProftaakRH/ProftaakRH.sln +++ b/ProftaakRH/ProftaakRH.sln @@ -15,7 +15,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Message", "..\Message\Messa EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DokterApp", "..\DokterApp\DokterApp.csproj", "{B150F08B-13DA-4D17-BD96-7E89F52727C6}" EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Hashing", "..\Hashing\Hashing.shproj", "{70277749-D423-4871-B692-2EFC5A6ED932}" +EndProject Global + GlobalSection(SharedMSBuildProjectFiles) = preSolution + ..\Hashing\Hashing.projitems*{5759dd20-7a4f-4d8d-b986-a70a7818c112}*SharedItemsImports = 5 + ..\Hashing\Hashing.projitems*{70277749-d423-4871-b692-2efc5a6ed932}*SharedItemsImports = 13 + ..\Hashing\Hashing.projitems*{b1ab6f51-a20d-4162-9a7f-b3350b7510fd}*SharedItemsImports = 5 + EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU diff --git a/Server/Client.cs b/Server/Client.cs index 5e385be..46b2025 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -5,6 +5,7 @@ using System.Net.Sockets; using System.Text; using Client; using Newtonsoft.Json; +using System.Security.Cryptography; namespace Server { @@ -19,6 +20,7 @@ namespace Server private SaveData saveData; private string username = null; private DateTime sessionStart; + private const string fileName = "userInfo.dat"; @@ -125,6 +127,7 @@ namespace Server } Array.Copy(message, 5, payloadbytes, 0, message.Length - 5); dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payloadbytes)); + saveData.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes)); } @@ -139,9 +142,48 @@ namespace Server private bool verifyLogin(string username, string password) { - return username == password; + Console.WriteLine("got hashes " + username + password); + Console.WriteLine(Hashing.Hasher.Decrypt(username) + " " + Hashing.Hasher.Decrypt(password)); + + if (!File.Exists(fileName)) + { + Console.WriteLine("file doesnt exist"); + + Console.WriteLine("true"); + return true; + } else + { + string[] usernamesPasswords = File.ReadAllLines(fileName); + + foreach (string s in usernamesPasswords) + { + string[] combo = s.Split(";"); + if (combo[0] == username) + { + Console.WriteLine("true"); + return combo[1] == password; + } + } + + } + Console.WriteLine("false"); + return false; + } + private void newUsers(string username, string password) + { + File.Create(fileName); + using (StreamWriter sw = File.AppendText(fileName)) + { + sw.WriteLine(username + ";" + password); + } + } + + + + + public static string ByteArrayToString(byte[] ba) { StringBuilder hex = new StringBuilder(ba.Length * 2); diff --git a/Server/Server.csproj b/Server/Server.csproj index a91c176..cd7c7da 100644 --- a/Server/Server.csproj +++ b/Server/Server.csproj @@ -13,4 +13,6 @@ + + From a5e679e6fbb0a3d379f29e06d350d6656b71d957 Mon Sep 17 00:00:00 2001 From: shinichi Date: Wed, 30 Sep 2020 19:40:37 +0200 Subject: [PATCH 18/24] server now gets response when resistance is set --- Client/Client.cs | 13 +++++++++---- Client/DataParser.cs | 14 ++++++++++++++ Server/Client.cs | 6 +++++- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index d52c349..c6f6f48 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -95,22 +95,22 @@ namespace Client break; case DataParser.START_SESSION: this.sessionRunning = true; - byte[] startSession = DataParser.getStartSessionJson(); - stream.BeginWrite(startSession, 0, startSession.Length, new AsyncCallback(OnWrite), null); + sendMessage(DataParser.getStartSessionJson()); break; case DataParser.STOP_SESSION: this.sessionRunning = false; - byte[] stopSession = DataParser.getStopSessionJson(); - stream.BeginWrite(stopSession, 0, stopSession.Length, new AsyncCallback(OnWrite), null); + sendMessage(DataParser.getStopSessionJson()); break; case DataParser.SET_RESISTANCE: if (this.handler == null) { Console.WriteLine("handler is null"); + sendMessage(DataParser.getSetResistanceResponseJson(false)); } else { this.handler.setResistance(DataParser.getResistanceFromJson(payloadbytes)); + sendMessage(DataParser.getSetResistanceResponseJson(true)); } break; default: @@ -131,6 +131,11 @@ namespace Client } + private void sendMessage(byte[] message) + { + stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + private void OnWrite(IAsyncResult ar) { this.stream.EndWrite(ar); diff --git a/Client/DataParser.cs b/Client/DataParser.cs index 5289c63..8eddb4c 100644 --- a/Client/DataParser.cs +++ b/Client/DataParser.cs @@ -182,11 +182,25 @@ namespace Client return getJsonMessage(SET_RESISTANCE, data); } + public static byte[] getSetResistanceResponseJson(bool mWorked) + { + dynamic data = new + { + worked = mWorked + }; + return getJsonMessage(SET_RESISTANCE, data); + } + public static float getResistanceFromJson(byte[] json) { return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.resistance; } + public static bool getResistanceFromResponseJson(byte[] json) + { + return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.worked; + } + } } diff --git a/Server/Client.cs b/Server/Client.cs index d486793..02abad4 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -122,6 +122,11 @@ namespace Server case DataParser.STOP_SESSION: this.saveData = null; break; + case DataParser.SET_RESISTANCE: + worked = DataParser.getResistanceFromResponseJson(payloadbytes); + Console.WriteLine($"set resistance worked is " + worked); + //set resistance on doctor GUI + break; default: Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); break; @@ -138,7 +143,6 @@ namespace Server else if (payloadbytes.Length == 2) { saveData?.WriteDataRAWBPM(payloadbytes); - sendMessage(DataParser.getSetResistanceJson(50)); } else { From fedf8c0e5b7d2c2b50d68fdc8add311f6eba90fa Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Fri, 2 Oct 2020 11:43:07 +0200 Subject: [PATCH 19/24] added client server login with hashed passwords and usernames --- Client/Client.cs | 12 ++++++------ Client/EngineConnection.cs | 2 +- Hashing/Hasher.cs | 40 ++++++++------------------------------ Server/Client.cs | 26 +++++++++++++++++-------- 4 files changed, 33 insertions(+), 47 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index d718b1f..16d24ad 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -38,8 +38,8 @@ namespace Client private void retryEngineConnection() { - Console.WriteLine("Could not connect to the VR engine. Please make sure you are running the simulation!"); - Console.WriteLine("Press any key to retry connection"); + Console.WriteLine("-- Could not connect to the VR engine. Please make sure you are running the simulation!"); + Console.WriteLine("-- Press any key to retry connecting to the VR engine."); Console.ReadKey(); engineConnection.CreateConnection(); @@ -92,6 +92,7 @@ namespace Client if (responseStatus == "OK") { this.connected = true; + initEngine(); } else { @@ -158,13 +159,12 @@ namespace Client Console.WriteLine("enter password"); string password = Console.ReadLine(); - string hashUser = Hashing.Hasher.Encrypt(username); - string hashPassword = Hashing.Hasher.Encrypt(password); - Console.WriteLine("hashed to " + hashUser + " " + hashPassword); + string hashUser = Hashing.Hasher.HashString(username); + string hashPassword = Hashing.Hasher.HashString(password); byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword)); - initEngine(); + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); } } diff --git a/Client/EngineConnection.cs b/Client/EngineConnection.cs index 655e073..4905911 100644 --- a/Client/EngineConnection.cs +++ b/Client/EngineConnection.cs @@ -167,7 +167,7 @@ namespace Client stream.Write(res); - Write("sent message " + message); + //Write("sent message " + message); } public void Write(string msg) { diff --git a/Hashing/Hasher.cs b/Hashing/Hasher.cs index aaea498..270faa3 100644 --- a/Hashing/Hasher.cs +++ b/Hashing/Hasher.cs @@ -7,45 +7,21 @@ namespace Hashing { class Hasher { - static string key = "ProftaakRH-B4"; - public static string Encrypt(string text) + public static byte[] GetHash(string input) { - using (var md5 = new MD5CryptoServiceProvider()) + using (HashAlgorithm algorithm = SHA256.Create()) { - using (var tdes = new TripleDESCryptoServiceProvider()) - { - tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); - tdes.Mode = CipherMode.ECB; - tdes.Padding = PaddingMode.PKCS7; - - using (var transform = tdes.CreateEncryptor()) - { - byte[] textBytes = UTF8Encoding.UTF8.GetBytes(text); - byte[] bytes = transform.TransformFinalBlock(textBytes, 0, textBytes.Length); - return Convert.ToBase64String(bytes, 0, bytes.Length); - } - } + return algorithm.ComputeHash(Encoding.UTF8.GetBytes(input)); } } - public static string Decrypt(string cipher) + public static string HashString(string input) { - using (var md5 = new MD5CryptoServiceProvider()) - { - using (var tdes = new TripleDESCryptoServiceProvider()) - { - tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); - tdes.Mode = CipherMode.ECB; - tdes.Padding = PaddingMode.PKCS7; - - using (var transform = tdes.CreateDecryptor()) - { - byte[] cipherBytes = Convert.FromBase64String(cipher); - byte[] bytes = transform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length); - return UTF8Encoding.UTF8.GetString(bytes); - } - } + StringBuilder sb = new StringBuilder(); + foreach (byte b in GetHash(input)) { + sb.Append(b.ToString("X2")); } + return sb.ToString(); } } } diff --git a/Server/Client.cs b/Server/Client.cs index 46b2025..79697b7 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -128,7 +128,7 @@ namespace Server Array.Copy(message, 5, payloadbytes, 0, message.Length - 5); dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payloadbytes)); - saveData.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes)); + //saveData.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes)); } else if (DataParser.isRawData(message)) @@ -142,28 +142,37 @@ namespace Server private bool verifyLogin(string username, string password) { - Console.WriteLine("got hashes " + username + password); - Console.WriteLine(Hashing.Hasher.Decrypt(username) + " " + Hashing.Hasher.Decrypt(password)); + Console.WriteLine("got hashes " + username + "\n" + password); + if (!File.Exists(fileName)) { + File.Create(fileName); Console.WriteLine("file doesnt exist"); - + newUsers(username, password); Console.WriteLine("true"); return true; } else { + Console.WriteLine("file exists, located at " + Path.GetFullPath(fileName)); string[] usernamesPasswords = File.ReadAllLines(fileName); + if (usernamesPasswords.Length == 0) + { + newUsers(username, password); + return true; + } foreach (string s in usernamesPasswords) { - string[] combo = s.Split(";"); + string[] combo = s.Split(" "); if (combo[0] == username) { - Console.WriteLine("true"); + Console.WriteLine("correct info"); return combo[1] == password; } + } + Console.WriteLine("combo was not found in file"); } Console.WriteLine("false"); @@ -173,10 +182,11 @@ namespace Server private void newUsers(string username, string password) { - File.Create(fileName); + + Console.WriteLine("creating new entry in file"); using (StreamWriter sw = File.AppendText(fileName)) { - sw.WriteLine(username + ";" + password); + sw.WriteLine(username + " " + password); } } From 32ef17365e66858dcfd7ea209fef942d2ff2c4d4 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Fri, 2 Oct 2020 11:44:26 +0200 Subject: [PATCH 20/24] pull --- Client/Client.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index e65204f..16d24ad 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -27,16 +27,24 @@ namespace Client this.client = new TcpClient(); this.connected = false; client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); - - initEngine(); } private void initEngine() { engineConnection = EngineConnection.INSTANCE; + engineConnection.OnNoTunnelId = retryEngineConnection; if (!engineConnection.Connected) engineConnection.Connect(); } + private void retryEngineConnection() + { + Console.WriteLine("-- Could not connect to the VR engine. Please make sure you are running the simulation!"); + Console.WriteLine("-- Press any key to retry connecting to the VR engine."); + Console.ReadKey(); + + engineConnection.CreateConnection(); + } + private void OnConnect(IAsyncResult ar) { this.client.EndConnect(ar); @@ -84,6 +92,7 @@ namespace Client if (responseStatus == "OK") { this.connected = true; + initEngine(); } else { @@ -150,9 +159,12 @@ namespace Client Console.WriteLine("enter password"); string password = Console.ReadLine(); - byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(username, password)); + string hashUser = Hashing.Hasher.HashString(username); + string hashPassword = Hashing.Hasher.HashString(password); - initEngine(); + byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword)); + + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); } } From cb2435bf53cd88f819e24f8e2f9f773b267c92e5 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Fri, 2 Oct 2020 11:48:03 +0200 Subject: [PATCH 21/24] weird fix --- ProftaakRH/ProftaakRH.sln | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProftaakRH/ProftaakRH.sln b/ProftaakRH/ProftaakRH.sln index 42a23ed..f05bff3 100644 --- a/ProftaakRH/ProftaakRH.sln +++ b/ProftaakRH/ProftaakRH.sln @@ -13,7 +13,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "..\Client\Client. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Message", "..\Message\Message.csproj", "{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DokterApp", "..\DokterApp\DokterApp.csproj", "{B150F08B-13DA-4D17-BD96-7E89F52727C6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DokterApp", "..\DokterApp\DokterApp.csproj", "{B150F08B-13DA-4D17-BD96-7E89F52727C6}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Hashing", "..\Hashing\Hashing.shproj", "{70277749-D423-4871-B692-2EFC5A6ED932}" EndProject From d85c5ff935935fc662c91a995ca0f95ce21aaf1a Mon Sep 17 00:00:00 2001 From: shinichi Date: Fri, 2 Oct 2020 15:37:57 +0200 Subject: [PATCH 22/24] added function to get BPM graph data --- Server/SaveData.cs | 60 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/Server/SaveData.cs b/Server/SaveData.cs index 15fd0d4..bcabb1f 100644 --- a/Server/SaveData.cs +++ b/Server/SaveData.cs @@ -2,12 +2,16 @@ using System.Collections.Generic; using System.IO; using System.Text; +using System.Threading; namespace Server { class SaveData { private string path; + private const string jsonFilename = "/json.txt"; + private const string rawBikeFilename = "/rawBike.bin"; + private const string rawBPMFilename = "/rawBPM.bin"; public SaveData(string path) { this.path = path; @@ -23,7 +27,7 @@ namespace Server public void WriteDataJSON(string data) { - using (StreamWriter sw = File.AppendText(this.path + "/json" + ".txt")) + using (StreamWriter sw = File.AppendText(this.path + jsonFilename)) { sw.WriteLine(data); } @@ -35,7 +39,7 @@ namespace Server { throw new ArgumentException("data should have length of 2"); } - WriteRawData(data, this.path + "/rawBPM" + ".bin"); + WriteRawData(data, this.path + rawBPMFilename); } public void WriteDataRAWBike(byte[] data) @@ -44,7 +48,7 @@ namespace Server { throw new ArgumentException("data should have length of 8"); } - WriteRawData(data, this.path + "/rawBike" + ".bin"); + WriteRawData(data, this.path + rawBikeFilename); } private void WriteRawData(byte[] data, string fileLocation) @@ -67,6 +71,56 @@ namespace Server } } + /// + /// gets BPM graph data out of file. + /// if you want 100 datapoints but here are onlny 50, de last 50 datapoint will be 0 + /// if you want 100 datapoints where it takes the average of 2, the last 75 will be 0 + /// if the file isn't created yet it will retun null + /// + /// the amount of data points for the output + /// the amount of data points form the file for one data point in the output + /// byte array with data points from file + public byte[] getBPMgraphData(int outputSize, int averageOver) + { + if (File.Exists(this.path + rawBPMFilename)) + { + FileInfo fi = new FileInfo(this.path + rawBPMFilename); + int length = (int)fi.Length; + + byte[] output = new byte[outputSize]; + + int messageSize = 2; + int readSize = messageSize * averageOver; + byte[] readBuffer = new byte[readSize]; + + using (FileStream fileStream = new FileStream(this.path + rawBPMFilename, FileMode.Open, FileAccess.Read)) + { + for (int i = 1; i >= outputSize; i++) + { + if (length - (i * readSize) < 0) + { + break; + } + fileStream.Read(readBuffer, length - (i * readSize), readSize); + + //handling data + int total = 0; + for (int j = 0; j < averageOver; j++) + { + total += readBuffer[j * messageSize + 1]; + } + output[i - 1] = (byte)(total / averageOver); + } + } + + return output; + } + else + { + return null; + } + } + } } From 09db19246e0d88828b74a37f693d639aa947091d Mon Sep 17 00:00:00 2001 From: shinichi Date: Fri, 2 Oct 2020 15:53:50 +0200 Subject: [PATCH 23/24] quick fix --- Server/Client.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Server/Client.cs b/Server/Client.cs index 6219992..0151e87 100644 --- a/Server/Client.cs +++ b/Server/Client.cs @@ -20,7 +20,7 @@ namespace Server private SaveData saveData; private string username = null; private DateTime sessionStart; - private const string fileName = "userInfo.dat"; + private string fileName; @@ -32,6 +32,7 @@ namespace Server this.communication = communication; this.tcpClient = tcpClient; this.stream = this.tcpClient.GetStream(); + this.fileName = Directory.GetCurrentDirectory() + "/userInfo.dat"; stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); } @@ -137,7 +138,7 @@ namespace Server Array.Copy(message, 5, payloadbytes, 0, message.Length - 5); dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payloadbytes)); - + } else if (DataParser.isRawData(message)) { @@ -167,8 +168,8 @@ namespace Server private bool verifyLogin(string username, string password) { Console.WriteLine("got hashes " + username + "\n" + password); - - + + if (!File.Exists(fileName)) { File.Create(fileName); @@ -176,7 +177,8 @@ namespace Server newUsers(username, password); Console.WriteLine("true"); return true; - } else + } + else { Console.WriteLine("file exists, located at " + Path.GetFullPath(fileName)); string[] usernamesPasswords = File.ReadAllLines(fileName); @@ -206,7 +208,7 @@ namespace Server private void newUsers(string username, string password) { - + Console.WriteLine("creating new entry in file"); using (StreamWriter sw = File.AppendText(fileName)) { @@ -216,7 +218,7 @@ namespace Server - + public static string ByteArrayToString(byte[] ba) { From e4d192fb06093dedb9e73c0decac772a737f94cc Mon Sep 17 00:00:00 2001 From: Logophilist Date: Mon, 5 Oct 2020 20:20:57 +0200 Subject: [PATCH 24/24] Commit alt code of VR engine --- RH-Engine/Command.cs | 26 +++--- RH-Engine/JSONParser.cs | 20 ++++ RH-Engine/Program.cs | 112 ++++++++++++++++++++--- RH-Engine/Properties/launchSettings.json | 8 ++ 4 files changed, 143 insertions(+), 23 deletions(-) create mode 100644 RH-Engine/Properties/launchSettings.json diff --git a/RH-Engine/Command.cs b/RH-Engine/Command.cs index 3ef3bc1..ea464c3 100644 --- a/RH-Engine/Command.cs +++ b/RH-Engine/Command.cs @@ -83,11 +83,12 @@ namespace RH_Engine return JsonConvert.SerializeObject(Payload(payload)); } - public string DeleteNode(string uuid) + public string DeleteNode(string uuid, string serialCode) { dynamic payload = new { id = "scene/node/delete", + serial = serialCode, data = new { id = uuid, @@ -105,14 +106,13 @@ namespace RH_Engine data = new { name = "dashboard", - parent = uuidBike, components = new { panel = new { size = new int[] { 1, 1 }, resolution = new int[] { 512, 512 }, - background = new int[] { 1, 0, 0, 0 }, + background = new int[] { 1, 1, 1, 1 }, castShadow = false } } @@ -151,17 +151,18 @@ namespace RH_Engine return JsonConvert.SerializeObject(Payload(payload)); } - public string bikeSpeed(string uuidPanel, double speed) + public string bikeSpeed(string uuidPanel, string serialCode, double speed) { dynamic payload = new { id = "scene/panel/drawtext", + serial = serialCode, data = new { id = uuidPanel, - text = "Bike speed placeholder", - position = new int[] { 0, 0 }, - size = 32.0, + text = "Speed: " + speed.ToString(), + position = new int[] { 4, 24 }, + size = 36.0, color = new int[] { 0, 0, 0, 1 }, font = "segoeui" } @@ -250,16 +251,17 @@ namespace RH_Engine return JsonConvert.SerializeObject(Payload(payload)); } - public string MoveTo(string uuid, float[] positionVector, float rotateValue, float speedValue, float timeValue) + public string MoveTo(string uuid, string serial, float[] positionVector, string rotateValue, int speedValue, int timeValue) { - return MoveTo(uuid, "idk", positionVector, rotateValue, "linear", false, speedValue, timeValue); + return MoveTo(uuid, serial, "stop", positionVector, rotateValue, "linear", false, speedValue, timeValue); } - private string MoveTo(string uuid, string stopValue, float[] positionVector, float rotateValue, string interpolateValue, bool followHeightValue, float speedValue, float timeValue) + private string MoveTo(string uuid, string serialCode, string stopValue, float[] positionVector, string rotateValue, string interpolateValue, bool followHeightValue, int speedValue, int timeValue) { dynamic payload = new { id = "scene/node/moveto", + serial = serialCode, data = new { id = uuid, @@ -319,7 +321,7 @@ namespace RH_Engine } } }; - Console.WriteLine("route command: " + JsonConvert.SerializeObject(Payload(payload))); + //Console.WriteLine("route command: " + JsonConvert.SerializeObject(Payload(payload))); return JsonConvert.SerializeObject(Payload(payload)); } @@ -350,7 +352,7 @@ namespace RH_Engine { return RouteFollow(routeID, nodeID, speedValue, 0, "XYZ", 1, true, new float[] { 0, 0, 0 }, positionOffsetVector); } - private string RouteFollow(string routeID, string nodeID, float speedValue, float offsetValue, string rotateValue, float smoothingValue, bool followHeightValue, float[] rotateOffsetVector, float[] positionOffsetVector) + public string RouteFollow(string routeID, string nodeID, float speedValue, float offsetValue, string rotateValue, float smoothingValue, bool followHeightValue, float[] rotateOffsetVector, float[] positionOffsetVector) { dynamic payload = new { diff --git a/RH-Engine/JSONParser.cs b/RH-Engine/JSONParser.cs index 8621aff..f3541be 100644 --- a/RH-Engine/JSONParser.cs +++ b/RH-Engine/JSONParser.cs @@ -25,6 +25,20 @@ namespace RH_Engine return res; } + public static string GetIdSceneInfoChild(string msg, string nodeName) + { + dynamic jsonData = JsonConvert.DeserializeObject(msg); + Newtonsoft.Json.Linq.JArray children = jsonData.data.data.data.children; + foreach (dynamic d in children) + { + if (d.name == nodeName) + { + return d.uuid; + } + } + return null; + } + public static string GetSessionID(string msg, PC[] PCs) { dynamic jsonData = JsonConvert.DeserializeObject(msg); @@ -45,6 +59,12 @@ namespace RH_Engine return null; } + public static bool GetStatus(string json) + { + dynamic jsonData = JsonConvert.DeserializeObject(json); + return jsonData.data.data.status == "ok"; + } + public static string GetSerial(string json) { dynamic jsonData = JsonConvert.DeserializeObject(json); diff --git a/RH-Engine/Program.cs b/RH-Engine/Program.cs index 63c86fb..3b3bf93 100644 --- a/RH-Engine/Program.cs +++ b/RH-Engine/Program.cs @@ -1,4 +1,5 @@ using LibNoise.Primitive; +using Microsoft.VisualBasic.FileIO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; @@ -16,7 +17,7 @@ namespace RH_Engine //new PC("DESKTOP-M2CIH87", "Fabian"), //new PC("T470S", "Shinichi"), //new PC("DESKTOP-DHS478C", "semme"), - new PC("HP-ZBOOK-SEM", "Sem"), + //new PC("HP-ZBOOK-SEM", "Sem"), //new PC("DESKTOP-TV73FKO", "Wouter"), new PC("DESKTOP-SINMKT1", "Ralf van Aert"), //new PC("NA", "Bart") @@ -25,9 +26,11 @@ namespace RH_Engine private static ServerResponseReader serverResponseReader; private static string sessionId = string.Empty; private static string tunnelId = string.Empty; + private static string cameraId = string.Empty; private static string routeId = string.Empty; private static string panelId = string.Empty; private static string bikeId = string.Empty; + private static string headId = string.Empty; private static Dictionary serialResponses = new Dictionary(); @@ -55,6 +58,7 @@ namespace RH_Engine /// the response message from the server public static void HandleResponse(string message) { + //Console.WriteLine(message); string id = JSONParser.GetID(message); // because the first messages don't have a serial, we need to check on the id @@ -109,7 +113,7 @@ namespace RH_Engine stream.Write(res); - Console.WriteLine("sent message " + message); + //Console.WriteLine("sent message " + message); } /// @@ -144,23 +148,85 @@ namespace RH_Engine { Command mainCommand = new Command(tunnelID); + // Reset scene WriteTextMessage(stream, mainCommand.ResetScene()); + //headId = GetId("Root", stream, mainCommand); + //while (headId == string.Empty) { } + + //Get sceneinfo + SendMessageAndOnResponse(stream, mainCommand.GetSceneInfoCommand("sceneinfo"), "sceneinfo", + (message) => + { + //Console.WriteLine("\r\n\r\n\r\nscene info" + message); + cameraId = JSONParser.GetIdSceneInfoChild(message, "Camera"); + string headId = JSONParser.GetIdSceneInfoChild(message, "Head"); + string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand"); + string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand"); + + //Force(stream, mainCommand.DeleteNode(handLeftId, "deleteHandL"), "deleteHandL", (message) => Console.WriteLine("Left hand deleted")); + //Force(stream, mainCommand.DeleteNode(handRightId, "deleteHandR"), "deleteHandR", (message) => Console.WriteLine("Right hand deleted")); + }); + + //Add route, bike and put camera and bike to follow route at same speed. SendMessageAndOnResponse(stream, mainCommand.RouteCommand("routeID"), "routeID", (message) => routeId = JSONParser.GetResponseUuid(message)); + SendMessageAndOnResponse(stream, mainCommand.AddBikeModel("bikeID"), "bikeID", + (message) => + { + bikeId = JSONParser.GetResponseUuid(message); + SendMessageAndOnResponse(stream, mainCommand.addPanel("panelAdd", bikeId), "panelAdd", + (message) => + { + bool speedReplied = false; + bool moveReplied = true; + panelId = JSONParser.getPanelID(message); + WriteTextMessage(stream, mainCommand.ClearPanel(panelId)); + + + SendMessageAndOnResponse(stream, mainCommand.MoveTo(panelId, "panelMove", new float[] { 0f, 0f, 0f }, "Z", 1, 5), "panelMove", + (message) => + { + Console.WriteLine(message); + SendMessageAndOnResponse(stream, mainCommand.bikeSpeed(panelId, "bikeSpeed", 5.0), "bikeSpeed", + (message) => + { + WriteTextMessage(stream, mainCommand.SwapPanel(panelId)); + }); + }); + + + //while (!(speedReplied && moveReplied)) { } + + while (cameraId == string.Empty) { } + SetFollowSpeed(5.0f, stream, mainCommand); + }); + }); + + //Force(stream, mainCommand.addPanel("panelID", bikeId), "panelID", + // (message) => + // { + // Console.WriteLine("panel response: " + message); + // panelId = JSONParser.GetResponseUuid(message); + // while(bikeId == string.Empty) { } + // SetFollowSpeed(5.0f, stream, mainCommand); + // }); + //SendMessageAndOnResponse(stream, maincommand.addpanel("panelid", bikeid), "panelid", + // (message) => + // { + // console.writeline("panelid: " + message); + // //panelid = jsonparser.getpanelid(message); + // panelid = jsonparser.getresponseuuid(message); + // while (bikeid == string.empty) { } + // setfollowspeed(5.0f, stream, maincommand); + // }); + + //WriteTextMessage(stream, mainCommand.TerrainCommand(new int[] { 256, 256 }, null)); //string command; - SendMessageAndOnResponse(stream, mainCommand.AddBikeModel("bikeID"), "bikeID", (message) => bikeId = JSONParser.GetResponseUuid(message)); - SendMessageAndOnResponse(stream, mainCommand.addPanel("panelID", bikeId), "panelID", - (message) => - { - panelId = JSONParser.GetResponseUuid(message); - while (bikeId == string.Empty) { } - WriteTextMessage(stream, mainCommand.RouteFollow(routeId, bikeId, 5, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 })); - }); - Console.WriteLine("id of head " + GetId(Command.STANDARD_HEAD, stream, mainCommand)); + //Console.WriteLine("id of head " + GetId(Command.STANDARD_HEAD, stream, mainCommand)); //command = mainCommand.AddModel("car", "data\\customModels\\TeslaRoadster.fbx"); //WriteTextMessage(stream, command); @@ -255,6 +321,30 @@ namespace RH_Engine return res; } + + private static void SetFollowSpeed(float speed, NetworkStream stream, Command mainCommand) + { + WriteTextMessage(stream, mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 })); + WriteTextMessage(stream, mainCommand.RouteFollow(routeId, cameraId, speed)); + WriteTextMessage(stream, mainCommand.RouteFollow(routeId, panelId, speed, 0, "XYZ", 1, false, new float[] { 0, 0, 0 }, new float[] { 0f, 0f, 150f })); + } + //string routeID, string nodeID, float speedValue, float offsetValue, string rotateValue, float smoothingValue, bool followHeightValue, float[] rotateOffsetVector, float[] positionOffsetVector) + private static void Force(NetworkStream stream, string message, string serial, HandleSerial action) + { + SendMessageAndOnResponse(stream, message, serial, + (message) => + { + if (!JSONParser.GetStatus(message)) + { + serialResponses.Remove(serial); + Force(stream, message, serial,action); + } else + { + action(message); + } + } + ); + } } /// diff --git a/RH-Engine/Properties/launchSettings.json b/RH-Engine/Properties/launchSettings.json new file mode 100644 index 0000000..cb21041 --- /dev/null +++ b/RH-Engine/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "RH-Engine": { + "commandName": "Project", + "nativeDebugging": true + } + } +} \ No newline at end of file