75 Commits

Author SHA1 Message Date
fabjuuuh
fc0e70403f Icon en livechart library 2020-10-07 16:16:52 +02:00
fabjuuuh
acbe3e9d55 Connect new tab 2020-10-07 14:56:04 +02:00
fabjuuuh
aea1b4fce4 connectie met server 2020-10-07 13:21:30 +02:00
fabjuuuh
a2937c0427 Merge branch 'wpf' into develop 2020-10-07 11:08:05 +02:00
fabjuuuh
02bd68d142 Merge branch 'develop' into wpf 2020-10-07 11:07:40 +02:00
Logophilist
699528bb83 Merge remote-tracking branch 'origin/develop' into develop 2020-10-05 20:21:08 +02:00
Logophilist
e4d192fb06 Commit alt code of VR engine 2020-10-05 20:20:57 +02:00
shinichi
09db19246e quick fix 2020-10-02 15:53:50 +02:00
shinichi
eb2738168b Merge remote-tracking branch 'origin/develop' into develop 2020-10-02 15:38:00 +02:00
shinichi
d85c5ff935 added function to get BPM graph data 2020-10-02 15:37:57 +02:00
Sem van der Hoeven
d420bdc2a4 merge conflicts 7: conflictnado 2020-10-02 11:49:48 +02:00
Sem van der Hoeven
cb2435bf53 weird fix 2020-10-02 11:48:03 +02:00
Sem van der Hoeven
ca2e61eb8e Merge branch 'develop' of https://github.com/SemvdH/Proftaak-RH-B4 into develop 2020-10-02 11:44:30 +02:00
Sem van der Hoeven
32ef17365e pull 2020-10-02 11:44:26 +02:00
Sem van der Hoeven
fedf8c0e5b added client server login with hashed passwords and usernames 2020-10-02 11:43:07 +02:00
shinichi
505c4907d0 Merge branch 'set-resistance' into develop 2020-09-30 19:40:46 +02:00
shinichi
a5e679e6fb server now gets response when resistance is set 2020-09-30 19:40:37 +02:00
Sem van der Hoeven
3e5f6e46c4 progress on validation 2020-09-30 16:22:57 +02:00
shinichi
adea08cfb7 server can set resistance 2020-09-30 16:22:26 +02:00
wouter
c20a1b292e upgraded doktor stuff 2020-09-30 16:08:35 +02:00
shinichi
599b79ceee correctly implemented IHandler 2020-09-30 15:26:34 +02:00
shinichi
bd8994ad5b added start and stop session 2020-09-30 15:12:10 +02:00
Sem van der Hoeven
97f9d863aa fix 2020-09-30 15:10:47 +02:00
fabjuuuh
f777b583f5 progress 2020-09-30 14:37:40 +02:00
Sem van der Hoeven
d6b938668f added reconnecting to the vr server when no tunnel id is found 2020-09-30 14:33:15 +02:00
shinichi
45edbe5936 Merge branch 'binairy-writer' into develop 2020-09-30 14:25:29 +02:00
shinichi
a65c36b8d1 fix bug and more efficient code 2020-09-30 14:24:38 +02:00
shinichi
82f2d6b71c saving bike and bpm data in separate files 2020-09-30 14:17:26 +02:00
fabjuuuh
41e77ba16c hi 2020-09-30 13:12:18 +02:00
shinichi
6f1ab57fe4 saving in binairy format
took forever
2020-09-30 13:00:13 +02:00
Sem van der Hoeven
341723d1d1 added maincommand to engineconnection 2020-09-30 12:59:04 +02:00
Sem van der Hoeven
0cd3753b76 properly added engineconnection to client 2020-09-30 12:30:40 +02:00
Sem van der Hoeven
4388b39be5 only connects when username and password are entered 2020-09-30 12:27:31 +02:00
Sem van der Hoeven
0dc4bb6fad connected engine to client 2020-09-30 12:23:53 +02:00
Sem van der Hoeven
3ca3c1ad78 added engineconnection to client 2020-09-30 12:17:57 +02:00
Sem van der Hoeven
d06d621b13 added necessary methods and added method sig to cw of engineconnect 2020-09-30 12:13:59 +02:00
Sem van der Hoeven
7b05fcc898 added engineconnect as singleton 2020-09-30 12:01:53 +02:00
fabjuuuh
cc7f2d154c wpf 2020-09-30 11:52:38 +02:00
Sem van der Hoeven
c5b9a7ec09 made rh engine classes public 2020-09-30 11:44:00 +02:00
Sem van der Hoeven
3494f678e3 added doctor project 2020-09-30 10:15:30 +02:00
Sem van der Hoeven
9a80dc6260 Merge branch 'client' into develop 2020-09-25 16:49:53 +02:00
Sem van der Hoeven
4cabce69d5 Merge branch 'dashboard_VR' into develop 2020-09-25 16:49:19 +02:00
Logophilist
38886ca7c3 Bike follows route 2020-09-25 16:48:05 +02:00
shinichi
04e29402f7 Merge remote-tracking branch 'origin/client' into client 2020-09-25 16:38:45 +02:00
shinichi
78bb7f6a6c added possibility for multiple DataReceivers 2020-09-25 16:38:22 +02:00
fabjuuuh
99887a22ba Merge remote-tracking branch 'origin/client' into client 2020-09-25 16:38:22 +02:00
fabjuuuh
68a43fb930 Save Raw data 2020-09-25 16:38:16 +02:00
Sem van der Hoeven
dc4d3c852b removed internal 2020-09-25 15:56:47 +02:00
Sem van der Hoeven
13d99eb107 cleanup files 2020-09-25 15:56:26 +02:00
Sem van der Hoeven
aa5f58e752 cleaned program.cs 2020-09-25 15:54:41 +02:00
shinichi
a353d6839e added some flair 2020-09-25 15:50:20 +02:00
Sem van der Hoeven
b6e4842cf8 updated method to get id based on name 2020-09-25 15:48:47 +02:00
Sem van der Hoeven
1057c0caab added comments 2020-09-25 15:40:07 +02:00
shinichi
21203fd3ff login implemented 2020-09-25 15:33:39 +02:00
Sem van der Hoeven
8160e1c158 probably fixed the serials 2020-09-25 15:26:57 +02:00
shinichi
9c3b2c3f9b Auto stash before merge of "client" and "origin/client" 2020-09-25 15:00:43 +02:00
Sem van der Hoeven
d3a37d0238 progress on improving responses 2020-09-25 14:30:33 +02:00
Logophilist
bb30538f00 added features panel 2020-09-25 14:12:16 +02:00
Sem van der Hoeven
23846b14bc creating connection with new reading stuff works 2020-09-25 14:06:56 +02:00
fabjuuuh
6ef5bbfe12 More SaveData 2020-09-25 14:06:45 +02:00
fabjuuuh
cf9341a93e SaveData 2020-09-25 13:43:00 +02:00
Sem van der Hoeven
23f146afdd getting response from server through callback 2020-09-25 13:41:54 +02:00
Sem van der Hoeven
fac3987678 added delegate for reading server response 2020-09-25 13:26:48 +02:00
shinichi
d0071bd13c bug fix 2020-09-25 13:22:16 +02:00
fabjuuuh
97e6a528bb Merge remote-tracking branch 'origin/client' into client 2020-09-25 13:18:49 +02:00
fabjuuuh
80ee448acf Handledata 2020-09-25 13:18:41 +02:00
shinichi
8204f22fe7 better printing on client side 2020-09-25 13:18:19 +02:00
shinichi
22558e3289 print received data on client side 2020-09-25 13:11:14 +02:00
shinichi
360ec4175f OnRead for client updated 2020-09-25 13:04:39 +02:00
shinichi
506a074f36 Merge branch 'OnRead-rewrite' into client 2020-09-25 12:58:20 +02:00
shinichi
96f2e6e973 rewrote OnRead 2020-09-25 12:58:12 +02:00
shinichi
2139fcf2b2 removed clientId 2020-09-25 12:51:54 +02:00
shinichi
dded1a5b24 johan's code
senior meeting
2020-09-25 12:43:01 +02:00
Logophilist
64773ffe1c Attempt 1 dashboard VR 2020-09-23 15:33:23 +02:00
Sem van der Hoeven
a8d7e03331 added comment to enum 2020-09-23 12:11:36 +02:00
38 changed files with 2173 additions and 316 deletions

View File

