From aea1b4fce4807c9ccc6d69a3a529b8095c88c30a Mon Sep 17 00:00:00 2001 From: fabjuuuh Date: Wed, 7 Oct 2020 13:21:30 +0200 Subject: [PATCH] connectie met server --- Client/Client.cs | 15 ++- DokterApp/Client.cs | 201 ++++++++++++++++++++++++++++++++++ DokterApp/DataParser.cs | 206 +++++++++++++++++++++++++++++++++++ DokterApp/DokterApp.csproj | 6 + DokterApp/MainWindow.xaml | 2 +- DokterApp/MainWindow.xaml.cs | 8 +- ProftaakRH/ProftaakRH.sln | 1 + RH-Engine/Program.cs | 23 ---- 8 files changed, 434 insertions(+), 28 deletions(-) create mode 100644 DokterApp/Client.cs create mode 100644 DokterApp/DataParser.cs diff --git a/Client/Client.cs b/Client/Client.cs index 1a3392a..e9715b9 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -6,7 +6,7 @@ using ProftaakRH; namespace Client { - class Client : IDataReceiver + public class Client : IDataReceiver { private TcpClient client; private NetworkStream stream; @@ -55,7 +55,7 @@ namespace Client this.stream = this.client.GetStream(); - tryLogin(); + tryLoginDoctor("hi","hi"); this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); } @@ -203,6 +203,17 @@ namespace Client this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); } + public void tryLoginDoctor(string username, string password) + { + string hashUser = Hashing.Hasher.HashString(username); + string hashPassword = Hashing.Hasher.HashString(password); + + byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword)); + + + stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + public void setHandler(IHandler handler) { this.handler = handler; diff --git a/DokterApp/Client.cs b/DokterApp/Client.cs new file mode 100644 index 0000000..98f6224 --- /dev/null +++ b/DokterApp/Client.cs @@ -0,0 +1,201 @@ +using System; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using ProftaakRH; + +namespace DokterApp +{ + public class Client : IDataReceiver + { + private TcpClient client; + private NetworkStream stream; + private byte[] buffer = new byte[1024]; + private bool connected; + private byte[] totalBuffer = new byte[1024]; + private int totalBufferReceived = 0; + private bool sessionRunning = false; + private IHandler handler = null; + private string username; + private string password; + + + public Client(string adress, int port, string username, string password) + { + this.username = username; + this.password = password; + this.client = new TcpClient(); + this.connected = false; + client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); + } + + + + + + private void OnConnect(IAsyncResult ar) + { + this.client.EndConnect(ar); + Console.WriteLine("TCP client Verbonden!"); + + this.stream = this.client.GetStream(); + + tryLogin(); + + this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); + } + + private void OnRead(IAsyncResult ar) + { + int receivedBytes = this.stream.EndRead(ar); + + if (totalBufferReceived + receivedBytes > 1024) + { + throw new OutOfMemoryException("buffer too small"); + } + Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, receivedBytes); + totalBufferReceived += receivedBytes; + + int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); + while (totalBufferReceived >= expectedMessageLength) + { + //volledig packet binnen + byte[] messageBytes = new byte[expectedMessageLength]; + Array.Copy(totalBuffer, 0, messageBytes, 0, expectedMessageLength); + + + byte[] payloadbytes = new byte[BitConverter.ToInt32(messageBytes, 0) - 5]; + + Array.Copy(messageBytes, 5, payloadbytes, 0, payloadbytes.Length); + + string identifier; + bool isJson = DataParser.getJsonIdentifier(messageBytes, out identifier); + if (isJson) + { + switch (identifier) + { + case DataParser.LOGIN_RESPONSE: + string responseStatus = DataParser.getResponseStatus(payloadbytes); + if (responseStatus == "OK") + { + this.connected = true; + } + else + { + Console.WriteLine($"login failed \"{responseStatus}\""); + tryLogin(); + } + break; + case DataParser.START_SESSION: + this.sessionRunning = true; + sendMessage(DataParser.getStartSessionJson()); + break; + case DataParser.STOP_SESSION: + this.sessionRunning = false; + 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: + Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); + break; + } + } + else if (DataParser.isRawData(messageBytes)) + { + Console.WriteLine($"Received data: {BitConverter.ToString(payloadbytes)}"); + } + + totalBufferReceived -= expectedMessageLength; + expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); + } + + this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); + + } + + private void sendMessage(byte[] message) + { + stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + + private void OnWrite(IAsyncResult ar) + { + this.stream.EndWrite(ar); + } + + #region interface + //maybe move this to other place + public void BPM(byte[] bytes) + { + if (!sessionRunning) + { + return; + } + if (bytes == null) + { + throw new ArgumentNullException("no bytes"); + } + byte[] message = DataParser.GetRawDataMessage(bytes); + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + + public void Bike(byte[] bytes) + { + if (!sessionRunning) + { + return; + } + if (bytes == null) + { + throw new ArgumentNullException("no bytes"); + } + byte[] message = DataParser.GetRawDataMessage(bytes); + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + + #endregion + + public bool IsConnected() + { + return this.connected; + } + private void tryLogin() + { + //TODO File in lezen + /*Console.WriteLine("enter username"); + string username = Console.ReadLine(); + Console.WriteLine("enter password"); + string password = Console.ReadLine();*/ + + + + + + string hashUser = Hashing.Hasher.HashString(username); + string hashPassword = Hashing.Hasher.HashString(password); + + byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword)); + + + this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); + } + + + + public void setHandler(IHandler handler) + { + this.handler = handler; + } + } +} diff --git a/DokterApp/DataParser.cs b/DokterApp/DataParser.cs new file mode 100644 index 0000000..74df66b --- /dev/null +++ b/DokterApp/DataParser.cs @@ -0,0 +1,206 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Globalization; +using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; +using System.Text; + +namespace DokterApp +{ + public class DataParser + { + public const string LOGIN = "LOGIN"; + 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 + /// + /// username + /// password + /// json object to ASCII to bytes + public static byte[] GetLoginJson(string mUsername, string mPassword) + { + dynamic json = new + { + identifier = LOGIN, + data = new + { + username = mUsername, + password = mPassword, + } + }; + + return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)); + } + + public static bool GetUsernamePassword(byte[] jsonbytes, out string username, out string password) + { + dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(jsonbytes)); + try + { + username = json.data.username; + password = json.data.password; + return true; + } + catch + { + username = null; + password = null; + return false; + } + } + + private static byte[] getJsonMessage(string mIdentifier, dynamic data) + { + dynamic json = new + { + identifier = mIdentifier, + data + }; + 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 }); + } + + public static string getResponseStatus(byte[] json) + { + return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.status; + } + + /// + /// get the identifier from json + /// + /// json in ASCII + /// gets the identifier + /// if it sucseeded + public static bool getJsonIdentifier(byte[] bytes, out string identifier) + { + if (bytes.Length <= 5) + { + throw new ArgumentException("bytes to short"); + } + byte messageId = bytes[4]; + + if (messageId == 0x01) + { + dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(bytes.Skip(5).ToArray())); + identifier = json.identifier; + return true; + } + else + { + identifier = ""; + return false; + } + } + + /// + /// checks if the de message is raw data according to the protocol + /// + /// message + /// if message contains raw data + public static bool isRawData(byte[] bytes) + { + if (bytes.Length <= 5) + { + throw new ArgumentException("bytes to short"); + } + return bytes[4] == 0x02; + } + + /// + /// constructs a message with the payload, messageId and clientId + /// + /// + /// + /// + /// the message ready for sending + private static byte[] getMessage(byte[] payload, byte messageId) + { + byte[] res = new byte[payload.Length + 5]; + + Array.Copy(BitConverter.GetBytes(payload.Length + 5), 0, res, 0, 4); + res[4] = messageId; + Array.Copy(payload, 0, res, 5, payload.Length); + + return res; + } + + /// + /// constructs a message with the payload and clientId and assumes the payload is raw data + /// + /// + /// + /// the message ready for sending + public static byte[] GetRawDataMessage(byte[] payload) + { + return getMessage(payload, 0x02); + } + + /// + /// constructs a message with the payload and clientId and assumes the payload is json + /// + /// + /// + /// the message ready for sending + public static byte[] getJsonMessage(byte[] payload) + { + return getMessage(payload, 0x01); + } + + public static byte[] getStartSessionJson() + { + return getJsonMessage(START_SESSION); + } + + public static byte[] getStopSessionJson() + { + return getJsonMessage(STOP_SESSION); + } + + public static byte[] getSetResistanceJson(float mResistance) + { + dynamic data = new + { + resistance = mResistance + }; + 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/DokterApp/DokterApp.csproj b/DokterApp/DokterApp.csproj index 6c68d0e..f11295a 100644 --- a/DokterApp/DokterApp.csproj +++ b/DokterApp/DokterApp.csproj @@ -6,4 +6,10 @@ true + + + + + + \ No newline at end of file diff --git a/DokterApp/MainWindow.xaml b/DokterApp/MainWindow.xaml index 1c9bce1..092c8e5 100644 --- a/DokterApp/MainWindow.xaml +++ b/DokterApp/MainWindow.xaml @@ -17,7 +17,7 @@ -