Merge branch 'dokter' into develop

This commit is contained in:
fabjuuuh
2020-10-09 10:57:16 +02:00
12 changed files with 473 additions and 20 deletions

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Text;
@@ -6,7 +6,7 @@ using ProftaakRH;
namespace Client
{
class Client : IDataReceiver
public class Client : IDataReceiver
{
private TcpClient client;
private NetworkStream stream;
@@ -123,7 +123,7 @@ namespace Client
{
Console.WriteLine("Username and password correct!");
this.connected = true;
initEngine();
//initEngine();
}
else
{

View File

@@ -4,6 +4,7 @@ using Hardware.Simulators;
using RH_Engine;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace Client
{
@@ -14,6 +15,7 @@ namespace Client
Console.WriteLine("// Connecting... //");
//connect fiets?
Thread.Sleep(20000);
Client client = new Client();

196
DokterApp/Client.cs Normal file
View File

@@ -0,0 +1,196 @@
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;
private Del callback;
public Client(string adress, int port, string username, string password, Del callback)
{
this.callback = callback;
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
{
callback("yeet");
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
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;
}
}
}

206
DokterApp/DataParser.cs Normal file
View File

@@ -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";
/// <summary>
/// makes the json object with LOGIN identifier and username and password
/// </summary>
/// <param name="mUsername">username</param>
/// <param name="mPassword">password</param>
/// <returns>json object to ASCII to bytes</returns>
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;
}
/// <summary>
/// get the identifier from json
/// </summary>
/// <param name="bytes">json in ASCII</param>
/// <param name="identifier">gets the identifier</param>
/// <returns>if it sucseeded</returns>
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;
}
}
/// <summary>
/// checks if the de message is raw data according to the protocol
/// </summary>
/// <param name="bytes">message</param>
/// <returns>if message contains raw data</returns>
public static bool isRawData(byte[] bytes)
{
if (bytes.Length <= 5)
{
throw new ArgumentException("bytes to short");
}
return bytes[4] == 0x02;
}
/// <summary>
/// constructs a message with the payload, messageId and clientId
/// </summary>
/// <param name="payload"></param>
/// <param name="messageId"></param>
/// <param name="clientId"></param>
/// <returns>the message ready for sending</returns>
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;
}
/// <summary>
/// constructs a message with the payload and clientId and assumes the payload is raw data
/// </summary>
/// <param name="payload"></param>
/// <param name="clientId"></param>
/// <returns>the message ready for sending</returns>
public static byte[] GetRawDataMessage(byte[] payload)
{
return getMessage(payload, 0x02);
}
/// <summary>
/// constructs a message with the payload and clientId and assumes the payload is json
/// </summary>
/// <param name="payload"></param>
/// <param name="clientId"></param>
/// <returns>the message ready for sending</returns>
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;
}
}
}

View File

@@ -6,4 +6,15 @@
<UseWPF>true</UseWPF>
</PropertyGroup>
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
<ItemGroup>
<PackageReference Include="ChartControls" Version="1.3.3" />
<PackageReference Include="LiveCharts.Wpf" Version="0.9.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProftaakRH\ProftaakRH.csproj" />
</ItemGroup>
</Project>

View File

@@ -17,7 +17,7 @@
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.ColumnSpan="2" Grid.RowSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Orientation="Vertical">
<Label Content="Sensei" Margin="0,0,0,20" HorizontalAlignment="Center"/>
<Label x:Name="Label" Content="Yo dokter login" Margin="0,0,0,20" HorizontalAlignment="Center"/>
<Label Content="Username" HorizontalContentAlignment="Center"/>
<TextBox x:Name="Username" TextWrapping="Wrap" Width="120"/>
<Label Content="Password" HorizontalContentAlignment="Center"/>

View File

@@ -1,4 +1,5 @@
using System;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -12,7 +13,6 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DokterApp
{
/// <summary>
@@ -20,21 +20,35 @@ namespace DokterApp
/// </summary>
public partial class MainWindow : Window
{
Del handler;
Client client;
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Login_Click_1(object sender, RoutedEventArgs e)
{
WindowTabs windowTabs = new WindowTabs();
handler = windowTabs.NewTab;
this.Label.Content = "Waiting";
this.client = new Client("localhost", 5555, this.Username.Text, this.Password.Text, handler);
while (!client.IsConnected())
{
}
windowTabs.Show();
this.Close();
}
}
public delegate void Del(string message);
}

View File

@@ -31,14 +31,23 @@ namespace DokterApp
private void Button_Click(object sender, RoutedEventArgs e)
{
TabItem newTabItem = new TabItem
{
Header = "Test",
Width = 110,
Height = 40
};
newTabItem.Content = new UserControlForTab();
this.tbControl.Items.Add(newTabItem);
NewTab("Test");
}
public void NewTab(string username)
{
Application.Current.Dispatcher.Invoke((Action)delegate {
// your code
TabItem newTabItem = new TabItem
{
Header = username,
Width = 110,
Height = 40
};
newTabItem.Content = new UserControlForTab();
this.tbControl.Items.Add(newTabItem);
});
}
}
}

BIN
DokterApp/favicon (1).ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -21,6 +21,7 @@ Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
..\Hashing\Hashing.projitems*{013aadba-1d27-4a52-81d8-217697e91039}*SharedItemsImports = 5
..\Hashing\Hashing.projitems*{70277749-d423-4871-b692-2efc5a6ed932}*SharedItemsImports = 13
..\Hashing\Hashing.projitems*{b150f08b-13da-4d17-bd96-7e89f52727c6}*SharedItemsImports = 5
..\Hashing\Hashing.projitems*{b1ab6f51-a20d-4162-9a7f-b3350b7510fd}*SharedItemsImports = 5
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@@ -36,6 +36,7 @@ namespace Server
private void OnRead(IAsyncResult ar)
{
int receivedBytes = this.stream.EndRead(ar);
if (totalBufferReceived + receivedBytes > 1024)
@@ -160,7 +161,7 @@ namespace Server
}
private void sendMessage(byte[] message)
public void sendMessage(byte[] message)
{
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
}

View File

@@ -1,6 +1,8 @@
using System;
using Client;
using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Net.Sockets;
using System.Text;
@@ -10,6 +12,7 @@ namespace Server
{
private TcpListener listener;
private List<Client> clients;
private Client doctor;
public Communication(TcpListener listener)
{
@@ -28,9 +31,19 @@ namespace Server
private void OnConnect(IAsyncResult ar)
{
var tcpClient = listener.EndAcceptTcpClient(ar);
Console.WriteLine($"Client connected from {tcpClient.Client.RemoteEndPoint}");
clients.Add(new Client(this, tcpClient));
if (doctor == null)
{
doctor = clients.ElementAt(0);
}
else
{
doctor.sendMessage(DataParser.getLoginResponse("new client"));
}
listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
}