@@ -1,17 +1,22 @@
using System; using System;
using System.Linq;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text;
using ProftaakRH; using ProftaakRH;
namespace Client namespace Client
{ {
class Client : IDataReceiver public class Client : IDataReceiver
{ {
private TcpClient client; private TcpClient client;
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[1024];
private int bytesReceived;
private bool connected; private bool connected;
private byte clientId = 0; private byte[] totalBuffer = new byte[1024];
private int totalBufferReceived = 0;
private EngineConnection engineConnection;
private bool sessionRunning = false;
private IHandler handler = null;
public Client() : this("localhost", 5555) public Client() : this("localhost", 5555)
@@ -22,80 +27,124 @@ namespace Client
public Client(string adress, int port) public Client(string adress, int port)
{ {
this.client = new TcpClient(); this.client = new TcpClient();
this.bytesReceived = 0;
this.connected = false; this.connected = false;
client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null); client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null);
} }
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) private void OnConnect(IAsyncResult ar)
{ {
this.client.EndConnect(ar); this.client.EndConnect(ar);
Console.WriteLine("Verbonden!"); Console.WriteLine("TCP client Verbonden!");
this.stream = this.client.GetStream(); this.stream = this.client.GetStream();
//TODO File in lezen tryLogin();
Console.WriteLine("enter username");
string username = Console.ReadLine();
Console.WriteLine("enter password");
string password = Console.ReadLine();
byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(username, password), this.clientId);
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
//TODO lees OK message
//temp moet eigenlijk een ok bericht ontvangen
this.connected = true;
} }
private void OnRead(IAsyncResult ar) private void OnRead(IAsyncResult ar)
{ {
int receivedBytes = this.stream.EndRead(ar); int receivedBytes = this.stream.EndRead(ar);
byte[] lengthBytes = new byte[4];
Array.Copy(this.buffer, 0, lengthBytes, 0, 4); if (totalBufferReceived + receivedBytes > 1024)
int expectedMessageLength = BitConverter.ToInt32(lengthBytes);
if (expectedMessageLength > this.buffer.Length)
{ {
throw new OutOfMemoryException("buffer to small"); throw new OutOfMemoryException("buffer too small");
} }
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, receivedBytes);
totalBufferReceived += receivedBytes;
if (expectedMessageLength > this.bytesReceived + receivedBytes) int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{ {
//message hasn't completely arrived yet //volledig packet binnen
this.bytesReceived += receivedBytes; byte[] messageBytes = new byte[expectedMessageLength];
this.stream.BeginRead(this.buffer, this.bytesReceived, this.buffer.Length - this.bytesReceived, new AsyncCallback(OnRead), null); Array.Copy(totalBuffer, 0, messageBytes, 0, expectedMessageLength);
}
else byte[] payloadbytes = new byte[BitConverter.ToInt32(messageBytes, 0) - 5];
{
//message completely arrived Array.Copy(messageBytes, 5, payloadbytes, 0, payloadbytes.Length);
if (expectedMessageLength != this.bytesReceived + receivedBytes)
{
Console.WriteLine("something has gone completely wrong");
}
string identifier; string identifier;
bool isJson = DataParser.getJsonIdentifier(this.buffer, out identifier); bool isJson = DataParser.getJsonIdentifier(messageBytes, out identifier);
if (isJson) if (isJson)
{ {
throw new NotImplementedException(); switch (identifier)
{
case DataParser.LOGIN_RESPONSE:
string responseStatus = DataParser.getResponseStatus(payloadbytes);
if (responseStatus == "OK")
{
this.connected = true;
//initEngine();
}
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(this.buffer)) else if (DataParser.isRawData(messageBytes))
{ {
throw new NotImplementedException(); 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); 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) private void OnWrite(IAsyncResult ar)
{ {
this.stream.EndWrite(ar); this.stream.EndWrite(ar);
@@ -105,21 +154,29 @@ namespace Client
//maybe move this to other place //maybe move this to other place
public void BPM(byte[] bytes) public void BPM(byte[] bytes)
{ {
if (!sessionRunning)
{
return;
}
if (bytes == null) if (bytes == null)
{ {
throw new ArgumentNullException("no bytes"); throw new ArgumentNullException("no bytes");
} }
byte[] message = DataParser.GetRawDataMessage(bytes, clientId); byte[] message = DataParser.GetRawDataMessage(bytes);
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
} }
public void Bike(byte[] bytes) public void Bike(byte[] bytes)
{ {
if (!sessionRunning)
{
return;
}
if (bytes == null) if (bytes == null)
{ {
throw new ArgumentNullException("no bytes"); throw new ArgumentNullException("no bytes");
} }
byte[] message = DataParser.GetRawDataMessage(bytes, clientId); byte[] message = DataParser.GetRawDataMessage(bytes);
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null); this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
} }
@@ -129,5 +186,37 @@ namespace Client
{ {
return this.connected; 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 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;
}
} }
} }

View File

@@ -12,6 +12,9 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Message\Message.csproj" /> <ProjectReference Include="..\Message\Message.csproj" />
<ProjectReference Include="..\ProftaakRH\ProftaakRH.csproj" /> <ProjectReference Include="..\ProftaakRH\ProftaakRH.csproj" />
<ProjectReference Include="..\RH-Engine\RH-Engine.csproj" />
</ItemGroup> </ItemGroup>
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
</Project> </Project>

View File

@@ -1,12 +1,20 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System; using System;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text; using System.Text;
namespace Client namespace Client
{ {
class DataParser 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> /// <summary>
/// makes the json object with LOGIN identifier and username and password /// makes the json object with LOGIN identifier and username and password
/// </summary> /// </summary>
@@ -17,7 +25,7 @@ namespace Client
{ {
dynamic json = new dynamic json = new
{ {
identifier = "LOGIN", identifier = LOGIN,
data = new data = new
{ {
username = mUsername, username = mUsername,
@@ -28,6 +36,52 @@ namespace Client
return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)); 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> /// <summary>
/// get the identifier from json /// get the identifier from json
/// </summary> /// </summary>
@@ -36,15 +90,15 @@ namespace Client
/// <returns>if it sucseeded</returns> /// <returns>if it sucseeded</returns>
public static bool getJsonIdentifier(byte[] bytes, out string identifier) public static bool getJsonIdentifier(byte[] bytes, out string identifier)
{ {
if (bytes.Length <= 6) if (bytes.Length <= 5)
{ {
throw new ArgumentException("bytes to short"); throw new ArgumentException("bytes to short");
} }
byte messageId = bytes[4]; byte messageId = bytes[4];
if (messageId == 1) if (messageId == 0x01)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(bytes.Skip(6).ToArray())); dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(bytes.Skip(5).ToArray()));
identifier = json.identifier; identifier = json.identifier;
return true; return true;
} }
@@ -62,7 +116,7 @@ namespace Client
/// <returns>if message contains raw data</returns> /// <returns>if message contains raw data</returns>
public static bool isRawData(byte[] bytes) public static bool isRawData(byte[] bytes)
{ {
if (bytes.Length <= 6) if (bytes.Length <= 5)
{ {
throw new ArgumentException("bytes to short"); throw new ArgumentException("bytes to short");
} }
@@ -76,14 +130,13 @@ namespace Client
/// <param name="messageId"></param> /// <param name="messageId"></param>
/// <param name="clientId"></param> /// <param name="clientId"></param>
/// <returns>the message ready for sending</returns> /// <returns>the message ready for sending</returns>
private static byte[] getMessage(byte[] payload, byte messageId, byte clientId) private static byte[] getMessage(byte[] payload, byte messageId)
{ {
byte[] res = new byte[payload.Length + 6]; byte[] res = new byte[payload.Length + 5];
Array.Copy(BitConverter.GetBytes(payload.Length + 6), 0, res, 0, 4); Array.Copy(BitConverter.GetBytes(payload.Length + 5), 0, res, 0, 4);
res[4] = messageId; res[4] = messageId;
res[5] = clientId; Array.Copy(payload, 0, res, 5, payload.Length);
Array.Copy(payload, 0, res, 6, payload.Length);
return res; return res;
} }
@@ -94,9 +147,9 @@ namespace Client
/// <param name="payload"></param> /// <param name="payload"></param>
/// <param name="clientId"></param> /// <param name="clientId"></param>
/// <returns>the message ready for sending</returns> /// <returns>the message ready for sending</returns>
public static byte[] GetRawDataMessage(byte[] payload, byte clientId) public static byte[] GetRawDataMessage(byte[] payload)
{ {
return getMessage(payload, 0x02, clientId); return getMessage(payload, 0x02);
} }
/// <summary> /// <summary>
@@ -105,20 +158,47 @@ namespace Client
/// <param name="payload"></param> /// <param name="payload"></param>
/// <param name="clientId"></param> /// <param name="clientId"></param>
/// <returns>the message ready for sending</returns> /// <returns>the message ready for sending</returns>
public static byte[] getJsonMessage(byte[] payload, byte clientId) public static byte[] getJsonMessage(byte[] payload)
{ {
return getMessage(payload, 0x01, clientId); return getMessage(payload, 0x01);
} }
/// <summary> public static byte[] getStartSessionJson()
/// constructs a message with the message and clientId
/// </summary>
/// <param name="message"></param>
/// <param name="clientId"></param>
/// <returns>the message ready for sending</returns>
public static byte[] getJsonMessage(string message, byte clientId)
{ {
return getJsonMessage(Encoding.ASCII.GetBytes(message), clientId); 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;
} }

180
Client/EngineConnection.cs Normal file
View File

@@ -0,0 +1,180 @@
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 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("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<string, HandleSerial> serialResponses = new Dictionary<string, HandleSerial>();
private Command mainCommand;
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();
initReader();
CreateConnection();
}
/// <summary>
/// connects to the server and creates the tunnel
/// </summary>
/// <param name="stream">the network stream to use</param>
public void CreateConnection()
{
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) { }
if (tunnelId != null)
{
Write("got tunnel id! " + tunnelId);
}
mainCommand = new Command(tunnelId);
}
/// <summary>
/// initializes and starts the reading of the responses from the vr server
/// </summary>
/// <param name="stream">the networkstream</param>
private void initReader()
{
serverResponseReader = new ServerResponseReader(stream);
serverResponseReader.callback = HandleResponse;
serverResponseReader.StartRead();
Connected = true;
}
/// <summary>
/// callback method that handles responses from the server
/// </summary>
/// <param name="message">the response message from the server</param>
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!");
OnNoTunnelId?.Invoke();
Connected = false;
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="stream">the networkstream to use</param>
/// <param name="message">the message to send</param>
/// <param name="serial">the serial to check for</param>
/// <param name="action">the code to be executed upon reveiving a reply from the server with the specified serial</param>
public void SendMessageAndOnResponse(string message, string serial, HandleSerial action)
{
serialResponses.Add(serial, action);
WriteTextMessage(message);
}
/// <summary>
/// writes a message to the server
/// </summary>
/// <param name="stream">the network stream to use</param>
/// <param name="message">the message to send</param>
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);
}
}
}

View File

@@ -1,5 +1,10 @@
using System; using System;
using Hardware; using Hardware;
using Hardware.Simulators;
using RH_Engine;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace Client namespace Client
{ {
@@ -10,7 +15,7 @@ namespace Client
Console.WriteLine("Hello World!"); Console.WriteLine("Hello World!");
//connect fiets? //connect fiets?
Thread.Sleep(20000);
Client client = new Client(); Client client = new Client();
@@ -22,10 +27,15 @@ namespace Client
bLEHandler.Connect(); bLEHandler.Connect();
client.setHandler(bLEHandler);
//BikeSimulator bikeSimulator = new BikeSimulator(client); //BikeSimulator bikeSimulator = new BikeSimulator(client);
//bikeSimulator.StartSimulation(); //bikeSimulator.StartSimulation();
//client.setHandler(bikeSimulator);
while (true) while (true)
{ {
} }

9
DokterApp/App.xaml Normal file
View File

@@ -0,0 +1,9 @@
<Application x:Class="DokterApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DokterApp"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

17
DokterApp/App.xaml.cs Normal file
View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace DokterApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

10
DokterApp/AssemblyInfo.cs Normal file
View File

@@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

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

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<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>

28
DokterApp/ITab.cs Normal file
View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace DokterApp
{
public interface ITab
{
string Name { get; set; }
ICommand CloseCommand { get; }
event EventHandler CloseRequested;
}
public abstract class Tab : ITab
{
public string Name { get; set; }
public ICommand CloseCommand { get; }
public event EventHandler CloseRequested;
public Tab()
{
//CloseCommand =
}
}
}

29
DokterApp/MainWindow.xaml Normal file
View File

@@ -0,0 +1,29 @@
<Window x:Class="DokterApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DokterApp"
mc:Ignorable="d"
WindowState="Maximized"
Title="Dokter App" >
<Grid RenderTransformOrigin="0.499,0.49">
<Grid.RowDefinitions>
<RowDefinition Height="23*"/>
<RowDefinition Height="31*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.ColumnSpan="2" Grid.RowSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Orientation="Vertical">
<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"/>
<TextBox x:Name="Password" TextWrapping="Wrap" Width="120"/>
<Button x:Name="Login" Content="Login" Margin="0,20,0,0" Click="Login_Click_1" />
</StackPanel>
</Grid>
</Window>

View File

@@ -0,0 +1,54 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DokterApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Del handler;
Client client;
public MainWindow()
{
InitializeComponent();
}
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

@@ -0,0 +1,67 @@
<UserControl x:Class="DokterApp.UserControlForTab"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DokterApp"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Margin="15,5,15,15">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="43*"/>
<RowDefinition Height="47*"/>
<RowDefinition Height="180*"/>
<RowDefinition Height="180*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.RowSpan="2" Margin="0,0,0,22">
<StackPanel.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Margin" Value="0,0,20,0"/>
</Style>
</StackPanel.Resources>
<Label Content="UserName" Name="Username_Label"/>
<Label Content="Status: " Name="Status_Label"/>
</StackPanel>
<StackPanel Margin="0,10,0,0" Grid.RowSpan="2" Grid.Row="1">
<StackPanel.Resources>
<Style TargetType="{x:Type DockPanel}">
<Setter Property="Margin" Value="0,20,0,0"/>
</Style>
</StackPanel.Resources>
<DockPanel Height="26" LastChildFill="False" HorizontalAlignment="Stretch">
<Label Content="Resistance" Width="110" DockPanel.Dock="Right"/>
<Label Content="Current Speed" Width="110" DockPanel.Dock="Left"/>
<Label Content="Current BPM" Width="110" DockPanel.Dock="Top"/>
</DockPanel>
<DockPanel Height="26" LastChildFill="False" HorizontalAlignment="Stretch">
<TextBox Name="textBox_Resistance" Text="" TextWrapping="Wrap" Width="110" DockPanel.Dock="Right" IsReadOnly="true"/>
<TextBox Name="textBox_CurrentSpeed" Text="" TextWrapping="Wrap" Width="110" DockPanel.Dock="Left" IsReadOnly="true"/>
<TextBox Name="textBox_CurrentBPM" Text="" TextWrapping="Wrap" Width="110" DockPanel.Dock="Top" Height="26" IsReadOnly="true"/>
</DockPanel>
<DockPanel Height="26" LastChildFill="False">
<Label Content="Distance Covered" Width="110" DockPanel.Dock="Right"/>
<Label Content="Current Power" Width="110" DockPanel.Dock="Left"/>
<Label Content="Acc. Power" Width="110" DockPanel.Dock="Top"/>
</DockPanel>
<DockPanel Height="26" LastChildFill="False">
<TextBox Name="textBox_DistanceCovered" Text="" TextWrapping="Wrap" Width="110" DockPanel.Dock="Right" IsReadOnly="true"/>
<TextBox Name="textBox_CurrentPower" Text="" TextWrapping="Wrap" Width="110" DockPanel.Dock="Left" IsReadOnly="true"/>
<TextBox Name="textBox_AccPower" Text="" TextWrapping="Wrap" Width="110" DockPanel.Dock="Top" Height="26" IsReadOnly="true"/>
</DockPanel>
</StackPanel>
<ListBox Name="ChatBox" Grid.Column="1" Margin="59,41,0,0" SelectionChanged="ListBox_SelectionChanged" Grid.RowSpan="3"/>
<TextBox Name="textBox_Chat" Grid.Column="1" HorizontalAlignment="Left" Margin="59,10,0,0" Grid.Row="3" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="235"/>
<Button Content="Button" Grid.Column="1" HorizontalAlignment="Left" Margin="59,33,0,0" Grid.Row="3" VerticalAlignment="Top" Click="Button_Click"/>
<Button Content="Start Session" Grid.Column="1" HorizontalAlignment="Left" Margin="69,86,0,0" Grid.Row="3" VerticalAlignment="Top" Width="97" Click="StartSession_Click"/>
<Button Content="Stop Session" Grid.Column="1" HorizontalAlignment="Left" Margin="187,86,0,0" Grid.Row="3" VerticalAlignment="Top" Width="97" Click="StopSession_Click"/>
<TextBox x:Name="textBox_SetResistance" Grid.Column="1" HorizontalAlignment="Left" Margin="69,128,0,0" Grid.Row="3" TextWrapping="Wrap" VerticalAlignment="Top" Width="97"/>
<Button Content="Set Resistance" Grid.Column="1" HorizontalAlignment="Left" Margin="187,128,0,0" Grid.Row="3" VerticalAlignment="Top" Width="97" Height="18" Click="SetResistance_Click"/>
<Canvas Grid.Row="3" Background="White" Margin="0,33,0,0"/>
<ComboBox Name="DropBox" HorizontalAlignment="Left" Margin="0,6,0,0" Grid.Row="3" VerticalAlignment="Top" Width="190"/>
<Button Content="Client Info" Grid.Column="1" HorizontalAlignment="Left" Margin="207,6,0,0" VerticalAlignment="Top" Height="26" Width="82" Click="ClientInfo_Click"/>
</Grid>
</UserControl>

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DokterApp
{
/// <summary>
/// Interaction logic for UserControlForTab.xaml
/// </summary>
public partial class UserControlForTab : UserControl
{
public UserControlForTab()
{
InitializeComponent();
Username_Label.Content = "Bob";
Status_Label.Content = "Status: Dead";
}
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ChatBox.Items.Add(textBox_Chat.Text);
}
private void StartSession_Click(object sender, RoutedEventArgs e)
{
}
private void StopSession_Click(object sender, RoutedEventArgs e)
{
}
private void SetResistance_Click(object sender, RoutedEventArgs e)
{
}
private void ClientInfo_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("firstname:\tBob\n" +
"surname:\t\tde Bouwer");
}
}
}

14
DokterApp/UserTab.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace DokterApp
{
class UserTab : Tab
{
public UserTab()
{
Name = "Piet";
}
}
}

16
DokterApp/WindowTabs.xaml Normal file
View File

@@ -0,0 +1,16 @@
<Window x:Class="DokterApp.WindowTabs"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DokterApp"
mc:Ignorable="d"
WindowState="Maximized"
Title="WindowTabs" Height="450" Width="800">
<Grid>
<TabControl x:Name="tabControl" Loaded="tabControl_Load" TabStripPlacement="Left" Margin="0,23,0,0" />
<Button Content="Button" HorizontalAlignment="Left" Margin="578,125,0,0" VerticalAlignment="Top" Click="Button_Click"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>

View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace DokterApp
{
/// <summary>
/// Interaction logic for WindowTabs.xaml
/// </summary>
public partial class WindowTabs : Window
{
public TabControl tbControl;
public WindowTabs()
{
InitializeComponent();
}
private void tabControl_Load(object sender, RoutedEventArgs e)
{
this.tbControl = (sender as TabControl);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
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

27
Hashing/Hasher.cs Normal file
View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Hashing
{
class Hasher
{
public static byte[] GetHash(string input)
{
using (HashAlgorithm algorithm = SHA256.Create())
{
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(input));
}
}
public static string HashString(string input)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(input)) {
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
}

14
Hashing/Hashing.projitems Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>70277749-d423-4871-b692-2efc5a6ed932</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>Hashing</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Hasher.cs" />
</ItemGroup>
</Project>

13
Hashing/Hashing.shproj Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>70277749-d423-4871-b692-2efc5a6ed932</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="Hashing.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>

View File

@@ -60,6 +60,9 @@ namespace Message
} }
} }
/// <summary>
/// Identifier enum for the Message objects
/// </summary>
public enum Identifier public enum Identifier
{ {
LOGIN, LOGIN,

View File

@@ -11,9 +11,9 @@ namespace Hardware
/// <summary> /// <summary>
/// <c>BLEHandler</c> class that handles connection and traffic to and from the bike /// <c>BLEHandler</c> class that handles connection and traffic to and from the bike
/// </summary> /// </summary>
public class BLEHandler public class BLEHandler : IHandler
{ {
IDataReceiver dataReceiver; List<IDataReceiver> dataReceivers;
private BLE bleBike; private BLE bleBike;
private BLE bleHeart; private BLE bleHeart;
public bool Running { get; set; } public bool Running { get; set; }
@@ -24,7 +24,19 @@ namespace Hardware
/// <param name="dataReceiver">the dataconverter object</param> /// <param name="dataReceiver">the dataconverter object</param>
public BLEHandler(IDataReceiver dataReceiver) public BLEHandler(IDataReceiver dataReceiver)
{ {
this.dataReceiver = dataReceiver; this.dataReceivers = new List<IDataReceiver> { dataReceiver };
}
public BLEHandler(List<IDataReceiver> dataReceivers)
{
this.dataReceivers = dataReceivers;
}
public void addDataReceiver(IDataReceiver dataReceiver)
{
this.dataReceivers.Add(dataReceiver);
} }
/// <summary> /// <summary>
@@ -33,6 +45,7 @@ namespace Hardware
public void Connect() public void Connect()
{ {
BLE bleBike = new BLE(); BLE bleBike = new BLE();
Thread.Sleep(1000); // We need some time to list available devices Thread.Sleep(1000); // We need some time to list available devices
// List available devices // List available devices
@@ -125,11 +138,17 @@ namespace Hardware
{ {
byte[] payload = new byte[8]; byte[] payload = new byte[8];
Array.Copy(e.Data, 4, payload, 0, 8); Array.Copy(e.Data, 4, payload, 0, 8);
this.dataReceiver.Bike(payload); foreach (IDataReceiver dataReceiver in this.dataReceivers)
{
dataReceiver.Bike(payload);
}
} }
else if (e.ServiceName == "00002a37-0000-1000-8000-00805f9b34fb") else if (e.ServiceName == "00002a37-0000-1000-8000-00805f9b34fb")
{ {
this.dataReceiver.BPM(e.Data); foreach (IDataReceiver dataReceiver in this.dataReceivers)
{
dataReceiver.BPM(e.Data);
}
} }
else else
{ {
@@ -154,6 +173,11 @@ namespace Hardware
/// <param name="percentage">The precentage of resistance to set</param> /// <param name="percentage">The precentage of resistance to set</param>
public void setResistance(float percentage) public void setResistance(float percentage)
{ {
if (!this.Running)
{
Console.WriteLine("BLE is not running");
return;
}
byte[] antMessage = new byte[13]; byte[] antMessage = new byte[13];
antMessage[0] = 0x4A; antMessage[0] = 0x4A;
antMessage[1] = 0x09; antMessage[1] = 0x09;

View File

@@ -12,7 +12,7 @@ namespace Hardware.Simulators
{ {
public class BikeSimulator : IHandler public class BikeSimulator : IHandler
{ {
IDataReceiver dataReceiver; List<IDataReceiver> dataReceivers;
private int elapsedTime = 0; private int elapsedTime = 0;
private int eventCounter = 0; private int eventCounter = 0;
private double distanceTraveled = 0; private double distanceTraveled = 0;
@@ -32,7 +32,17 @@ namespace Hardware.Simulators
public BikeSimulator(IDataReceiver dataReceiver) public BikeSimulator(IDataReceiver dataReceiver)
{ {
this.dataReceiver = dataReceiver; this.dataReceivers = new List<IDataReceiver> { dataReceiver };
}
public BikeSimulator(List<IDataReceiver> dataReceivers)
{
this.dataReceivers = dataReceivers;
}
public void addDataReceiver(IDataReceiver dataReceiver)
{
this.dataReceivers.Add(dataReceiver);
} }
public void StartSimulation() public void StartSimulation()
@@ -50,9 +60,12 @@ namespace Hardware.Simulators
CalculateVariables(improvedPerlin.GetValue(x) + 1); CalculateVariables(improvedPerlin.GetValue(x) + 1);
//Simulate sending data //Simulate sending data
dataReceiver.Bike(GenerateBike0x19()); foreach (IDataReceiver dataReceiver in this.dataReceivers)
dataReceiver.Bike(GenerateBike0x10()); {
dataReceiver.BPM(GenerateHeart()); dataReceiver.Bike(GenerateBike0x19());
dataReceiver.Bike(GenerateBike0x10());
dataReceiver.BPM(GenerateHeart());
}
Thread.Sleep(1000); Thread.Sleep(1000);
@@ -85,32 +98,7 @@ namespace Hardware.Simulators
return hartByte; 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 //Calculates the needed variables
//Input perlin value //Input perlin value
@@ -130,20 +118,11 @@ namespace Hardware.Simulators
} }
//Set resistance in simulated bike //Set resistance in simulated bike
public void setResistance(byte[] bytes) public void setResistance(float percentage)
{ {
//TODO check if message is correct this.resistance = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0);
if (bytes.Length == 13)
{
this.resistance = Convert.ToDouble(bytes[11]) / 2;
}
} }
}
//Interface for receiving a message on the simulated bike
interface IHandler
{
void setResistance(byte[] bytes);
} }
} }

11
ProftaakRH/IHandler.cs Normal file
View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ProftaakRH
{
public interface IHandler
{
void setResistance(float percentage);
}
}

View File

@@ -13,9 +13,9 @@ namespace ProftaakRH
{ {
IDataReceiver dataReceiver = new DataConverter(); IDataReceiver dataReceiver = new DataConverter();
BLEHandler bLEHandler = new BLEHandler(dataReceiver); BLEHandler bLEHandler = new BLEHandler(dataReceiver);
//BikeSimulator bikeSimulator = new BikeSimulator(dataConverter); BikeSimulator bikeSimulator = new BikeSimulator(dataReceiver);
//bikeSimulator.setResistance(bikeSimulator.GenerateResistance(1f)); bikeSimulator.setResistance(1);
//bikeSimulator.StartSimulation(); bikeSimulator.StartSimulation();
bool running = true; bool running = true;

View File

@@ -7,13 +7,23 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProftaakRH", "ProftaakRH.cs
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RH-Engine", "..\RH-Engine\RH-Engine.csproj", "{984E295E-47A2-41E7-90E5-50FDB9E67694}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RH-Engine", "..\RH-Engine\RH-Engine.csproj", "{984E295E-47A2-41E7-90E5-50FDB9E67694}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "..\Server\Server.csproj", "{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "..\Server\Server.csproj", "{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "..\Client\Client.csproj", "{5759DD20-7A4F-4D8D-B986-A70A7818C112}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "..\Client\Client.csproj", "{5759DD20-7A4F-4D8D-B986-A70A7818C112}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Message", "..\Message\Message.csproj", "{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Message", "..\Message\Message.csproj", "{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}"
EndProject
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 EndProject
Global 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*{b150f08b-13da-4d17-bd96-7e89f52727c6}*SharedItemsImports = 5
..\Hashing\Hashing.projitems*{b1ab6f51-a20d-4162-9a7f-b3350b7510fd}*SharedItemsImports = 5
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
@@ -39,6 +49,10 @@ Global
{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Release|Any CPU.Build.0 = Release|Any CPU {9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Release|Any CPU.Build.0 = Release|Any CPU
{B150F08B-13DA-4D17-BD96-7E89F52727C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B150F08B-13DA-4D17-BD96-7E89F52727C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B150F08B-13DA-4D17-BD96-7E89F52727C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B150F08B-13DA-4D17-BD96-7E89F52727C6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -1,14 +1,10 @@
using LibNoise.Primitive; using LibNoise.Primitive;
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
namespace RH_Engine namespace RH_Engine
{ {
class Command public class Command
{ {
public const string STANDARD_HEAD = "Head"; public const string STANDARD_HEAD = "Head";
public const string STANDARD_GROUND = "GroundPlane"; public const string STANDARD_GROUND = "GroundPlane";
@@ -16,9 +12,7 @@ namespace RH_Engine
public const string STANDARD_LEFTHAND = "LeftHand"; public const string STANDARD_LEFTHAND = "LeftHand";
public const string STANDARD_RIGHTHAND = "RightHand"; public const string STANDARD_RIGHTHAND = "RightHand";
private string tunnelID;
string tunnelID;
public Command(string tunnelID) public Command(string tunnelID)
{ {
@@ -35,10 +29,10 @@ namespace RH_Engine
size = sizeArray, size = sizeArray,
heights = heightsArray heights = heightsArray
} }
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
public string AddLayer(string uid, string texture) public string AddLayer(string uid, string texture)
{ {
dynamic payload = new dynamic payload = new
@@ -56,6 +50,7 @@ namespace RH_Engine
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
public string UpdateTerrain() public string UpdateTerrain()
{ {
dynamic payload = new dynamic payload = new
@@ -63,7 +58,6 @@ namespace RH_Engine
id = "scene/terrain/update", id = "scene/terrain/update",
data = new data = new
{ {
} }
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
@@ -89,39 +83,138 @@ namespace RH_Engine
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
public string DeleteNode(string uuid) public string DeleteNode(string uuid, string serialCode)
{ {
dynamic payload = new dynamic payload = new
{ {
id = "scene/node/delete", id = "scene/node/delete",
serial = serialCode,
data = new data = new
{ {
id = uuid, id = uuid,
} }
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
public string AddBikeModel() public string addPanel(string serialToSend, string uuidBike)
{ {
return AddModel("bike", "data\\NetworkEngine\\models\\bike\\bike.fbx"); dynamic payload = new
{
id = "scene/node/add",
serial = serialToSend,
data = new
{
name = "dashboard",
components = new
{
panel = new
{
size = new int[] { 1, 1 },
resolution = new int[] { 512, 512 },
background = new int[] { 1, 1, 1, 1 },
castShadow = false
}
}
}
};
return JsonConvert.SerializeObject(Payload(payload));
} }
public string AddModel(string nodeName, string fileLocation) public string ColorPanel(string uuidPanel)
{ {
return AddModel(nodeName, fileLocation, null, new float[] { 0, 0, 0 }, 1, new float[] { 0, 0, 0 }); dynamic payload = new
{
id = "scene/panel/setclearcolor",
data = new
{
id = uuidPanel,
color = new int[] { 1, 1, 1, 1 }
}
};
return JsonConvert.SerializeObject(Payload(payload));
} }
public string AddModel(string nodeName, string fileLocation, float[] positionVector, float scalar, float[] rotationVector) public string SwapPanel(string uuid)
{ {
return AddModel(nodeName, fileLocation, null, positionVector, scalar, rotationVector); dynamic payload = new
{
id = "scene/panel/swap",
data = new
{
id = uuid
}
};
return JsonConvert.SerializeObject(Payload(payload));
} }
public string AddModel(string nodeName, string fileLocation, string animationLocation, float[] positionVector, float scalar, float[] rotationVector) public string bikeSpeed(string uuidPanel, string serialCode, double speed)
{
dynamic payload = new
{
id = "scene/panel/drawtext",
serial = serialCode,
data = new
{
id = uuidPanel,
text = "Speed: " + speed.ToString(),
position = new int[] { 4, 24 },
size = 36.0,
color = new int[] { 0, 0, 0, 1 },
font = "segoeui"
}
};
return JsonConvert.SerializeObject(Payload(payload));
}
public string SwapPanelCommand(string uuid)
{
dynamic payload = new
{
id = "scene/panel/swap",
data = new
{
id = uuid
}
};
return JsonConvert.SerializeObject(Payload(payload));
}
public string ClearPanel(string uuid)
{
dynamic payload = new
{
id = "scene/panel/clear",
data = new
{
id = uuid
}
};
return JsonConvert.SerializeObject(Payload(payload));
}
public string AddBikeModel(string serial)
{
return AddModel("bike", serial, "data\\NetworkEngine\\models\\bike\\bike.fbx");
}
public string AddModel(string nodeName, string serial, string fileLocation)
{
return AddModel(nodeName, serial, fileLocation, null, new float[] { 0, 0, 0 }, 1, new float[] { 0, 0, 0 });
}
public string AddModel(string nodeName, string serial, string fileLocation, float[] positionVector, float scalar, float[] rotationVector)
{
return AddModel(nodeName, serial, fileLocation, null, positionVector, scalar, rotationVector);
}
public string AddModel(string nodeName, string serialToSend, string fileLocation, string animationLocation, float[] positionVector, float scalar, float[] rotationVector)
{ {
string namename = nodeName; string namename = nodeName;
bool animatedBool = false; bool animatedBool = false;
@@ -133,6 +226,7 @@ namespace RH_Engine
dynamic payload = new dynamic payload = new
{ {
id = "scene/node/add", id = "scene/node/add",
serial = serialToSend,
data = new data = new
{ {
name = namename, name = namename,
@@ -143,7 +237,6 @@ namespace RH_Engine
position = positionVector, position = positionVector,
scale = scalar, scale = scalar,
rotation = rotationVector rotation = rotationVector
}, },
model = new model = new
{ {
@@ -154,21 +247,21 @@ namespace RH_Engine
}, },
} }
} }
}; };
return JsonConvert.SerializeObject(Payload(payload)); 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 dynamic payload = new
{ {
id = "scene/node/moveto", id = "scene/node/moveto",
serial = serialCode,
data = new data = new
{ {
id = uuid, id = uuid,
@@ -184,14 +277,14 @@ namespace RH_Engine
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
public string RouteCommand(string serialToSend)
public string RouteCommand()
{ {
ImprovedPerlin improvedPerlin = new ImprovedPerlin(4325, LibNoise.NoiseQuality.Best); ImprovedPerlin improvedPerlin = new ImprovedPerlin(4325, LibNoise.NoiseQuality.Best);
Random r = new Random(); Random r = new Random();
dynamic payload = new dynamic payload = new
{ {
id = "route/add", id = "route/add",
serial = serialToSend,
data = new data = new
{ {
nodes = new dynamic[] nodes = new dynamic[]
@@ -228,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)); return JsonConvert.SerializeObject(Payload(payload));
} }
@@ -241,13 +334,44 @@ namespace RH_Engine
private int[] GetDir() private int[] GetDir()
{ {
Random rng = new Random(); Random rng = new Random();
int[] dir = {rng.Next(50), 0, rng.Next(50)}; int[] dir = { rng.Next(50), 0, rng.Next(50) };
return dir; return dir;
} }
public string FollowRouteCommand() public string RouteFollow(string routeID, string nodeID, float speedValue)
{ {
return ""; return RouteFollow(routeID, nodeID, speedValue, new float[] { 0, 0, 0 });
}
public string RouteFollow(string routeID, string nodeID, float speedValue, float[] rotateOffsetVector, float[] positionOffsetVector)
{
return RouteFollow(routeID, nodeID, speedValue, 0, "XYZ", 1, true, rotateOffsetVector, positionOffsetVector);
}
public string RouteFollow(string routeID, string nodeID, float speedValue, float[] positionOffsetVector)
{
return RouteFollow(routeID, nodeID, speedValue, 0, "XYZ", 1, true, new float[] { 0, 0, 0 }, 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
{
id = "route/follow",
data = new
{
route = routeID,
node = nodeID,
speed = speedValue,
offset = offsetValue,
rotate = rotateValue,
smoothing = smoothingValue,
followHeight = followHeightValue,
rotateOffset = rotateOffsetVector,
positionOffset = positionOffsetVector
}
};
return JsonConvert.SerializeObject(Payload(payload));
} }
public string RoadCommand(string uuid_route) public string RoadCommand(string uuid_route)
@@ -268,11 +392,12 @@ namespace RH_Engine
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
public string GetSceneInfoCommand() public string GetSceneInfoCommand(string serialToSend)
{ {
dynamic payload = new dynamic payload = new
{ {
id = "scene/get" id = "scene/get",
serial = serialToSend
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
@@ -282,7 +407,8 @@ namespace RH_Engine
{ {
dynamic payload = new dynamic payload = new
{ {
id = "scene/reset" id = "scene/reset",
serial = "reset"
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
@@ -295,7 +421,6 @@ namespace RH_Engine
throw new Exception("The time must be between 0 and 24!"); throw new Exception("The time must be between 0 and 24!");
} }
dynamic payload = new dynamic payload = new
{ {
id = "scene/skybox/settime", id = "scene/skybox/settime",
@@ -303,13 +428,10 @@ namespace RH_Engine
{ {
time = timeToSet time = timeToSet
} }
}; };
return JsonConvert.SerializeObject(Payload(payload)); return JsonConvert.SerializeObject(Payload(payload));
} }
private object Payload(dynamic message) private object Payload(dynamic message)
{ {
return new return new
@@ -322,8 +444,5 @@ namespace RH_Engine
} }
}; };
} }
} }
} }

View File

@@ -1,13 +1,9 @@
using System; using Newtonsoft.Json;
using System.Collections.Generic; using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using Newtonsoft.Json;
namespace RH_Engine namespace RH_Engine
{ {
class JSONParser public class JSONParser
{ {
/// <summary> /// <summary>
/// returns all the users from the given response /// returns all the users from the given response
@@ -27,21 +23,34 @@ namespace RH_Engine
} }
return res; 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) public static string GetSessionID(string msg, PC[] PCs)
{ {
dynamic jsonData = JsonConvert.DeserializeObject(msg); dynamic jsonData = JsonConvert.DeserializeObject(msg);
Newtonsoft.Json.Linq.JArray data = jsonData.data; Newtonsoft.Json.Linq.JArray data = jsonData.data;
for (int i = data.Count-1; i >= 0; i--) for (int i = data.Count - 1; i >= 0; i--)
{ {
dynamic d = data[i]; dynamic d = data[i];
foreach (PC pc in PCs) foreach (PC pc in PCs)
{ {
if (d.clientinfo.host == pc.host && d.clientinfo.user == pc.user) 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; return d.id;
} }
} }
@@ -50,6 +59,24 @@ namespace RH_Engine
return null; 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);
return jsonData.data.data.serial;
}
public static string GetID(string json)
{
dynamic d = JsonConvert.DeserializeObject(json);
return d.id;
}
public static string GetTunnelID(string json) public static string GetTunnelID(string json)
{ {
dynamic jsonData = JsonConvert.DeserializeObject(json); dynamic jsonData = JsonConvert.DeserializeObject(json);
@@ -60,15 +87,30 @@ namespace RH_Engine
return null; return null;
} }
public static string GetRouteID(string json) /// <summary>
/// method to get the uuid from requests for adding a node,route or road
/// </summary>
/// <param name="json">the json response froo the server</param>
/// <returns>the uuid of the created object</returns>
public static string GetResponseUuid(string json)
{ {
dynamic jsonData = JsonConvert.DeserializeObject(json); dynamic jsonData = JsonConvert.DeserializeObject(json);
if (jsonData.data.status == "ok") if (jsonData.data.data.status == "ok")
{ {
return jsonData.data.uuid; return jsonData.data.data.data.uuid;
} }
return null; return null;
} }
public static string getPanelID(string json)
{
dynamic jsonData = JsonConvert.DeserializeObject(json);
if (jsonData.data.data.data.name == "dashboard")
{
Console.WriteLine(jsonData.data.data.data.uuid);
return jsonData.data.data.data.uuid;
}
return null;
}
} }
} }

View File

@@ -1,35 +1,101 @@
using LibNoise.Primitive; using LibNoise.Primitive;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Globalization; using System.Collections.Generic;
using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.Intrinsics.X86;
using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Threading;
namespace RH_Engine namespace RH_Engine
{ {
public delegate void HandleSerial(string message);
internal class Program public class Program
{ {
private static PC[] PCs = { private static PC[] PCs = {
//new PC("DESKTOP-M2CIH87", "Fabian"), //new PC("DESKTOP-M2CIH87", "Fabian"),
new PC("T470S", "Shinichi"), //new PC("T470S", "Shinichi"),
//new PC("DESKTOP-DHS478C", "semme"), //new PC("DESKTOP-DHS478C", "semme"),
//new PC("HP-ZBOOK-SEM", "Sem"),
//new PC("DESKTOP-TV73FKO", "Wouter"), //new PC("DESKTOP-TV73FKO", "Wouter"),
//new PC("DESKTOP-SINMKT1", "Ralf"), new PC("DESKTOP-SINMKT1", "Ralf van Aert"),
//new PC("NA", "Bart") //new PC("NA", "Bart")
}; };
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<string, HandleSerial> serialResponses = new Dictionary<string, HandleSerial>();
private static void Main(string[] args) private static void Main(string[] args)
{ {
TcpClient client = new TcpClient("145.48.6.10", 6666); TcpClient client = new TcpClient("145.48.6.10", 6666);
CreateConnection(client.GetStream()); CreateConnection(client.GetStream());
}
/// <summary>
/// initializes and starts the reading of the responses from the vr server
/// </summary>
/// <param name="stream">the networkstream</param>
private static void initReader(NetworkStream stream)
{
serverResponseReader = new ServerResponseReader(stream);
serverResponseReader.callback = HandleResponse;
serverResponseReader.StartRead();
}
/// <summary>
/// callback method that handles responses from the server
/// </summary>
/// <param name="message">the response message from the server</param>
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
if (id == "session/list")
{
sessionId = JSONParser.GetSessionID(message, PCs);
}
else if (id == "tunnel/create")
{
tunnelId = JSONParser.GetTunnelID(message);
if (tunnelId == null)
{
Console.WriteLine("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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="stream">the networkstream to use</param>
/// <param name="message">the message to send</param>
/// <param name="serial">the serial to check for</param>
/// <param name="action">the code to be executed upon reveiving a reply from the server with the specified serial</param>
public static void SendMessageAndOnResponse(NetworkStream stream, string message, string serial, HandleSerial action)
{
serialResponses.Add(serial, action);
WriteTextMessage(stream, message);
} }
/// <summary> /// <summary>
@@ -50,62 +116,27 @@ namespace RH_Engine
//Console.WriteLine("sent message " + message); //Console.WriteLine("sent message " + message);
} }
/// <summary>
/// reads a response from the server
/// </summary>
/// <param name="stream">the network stream to use</param>
/// <returns>the returned message from the server</returns>
public static string ReadPrefMessage(NetworkStream stream)
{
byte[] lengthBytes = new byte[4];
stream.Read(lengthBytes, 0, 4);
Console.WriteLine("read message..");
int length = BitConverter.ToInt32(lengthBytes);
//Console.WriteLine("length is: " + length);
byte[] buffer = new byte[length];
int totalRead = 0;
//read bytes until stream indicates there are no more
do
{
int read = stream.Read(buffer, totalRead, buffer.Length - totalRead);
totalRead += read;
//Console.WriteLine("ReadMessage: " + read);
} while (totalRead < length);
return Encoding.UTF8.GetString(buffer, 0, totalRead);
}
/// <summary> /// <summary>
/// connects to the server and creates the tunnel /// connects to the server and creates the tunnel
/// </summary> /// </summary>
/// <param name="stream">the network stream to use</param> /// <param name="stream">the network stream to use</param>
private static void CreateConnection(NetworkStream stream) private static void CreateConnection(NetworkStream stream)
{ {
WriteTextMessage(stream, "{\r\n\"id\" : \"session/list\"\r\n}"); initReader(stream);
string id = JSONParser.GetSessionID(ReadPrefMessage(stream), PCs);
string tunnelCreate = "{\"id\" : \"tunnel/create\", \"data\" : {\"session\" : \"" + id + "\"}}"; 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); WriteTextMessage(stream, tunnelCreate);
string tunnelResponse = ReadPrefMessage(stream); // wait until we have a tunnel id
while (tunnelId == string.Empty) { }
Console.WriteLine(tunnelResponse); Console.WriteLine("got tunnel id! sending commands...");
sendCommands(stream, tunnelId);
string tunnelID = JSONParser.GetTunnelID(tunnelResponse);
if (tunnelID == null)
{
Console.WriteLine("could not find a valid tunnel id!");
return;
}
sendCommands(stream, tunnelID);
} }
/// <summary> /// <summary>
@@ -117,27 +148,83 @@ namespace RH_Engine
{ {
Command mainCommand = new Command(tunnelID); Command mainCommand = new Command(tunnelID);
// Reset scene
WriteTextMessage(stream, mainCommand.ResetScene()); WriteTextMessage(stream, mainCommand.ResetScene());
ReadPrefMessage(stream); //headId = GetId("Root", stream, mainCommand);
string routeid = CreateRoute(stream, mainCommand); //while (headId == string.Empty) { }
WriteTextMessage(stream, mainCommand.TerrainCommand(new int[] { 256, 256 }, null)); //Get sceneinfo
Console.WriteLine(ReadPrefMessage(stream)); SendMessageAndOnResponse(stream, mainCommand.GetSceneInfoCommand("sceneinfo"), "sceneinfo",
string command; (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");
command = mainCommand.AddBikeModel(); //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"));
});
WriteTextMessage(stream, command); //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));
Console.WriteLine(ReadPrefMessage(stream));
command = mainCommand.AddModel("car", "data\\customModels\\TeslaRoadster.fbx"); 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));
});
});
WriteTextMessage(stream, command);
Console.WriteLine(ReadPrefMessage(stream)); //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;
Console.WriteLine("id of head " + GetId(Command.STANDARD_HEAD, stream, mainCommand));
} }
/// <summary> /// <summary>
@@ -160,19 +247,6 @@ namespace RH_Engine
} }
Console.WriteLine("Could not find id of " + name); Console.WriteLine("Could not find id of " + name);
return null; return null;
}
public static string CreateRoute(NetworkStream stream, Command createGraphics)
{
WriteTextMessage(stream, createGraphics.RouteCommand());
dynamic response = JsonConvert.DeserializeObject(ReadPrefMessage(stream));
if (response.data.data.id == "route/add")
{
return response.data.data.data.uuid;
}
return null;
} }
public static void CreateTerrain(NetworkStream stream, Command createGraphics) public static void CreateTerrain(NetworkStream stream, Command createGraphics)
@@ -185,12 +259,9 @@ namespace RH_Engine
height[i] = improvedPerlin.GetValue(x / 10, x / 10, x * 100) + 1; height[i] = improvedPerlin.GetValue(x / 10, x / 10, x * 100) + 1;
x += 0.001f; x += 0.001f;
} }
WriteTextMessage(stream, createGraphics.TerrainCommand(new int[] { 256, 256 }, height)); WriteTextMessage(stream, createGraphics.TerrainCommand(new int[] { 256, 256 }, height));
Console.WriteLine(ReadPrefMessage(stream));
WriteTextMessage(stream, createGraphics.AddNodeCommand()); WriteTextMessage(stream, createGraphics.AddNodeCommand());
Console.WriteLine(ReadPrefMessage(stream));
} }
/// <summary> /// <summary>
@@ -201,9 +272,14 @@ namespace RH_Engine
/// <returns>all the children objects in the current scene</returns> /// <returns>all the children objects in the current scene</returns>
public static JArray GetChildren(NetworkStream stream, Command createGraphics) public static JArray GetChildren(NetworkStream stream, Command createGraphics)
{ {
WriteTextMessage(stream, createGraphics.GetSceneInfoCommand()); JArray res = null;
dynamic response = JsonConvert.DeserializeObject(ReadPrefMessage(stream)); SendMessageAndOnResponse(stream, createGraphics.GetSceneInfoCommand("getChildren"), "getChildren", (message) =>
return response.data.data.data.children; {
dynamic response = JsonConvert.DeserializeObject(message);
res = response.data.data.data.children;
});
while (res == null) { }
return res;
} }
/// <summary> /// <summary>
@@ -225,15 +301,31 @@ namespace RH_Engine
} }
return res; return res;
} }
public static string getUUIDFromResponse(string response) private static void SetFollowSpeed(float speed, NetworkStream stream, Command mainCommand)
{ {
dynamic JSON = JsonConvert.DeserializeObject(response); WriteTextMessage(stream, mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 }));
return JSON.data.data.data.uuid; 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);
}
}
);
} }
} }
/// <summary> /// <summary>
@@ -246,6 +338,7 @@ namespace RH_Engine
this.host = host; this.host = host;
this.user = user; this.user = user;
} }
public string host { get; } public string host { get; }
public string user { get; } public string user { get; }

View File

@@ -0,0 +1,8 @@
{
"profiles": {
"RH-Engine": {
"commandName": "Project",
"nativeDebugging": true
}
}
}

View File

@@ -0,0 +1,77 @@
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace RH_Engine
{
public delegate void OnResponse(string response);
public class ServerResponseReader
{
public OnResponse callback
{
get; set;
}
public NetworkStream Stream { get; }
public ServerResponseReader(NetworkStream stream)
{
this.Stream = stream;
}
public void StartRead()
{
Thread t = new Thread(() =>
{
if (this.callback == null)
{
throw new Exception("Callback not initialized!");
}
else
{
Console.WriteLine("[SERVERRESPONSEREADER] Starting loop for reading");
while (true)
{
string res = ReadPrefMessage(Stream);
//Console.WriteLine("[SERVERRESPONSEREADER] got message from server: " + res);
this.callback(res);
}
}
});
t.Start();
}
/// <summary>
/// reads a response from the server
/// </summary>
/// <param name="stream">the network stream to use</param>
/// <returns>the returned message from the server</returns>
public static string ReadPrefMessage(NetworkStream stream)
{
byte[] lengthBytes = new byte[4];
int streamread = stream.Read(lengthBytes, 0, 4);
//Console.WriteLine("read message.. " + streamread);
int length = BitConverter.ToInt32(lengthBytes);
//Console.WriteLine("length is: " + length);
byte[] buffer = new byte[length];
int totalRead = 0;
//read bytes until stream indicates there are no more
do
{
int read = stream.Read(buffer, totalRead, buffer.Length - totalRead);
totalRead += read;
//Console.WriteLine("ReadMessage: " + read);
} while (totalRead < length);
return Encoding.UTF8.GetString(buffer, 0, totalRead);
}
}
}

View File

@@ -1,8 +1,11 @@
using System; using System;
using System.IO;
using System.Linq; using System.Linq;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using Client;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Security.Cryptography;
namespace Server namespace Server
{ {
@@ -13,75 +16,217 @@ namespace Server
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[1024];
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[1024];
private int bytesReceived; private int totalBufferReceived = 0;
private SaveData saveData;
private string username = null;
private DateTime sessionStart;
private string fileName;
public string Username { get; set; } public string Username { get; set; }
public Client(Communication communication, TcpClient tcpClient) public Client(Communication communication, TcpClient tcpClient)
{ {
this.sessionStart = DateTime.Now;
this.communication = communication; this.communication = communication;
this.tcpClient = tcpClient; this.tcpClient = tcpClient;
this.stream = this.tcpClient.GetStream(); this.stream = this.tcpClient.GetStream();
this.fileName = Directory.GetCurrentDirectory() + "/userInfo.dat";
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
} }
private void OnRead(IAsyncResult ar) private void OnRead(IAsyncResult ar)
{ {
int receivedBytes = this.stream.EndRead(ar); int receivedBytes = this.stream.EndRead(ar);
byte[] lengthBytes = new byte[4];
Array.Copy(this.buffer, 0, lengthBytes, 0, 4); if (totalBufferReceived + receivedBytes > 1024)
int expectedMessageLength = BitConverter.ToInt32(lengthBytes);
if (expectedMessageLength > this.buffer.Length)
{ {
throw new OutOfMemoryException("buffer to small"); throw new OutOfMemoryException("buffer too small");
} }
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, receivedBytes);
totalBufferReceived += receivedBytes;
if (expectedMessageLength > this.bytesReceived + receivedBytes) int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{ {
//message hasn't completely arrived yet //volledig packet binnen
this.bytesReceived += receivedBytes; byte[] messageBytes = new byte[expectedMessageLength];
Console.WriteLine("segmented message, {0} arrived", receivedBytes); Array.Copy(totalBuffer, 0, messageBytes, 0, expectedMessageLength);
this.stream.BeginRead(this.buffer, this.bytesReceived, this.buffer.Length - this.bytesReceived, new AsyncCallback(OnRead), null); HandleData(messageBytes);
} Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength)); //maybe unsafe idk
else
{
//message completely arrived
if (expectedMessageLength != this.bytesReceived + receivedBytes)
{
Console.WriteLine("something has gone completely wrong");
Console.WriteLine($"expected: {expectedMessageLength} bytesReceive: {bytesReceived} receivedBytes: {receivedBytes}");
Console.WriteLine($"received WEIRD data {BitConverter.ToString(buffer.Take(receivedBytes).ToArray())} string {Encoding.ASCII.GetString(buffer.Take(receivedBytes).ToArray())}");
} totalBufferReceived -= expectedMessageLength;
else if (buffer[4] == 0x02) expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
if (expectedMessageLength <= 5)
{ {
Console.WriteLine($"received raw data {BitConverter.ToString(buffer.Skip(5).Take(expectedMessageLength).ToArray())}"); break;
} }
else if (buffer[4] == 0x01)
{
byte[] packet = new byte[expectedMessageLength];
Console.WriteLine(Encoding.ASCII.GetString(buffer) + " " + expectedMessageLength);
Array.Copy(buffer, 5, packet, 0, expectedMessageLength - 5);
Console.WriteLine(Encoding.ASCII.GetString(packet));
HandleData(Encoding.ASCII.GetString(packet));
}
this.bytesReceived = 0;
} }
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
} }
private void HandleData(string packet) private void OnWrite(IAsyncResult ar)
{ {
Console.WriteLine("Data " + packet); this.stream.EndWrite(ar);
JsonConvert.DeserializeObject(packet); }
/// <summary>
/// TODO
/// </summary>
/// <param name="message">including message length and messageId (can be changed)</param>
private void HandleData(byte[] message)
{
//Console.WriteLine("Data " + packet);
//JsonConvert.DeserializeObject(packet);
//0x01 Json
//0x01 Raw data
byte[] payloadbytes = new byte[BitConverter.ToInt32(message, 0) - 5];
Array.Copy(message, 5, payloadbytes, 0, payloadbytes.Length);
string identifier;
bool isJson = DataParser.getJsonIdentifier(message, out identifier);
if (isJson)
{
switch (identifier)
{
case DataParser.LOGIN:
string username;
string password;
bool worked = DataParser.GetUsernamePassword(payloadbytes, out username, out password);
if (worked)
{
if (verifyLogin(username, password))
{
Console.WriteLine("Log in");
this.username = username;
sendMessage(DataParser.getLoginResponse("OK"));
sendMessage(DataParser.getStartSessionJson());
}
else
{
sendMessage(DataParser.getLoginResponse("wrong username or password"));
}
}
else
{
sendMessage(DataParser.getLoginResponse("invalid json"));
}
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;
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;
}
saveData?.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes));
Array.Copy(message, 5, payloadbytes, 0, message.Length - 5);
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payloadbytes));
}
else if (DataParser.isRawData(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));
}
}
}
public void sendMessage(byte[] message)
{
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
}
private bool verifyLogin(string username, string 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(" ");
if (combo[0] == username)
{
Console.WriteLine("correct info");
return combo[1] == password;
}
}
Console.WriteLine("combo was not found in file");
}
Console.WriteLine("false");
return false;
}
private void newUsers(string username, string password)
{
Console.WriteLine("creating new entry in file");
using (StreamWriter sw = File.AppendText(fileName))
{
sw.WriteLine(username + " " + password);
}
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
} }
} }
} }

View File

@@ -1,6 +1,8 @@
using System; using Client;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO.Pipes; using System.IO.Pipes;
using System.Linq;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
@@ -10,6 +12,7 @@ namespace Server
{ {
private TcpListener listener; private TcpListener listener;
private List<Client> clients; private List<Client> clients;
private Client doctor;
public Communication(TcpListener listener) public Communication(TcpListener listener)
{ {
@@ -20,14 +23,27 @@ namespace Server
public void Start() public void Start()
{ {
listener.Start(); listener.Start();
Console.WriteLine($"==========================================================================\n" +
$"\tstarted accepting clients at {DateTime.Now}\n" +
$"==========================================================================");
listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null); listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
} }
private void OnConnect(IAsyncResult ar) private void OnConnect(IAsyncResult ar)
{ {
var tcpClient = listener.EndAcceptTcpClient(ar); var tcpClient = listener.EndAcceptTcpClient(ar);
Console.WriteLine($"Client connected from {tcpClient.Client.RemoteEndPoint}"); Console.WriteLine($"Client connected from {tcpClient.Client.RemoteEndPoint}");
clients.Add(new Client(this, tcpClient)); 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); listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
} }

126
Server/SaveData.cs Normal file
View File

@@ -0,0 +1,126 @@
using System;
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;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/// <summary>
/// Every line is a new data entry
/// </summary>
public void WriteDataJSON(string data)
{
using (StreamWriter sw = File.AppendText(this.path + jsonFilename))
{
sw.WriteLine(data);
}
}
public void WriteDataRAWBPM(byte[] data)
{
if (data.Length != 2)
{
throw new ArgumentException("data should have length of 2");
}
WriteRawData(data, this.path + rawBPMFilename);
}
public void WriteDataRAWBike(byte[] data)
{
if (data.Length != 8)
{
throw new ArgumentException("data should have length of 8");
}
WriteRawData(data, this.path + rawBikeFilename);
}
private void WriteRawData(byte[] data, string fileLocation)
{
int length = 0;
try
{
FileInfo fi = new FileInfo(fileLocation);
length = (int)fi.Length;
}
catch
{
// do nothing
}
using (BinaryWriter sw = new BinaryWriter(File.Open(fileLocation, FileMode.Create)))
{
sw.Seek(length, SeekOrigin.End);
sw.Write(data);
sw.Flush();
}
}
/// <summary>
/// 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
/// </summary>
/// <param name="outputSize">the amount of data points for the output</param>
/// <param name="averageOver">the amount of data points form the file for one data point in the output</param>
/// <returns>byte array with data points from file</returns>
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;
}
}
}
}

View File

@@ -1,12 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Client\Client.csproj" />
</ItemGroup>
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
</Project> </Project>