Compare commits
249 Commits
testResist
...
graph
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4afbbe4c38 | ||
|
|
749498ba5b | ||
|
|
ab9180281e | ||
|
|
a043cdc723 | ||
|
|
143f7e4d88 | ||
|
|
e09f4f1325 | ||
|
|
a23b268dc9 | ||
|
|
7bf5bdb1ce | ||
|
|
46083b3912 | ||
|
|
187beaf6c1 | ||
|
|
d6da6b18c4 | ||
|
|
04b0051e72 | ||
|
|
91bb0d65b7 | ||
|
|
fc0e70403f | ||
|
|
847fa68acb | ||
|
|
d7dfe32cc3 | ||
|
|
651a44762b | ||
|
|
6159f3f57b | ||
|
|
046389f3b7 | ||
|
|
57aa9b6deb | ||
|
|
acbe3e9d55 | ||
|
|
aea1b4fce4 | ||
|
|
6e2b3a80b3 | ||
|
|
26a784277a | ||
|
|
bff4718d3f | ||
|
|
499134fa9a | ||
|
|
f5eb59694e | ||
|
|
71ff5dfc81 | ||
|
|
472c514275 | ||
|
|
7c943f4f73 | ||
|
|
f31cdeb467 | ||
|
|
05354b5ebe | ||
|
|
f6c2b3c662 | ||
|
|
475159bbb2 | ||
|
|
c2b4b259a3 | ||
|
|
a2937c0427 | ||
|
|
02bd68d142 | ||
|
|
699528bb83 | ||
|
|
e4d192fb06 | ||
|
|
5d14d53df5 | ||
|
|
09db19246e | ||
|
|
eb2738168b | ||
|
|
d85c5ff935 | ||
|
|
d420bdc2a4 | ||
|
|
cb2435bf53 | ||
|
|
ca2e61eb8e | ||
|
|
32ef17365e | ||
|
|
fedf8c0e5b | ||
|
|
505c4907d0 | ||
|
|
a5e679e6fb | ||
|
|
3e5f6e46c4 | ||
|
|
adea08cfb7 | ||
|
|
c20a1b292e | ||
|
|
599b79ceee | ||
|
|
bd8994ad5b | ||
|
|
97f9d863aa | ||
|
|
f777b583f5 | ||
|
|
d6b938668f | ||
|
|
45edbe5936 | ||
|
|
a65c36b8d1 | ||
|
|
82f2d6b71c | ||
|
|
41e77ba16c | ||
|
|
6f1ab57fe4 | ||
|
|
341723d1d1 | ||
|
|
0cd3753b76 | ||
|
|
4388b39be5 | ||
|
|
0dc4bb6fad | ||
|
|
3ca3c1ad78 | ||
|
|
d06d621b13 | ||
|
|
7b05fcc898 | ||
|
|
cc7f2d154c | ||
|
|
c5b9a7ec09 | ||
|
|
3494f678e3 | ||
|
|
9a80dc6260 | ||
|
|
4cabce69d5 | ||
|
|
38886ca7c3 | ||
|
|
04e29402f7 | ||
|
|
78bb7f6a6c | ||
|
|
99887a22ba | ||
|
|
68a43fb930 | ||
|
|
dc4d3c852b | ||
|
|
13d99eb107 | ||
|
|
aa5f58e752 | ||
|
|
a353d6839e | ||
|
|
b6e4842cf8 | ||
|
|
1057c0caab | ||
|
|
21203fd3ff | ||
|
|
8160e1c158 | ||
|
|
9c3b2c3f9b | ||
|
|
d3a37d0238 | ||
|
|
bb30538f00 | ||
|
|
23846b14bc | ||
|
|
6ef5bbfe12 | ||
|
|
cf9341a93e | ||
|
|
23f146afdd | ||
|
|
fac3987678 | ||
|
|
d0071bd13c | ||
|
|
97e6a528bb | ||
|
|
80ee448acf | ||
|
|
8204f22fe7 | ||
|
|
22558e3289 | ||
|
|
360ec4175f | ||
|
|
506a074f36 | ||
|
|
96f2e6e973 | ||
|
|
2139fcf2b2 | ||
|
|
dded1a5b24 | ||
|
|
fb57a1779c | ||
|
|
64773ffe1c | ||
|
|
8c6cb443e3 | ||
|
|
81dcebb5e8 | ||
|
|
c782301cf2 | ||
|
|
d5eadbe529 | ||
|
|
d67c8448ad | ||
|
|
8e45c9a435 | ||
|
|
cd5f23d3e4 | ||
|
|
5f7f1c8510 | ||
|
|
cdaac839b9 | ||
|
|
f899c90ff7 | ||
|
|
c62b0224e1 | ||
|
|
be9553cc51 | ||
|
|
40cbff209b | ||
|
|
fd36e420d1 | ||
|
|
e315e1cf3f | ||
|
|
e0e910ac25 | ||
|
|
0bf41b5c07 | ||
|
|
de18ddc0f0 | ||
|
|
a8d7e03331 | ||
|
|
748f7eed46 | ||
|
|
674a10a779 | ||
|
|
797fb16465 | ||
|
|
60cf23d980 | ||
|
|
31ef1beb82 | ||
|
|
603703b3f6 | ||
|
|
1a67e97f75 | ||
|
|
28242ff052 | ||
|
|
a52f1ea7ed | ||
|
|
dcae307754 | ||
|
|
1041aa0391 | ||
|
|
b391583107 | ||
|
|
c63b51c22b | ||
|
|
1ce519f661 | ||
|
|
7df8d98ed9 | ||
|
|
fce99ff9ec | ||
|
|
a4bfac3de1 | ||
|
|
5762989f93 | ||
|
|
fe977deb46 | ||
|
|
541538d50a | ||
|
|
8f8490fe2a | ||
|
|
47cfe4efe6 | ||
|
|
5cd4e61194 | ||
|
|
84a80df9ca | ||
|
|
3f3a388ec1 | ||
|
|
360767b6a5 | ||
|
|
ddcc2171e0 | ||
|
|
b6be86b811 | ||
|
|
109b982931 | ||
|
|
688509dc66 | ||
|
|
02b180c246 | ||
|
|
d912f2dd31 | ||
|
|
6d0439fab3 | ||
|
|
6b78cf12a2 | ||
|
|
9f675844ed | ||
|
|
92d95eb6a6 | ||
|
|
b2163b0459 | ||
|
|
c837af0392 | ||
|
|
de7f667dd0 | ||
|
|
7842baafb4 | ||
|
|
12b4b90bc5 | ||
|
|
4a745ace75 | ||
|
|
f1d543dafc | ||
|
|
c69c3193d4 | ||
|
|
17eb3b1845 | ||
|
|
6eb2ac1a82 | ||
|
|
36a0177270 | ||
|
|
a5a61a8a83 | ||
|
|
b7f3f3542f | ||
|
|
f1066a365e | ||
|
|
99b4e7f426 | ||
|
|
3d72ed9694 | ||
|
|
037bb8a6cf | ||
|
|
1e7d679fc2 | ||
|
|
0a2a0405bf | ||
|
|
6e09b87f60 | ||
|
|
0d107a7170 | ||
|
|
1cda955254 | ||
|
|
ef0b293373 | ||
|
|
bc99bfd46b | ||
|
|
8fd3322c63 | ||
|
|
c82f1e9537 | ||
|
|
178bbb030c | ||
|
|
bb70d80409 | ||
|
|
e54cca454b | ||
|
|
e98bf569f9 | ||
|
|
a655646e80 | ||
|
|
0e2ee807e1 | ||
|
|
9ff2eb4e68 | ||
|
|
a8494bc4d2 | ||
|
|
2b80dbad47 | ||
|
|
7c7b64094b | ||
|
|
e32d103e61 | ||
|
|
4782ecf53a | ||
|
|
a9036e6fc2 | ||
|
|
189fc18448 | ||
|
|
2e19b4af92 | ||
|
|
fe05f7e71d | ||
|
|
5f65eb32fd | ||
|
|
c171f15316 | ||
|
|
0264370b38 | ||
|
|
39e4f655b1 | ||
|
|
87a370ee76 | ||
|
|
b9dc2b82a6 | ||
|
|
7b94cd77f9 | ||
|
|
ac45f1b454 | ||
|
|
2adfce27b0 | ||
|
|
bdbda2b570 | ||
|
|
5f18b3e772 | ||
|
|
631342ba04 | ||
|
|
cb1ca0b671 | ||
|
|
119f6384b6 | ||
|
|
f292310775 | ||
|
|
60ae9a3716 | ||
|
|
3307f57f36 | ||
|
|
359484baa3 | ||
|
|
4854dcb759 | ||
|
|
ae4fd1f093 | ||
|
|
ececffef3f | ||
|
|
5699f8678e | ||
|
|
758fef325e | ||
|
|
b0dc258455 | ||
|
|
d197d01971 | ||
|
|
86a5ddfbc4 | ||
|
|
7edb0ceded | ||
|
|
b70da1148e | ||
|
|
934507dd36 | ||
|
|
03dcd4c8b0 | ||
|
|
9dd292dafc | ||
|
|
34a3e409ab | ||
|
|
6beb031907 | ||
|
|
72c369a578 | ||
|
|
1c0958f33c | ||
|
|
dee370a4cb | ||
|
|
40f70a42d4 | ||
|
|
4ab46d94db | ||
|
|
e77372c913 | ||
|
|
a471854d71 | ||
|
|
6e07f3b33a | ||
|
|
45096558fb | ||
|
|
8dac69ebf9 | ||
|
|
5c29a9c064 |
292
Client/Client.cs
Normal file
292
Client/Client.cs
Normal file
@@ -0,0 +1,292 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using ProftaakRH;
|
||||
|
||||
namespace Client
|
||||
{
|
||||
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 EngineConnection engineConnection;
|
||||
private bool sessionRunning = false;
|
||||
private IHandler handler = null;
|
||||
|
||||
|
||||
public Client() : this("localhost", 5555)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Client(string adress, int port)
|
||||
{
|
||||
this.client = new TcpClient();
|
||||
this.connected = false;
|
||||
client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// initializes the VR engine and sets the callbacks
|
||||
/// </summary>
|
||||
private void initEngine()
|
||||
{
|
||||
engineConnection = EngineConnection.INSTANCE;
|
||||
engineConnection.OnNoTunnelId = retryEngineConnection;
|
||||
engineConnection.OnSuccessFullConnection = engineConnected;
|
||||
if (!engineConnection.Connected) engineConnection.Connect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// retries to connect to the VR engine if no tunnel id was found
|
||||
/// </summary>
|
||||
private void retryEngineConnection()
|
||||
{
|
||||
Console.WriteLine("-- Could not connect to the VR engine. Please make sure you are running the simulation!");
|
||||
Console.WriteLine("-- Press ENTER to retry connecting to the VR engine.");
|
||||
Console.WriteLine("-- Press 'q' and then ENTER to not connect to the VR engine");
|
||||
string input = Console.ReadLine();
|
||||
if (input == string.Empty) engineConnection.CreateConnection();
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Skipping connecting to VR engine...");
|
||||
engineConnection.Stop();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void engineConnected()
|
||||
{
|
||||
Console.WriteLine("successfully connected to VR engine");
|
||||
engineConnection.initScene();
|
||||
if (engineConnection.Connected && sessionRunning && !engineConnection.FollowingRoute) engineConnection.StartRouteFollow();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method for when the TCP client is connected
|
||||
/// </summary>
|
||||
/// <param name="ar">the result of the async read</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method for when there is a message read
|
||||
/// </summary>
|
||||
/// <param name="ar">the result of the async read</param>
|
||||
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")
|
||||
{
|
||||
Console.WriteLine("Username and password correct!");
|
||||
this.connected = true;
|
||||
//initEngine();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"login failed \"{responseStatus}\"");
|
||||
tryLogin();
|
||||
}
|
||||
break;
|
||||
case DataParser.START_SESSION:
|
||||
Console.WriteLine("Session started!");
|
||||
this.sessionRunning = true;
|
||||
if (engineConnection.Connected && !engineConnection.FollowingRoute) engineConnection.StartRouteFollow();
|
||||
sendMessage(DataParser.getStartSessionJson());
|
||||
break;
|
||||
case DataParser.STOP_SESSION:
|
||||
Console.WriteLine("Stop session identifier");
|
||||
this.sessionRunning = false;
|
||||
sendMessage(DataParser.getStopSessionJson());
|
||||
break;
|
||||
case DataParser.SET_RESISTANCE:
|
||||
Console.WriteLine("Set resistance identifier");
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// starts sending a message to the server
|
||||
/// </summary>
|
||||
/// <param name="message">the message to send</param>
|
||||
private void sendMessage(byte[] message)
|
||||
{
|
||||
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method for when a message is fully written to the server
|
||||
/// </summary>
|
||||
/// <param name="ar">the async result representing the asynchronous call</param>
|
||||
private void OnWrite(IAsyncResult ar)
|
||||
{
|
||||
this.stream.EndWrite(ar);
|
||||
}
|
||||
|
||||
#region interface
|
||||
//maybe move this to other place
|
||||
/// <summary>
|
||||
/// bpm method for receiving the BPM value from the bluetooth bike or the simulation
|
||||
/// </summary>
|
||||
/// <param name="bytes">the message</param>
|
||||
public void BPM(byte[] bytes)
|
||||
{
|
||||
if (!sessionRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
throw new ArgumentNullException("no bytes");
|
||||
}
|
||||
byte[] message = DataParser.GetRawDataMessage(bytes);
|
||||
|
||||
if (engineConnection.Connected && engineConnection.FollowingRoute)
|
||||
{
|
||||
engineConnection.BikeBPM = bytes[1];
|
||||
engineConnection.UpdateInfoPanel();
|
||||
}
|
||||
|
||||
|
||||
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// method for receiving the bike message from the bluetooth bike or the simulation
|
||||
/// </summary>
|
||||
/// <param name="bytes">the message</param>
|
||||
public void Bike(byte[] bytes)
|
||||
{
|
||||
if (!sessionRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
throw new ArgumentNullException("no bytes");
|
||||
}
|
||||
byte[] message = DataParser.GetRawDataMessage(bytes);
|
||||
switch (bytes[0])
|
||||
{
|
||||
case 0x10:
|
||||
|
||||
engineConnection.BikeSpeed = (bytes[4] | (bytes[5] << 8)) * 0.01f;
|
||||
break;
|
||||
case 0x19:
|
||||
engineConnection.BikePower = (bytes[5]) | (bytes[6] & 0b00001111) << 8;
|
||||
break;
|
||||
}
|
||||
if (engineConnection.Connected && engineConnection.FollowingRoute)
|
||||
engineConnection.UpdateInfoPanel();
|
||||
|
||||
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// wether or not the client stream is connected
|
||||
/// </summary>
|
||||
/// <returns>true if it's connected, false if not</returns>
|
||||
public bool IsConnected()
|
||||
{
|
||||
return this.connected;
|
||||
}
|
||||
/// <summary>
|
||||
/// tries to log in to the server by asking for a username and password
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sets the handler for the client, so either the bike simulator or the bluetooth bike handler
|
||||
/// </summary>
|
||||
/// <param name="handler"></param>
|
||||
public void setHandler(IHandler handler)
|
||||
{
|
||||
this.handler = handler;
|
||||
}
|
||||
}
|
||||
}
|
||||
20
Client/Client.csproj
Normal file
20
Client/Client.csproj
Normal file
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Message\Message.csproj" />
|
||||
<ProjectReference Include="..\ProftaakRH\ProftaakRH.csproj" />
|
||||
<ProjectReference Include="..\RH-Engine\RH-Engine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
|
||||
|
||||
</Project>
|
||||
206
Client/DataParser.cs
Normal file
206
Client/DataParser.cs
Normal 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 Client
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
313
Client/EngineConnection.cs
Normal file
313
Client/EngineConnection.cs
Normal file
@@ -0,0 +1,313 @@
|
||||
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 delegate void OnSuccessfullConnection();
|
||||
|
||||
public sealed class EngineConnection
|
||||
{
|
||||
private static EngineConnection instance = null;
|
||||
private static readonly object padlock = new object();
|
||||
public HandleNoTunnelId OnNoTunnelId;
|
||||
public OnSuccessfullConnection OnSuccessFullConnection;
|
||||
|
||||
|
||||
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 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;
|
||||
|
||||
public float BikeSpeed { get; set; }
|
||||
public float BikePower { get; set; }
|
||||
public float BikeBPM { get; set; }
|
||||
public float BikeResistance { get; set; }
|
||||
|
||||
public bool FollowingRoute = false;
|
||||
|
||||
private static NetworkStream stream;
|
||||
|
||||
private static Dictionary<string, HandleSerial> serialResponses = new Dictionary<string, HandleSerial>();
|
||||
private Command mainCommand;
|
||||
|
||||
public bool Connected = false;
|
||||
|
||||
EngineConnection()
|
||||
{
|
||||
BikeSpeed = 0;
|
||||
BikePower = 0;
|
||||
BikeBPM = 0;
|
||||
BikeResistance = 50;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Singleton constructor
|
||||
/// </summary>
|
||||
public static EngineConnection INSTANCE
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (padlock)
|
||||
{
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new EngineConnection();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// connects to the vr engine and initalizes the serverResponseReader
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
TcpClient client = new TcpClient("145.48.6.10", 6666);
|
||||
stream = client.GetStream();
|
||||
initReader();
|
||||
CreateConnection();
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
#region VR Message traffic
|
||||
/// <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);
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// <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);
|
||||
Console.WriteLine("set tunnel id to " + tunnelId);
|
||||
if (tunnelId == null)
|
||||
{
|
||||
Write("could not find a valid tunnel id!");
|
||||
OnNoTunnelId?.Invoke();
|
||||
Connected = false;
|
||||
FollowingRoute = false;
|
||||
return;
|
||||
} else
|
||||
{
|
||||
Write("got tunnel id! " + tunnelId);
|
||||
Connected = true;
|
||||
OnSuccessFullConnection?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public void initScene()
|
||||
{
|
||||
Write("initializing scene...");
|
||||
mainCommand = new Command(tunnelId);
|
||||
|
||||
// reset the scene
|
||||
WriteTextMessage(mainCommand.ResetScene());
|
||||
|
||||
//Get sceneinfo and set the id's
|
||||
SendMessageAndOnResponse(mainCommand.GetSceneInfoCommand("sceneinfo"), "sceneinfo",
|
||||
(message) =>
|
||||
{
|
||||
//Console.WriteLine("\r\n\r\n\r\nscene info" + message);
|
||||
cameraId = JSONParser.GetIdSceneInfoChild(message, "Camera");
|
||||
string headId = JSONParser.GetIdSceneInfoChild(message, "Head");
|
||||
string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand");
|
||||
string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand");
|
||||
|
||||
//Force(stream, mainCommand.DeleteNode(handLeftId, "deleteHandL"), "deleteHandL", (message) => Console.WriteLine("Left hand deleted"));
|
||||
//Force(stream, mainCommand.DeleteNode(handRightId, "deleteHandR"), "deleteHandR", (message) => Console.WriteLine("Right hand deleted"));
|
||||
});
|
||||
// add the route and set the route id
|
||||
SendMessageAndOnResponse(mainCommand.RouteCommand("routeID"), "routeID", (message) => routeId = JSONParser.GetResponseUuid(message));
|
||||
}
|
||||
|
||||
internal void StartRouteFollow()
|
||||
{
|
||||
Write("Starting route follow...");
|
||||
FollowingRoute = true;
|
||||
|
||||
SendMessageAndOnResponse(mainCommand.AddBikeModel("bikeID"), "bikeID",
|
||||
(message) =>
|
||||
{
|
||||
bikeId = JSONParser.GetResponseUuid(message);
|
||||
SendMessageAndOnResponse(mainCommand.addPanel("panelAdd", bikeId), "panelAdd",
|
||||
(message) =>
|
||||
{
|
||||
|
||||
panelId = JSONParser.getPanelID(message);
|
||||
|
||||
WriteTextMessage(mainCommand.ColorPanel(panelId));
|
||||
UpdateInfoPanel();
|
||||
|
||||
while (cameraId == string.Empty) { }
|
||||
SetFollowSpeed(5.0f);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void UpdateInfoPanel()
|
||||
{
|
||||
ShowPanel(BikeSpeed, (int)BikeBPM, (int)BikePower, (int)BikeResistance);
|
||||
WriteTextMessage(mainCommand.RouteSpeed(BikeSpeed, bikeId));
|
||||
WriteTextMessage(mainCommand.RouteSpeed(BikeSpeed, cameraId));
|
||||
}
|
||||
|
||||
public void ShowPanel(double bikeSpeed, int bpm, int power, int resistance)
|
||||
{
|
||||
WriteTextMessage(mainCommand.ClearPanel(panelId));
|
||||
|
||||
SendMessageAndOnResponse(mainCommand.showBikespeed(panelId, "bikeSpeed", bikeSpeed), "bikeSpeed",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(mainCommand.showHeartrate(panelId, "bpm", bpm), "bpm",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(mainCommand.showPower(panelId, "power", power), "power",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(mainCommand.showResistance(panelId, "resistance", resistance), "resistance",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
|
||||
// Check if every text is drawn!
|
||||
|
||||
WriteTextMessage(mainCommand.SwapPanel(panelId));
|
||||
}
|
||||
|
||||
private void SetFollowSpeed(float speed)
|
||||
{
|
||||
WriteTextMessage(mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 }));
|
||||
WriteTextMessage(mainCommand.RouteFollow(routeId, cameraId, speed));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region message send/receive
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (serialResponses.ContainsKey(serial))
|
||||
{
|
||||
serialResponses[serial] = action;
|
||||
} else
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
serverResponseReader.Stop();
|
||||
|
||||
}
|
||||
public void Write(string msg)
|
||||
{
|
||||
Console.WriteLine( "[ENGINECONNECT] " + msg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
44
Client/Program.cs
Normal file
44
Client/Program.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using Hardware;
|
||||
using Hardware.Simulators;
|
||||
using RH_Engine;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace Client
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine("// Connecting... //");
|
||||
//connect fiets?
|
||||
|
||||
Thread.Sleep(20000);
|
||||
Client client = new Client();
|
||||
|
||||
|
||||
while (!client.IsConnected())
|
||||
{
|
||||
|
||||
}
|
||||
//BLEHandler bLEHandler = new BLEHandler(client);
|
||||
|
||||
//bLEHandler.Connect();
|
||||
|
||||
//client.setHandler(bLEHandler);
|
||||
|
||||
|
||||
BikeSimulator bikeSimulator = new BikeSimulator(client);
|
||||
|
||||
bikeSimulator.StartSimulation();
|
||||
|
||||
client.setHandler(bikeSimulator);
|
||||
|
||||
while (true)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
18
ClientApp/App.xaml
Normal file
18
ClientApp/App.xaml
Normal file
@@ -0,0 +1,18 @@
|
||||
<Application x:Class="ClientApp.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:ClientApp"
|
||||
xmlns:viewModels="clr-namespace:ClientApp.ViewModels"
|
||||
xmlns:views="clr-namespace:ClientApp.Views"
|
||||
StartupUri="Views/MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
<DataTemplate DataType="{x:Type viewModels:MainViewModel}">
|
||||
<views:MainView />
|
||||
<!-- This is a UserControl -->
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type viewModels:LoginViewModel}">
|
||||
<views:LoginView />
|
||||
<!-- This is a UserControl -->
|
||||
</DataTemplate>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
17
ClientApp/App.xaml.cs
Normal file
17
ClientApp/App.xaml.cs
Normal 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 ClientApp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
10
ClientApp/AssemblyInfo.cs
Normal file
10
ClientApp/AssemblyInfo.cs
Normal 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)
|
||||
)]
|
||||
23
ClientApp/ClientApp.csproj
Normal file
23
ClientApp/ClientApp.csproj
Normal file
@@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AsyncAwaitBestPractices.MVVM" Version="4.3.0" />
|
||||
<PackageReference Include="MvvmLightLibsStd10" Version="5.4.1.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
<PackageReference Include="PropertyChanged.Fody" Version="3.2.9" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ProftaakRH\ProftaakRH.csproj" />
|
||||
<ProjectReference Include="..\RH-Engine\RH-Engine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
|
||||
|
||||
</Project>
|
||||
3
ClientApp/FodyWeavers.xml
Normal file
3
ClientApp/FodyWeavers.xml
Normal file
@@ -0,0 +1,3 @@
|
||||
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
||||
<PropertyChanged />
|
||||
</Weavers>
|
||||
74
ClientApp/FodyWeavers.xsd
Normal file
74
ClientApp/FodyWeavers.xsd
Normal file
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
|
||||
<xs:element name="Weavers">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="PropertyChanged" minOccurs="0" maxOccurs="1">
|
||||
<xs:complexType>
|
||||
<xs:attribute name="InjectOnPropertyNameChanged" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the On_PropertyName_Changed feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="TriggerDependentProperties" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the Dependent properties feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="EnableIsChangedProperty" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the IsChanged property feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="EventInvokerNames" type="xs:string">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to change the name of the method that fires the notify event. This is a string that accepts multiple values in a comma separated form.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="CheckForEquality" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should be inserted. If false, equality checking will be disabled for the project.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="CheckForEqualityUsingBaseEquals" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should use the Equals method resolved from the base class.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="UseStaticEqualsFromBase" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should use the static Equals method resolved from the base class.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="SuppressWarnings" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to turn off build warnings from this weaver.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="SuppressOnPropertyNameChangedWarning" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to turn off build warnings about mismatched On_PropertyName_Changed methods.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:all>
|
||||
<xs:attribute name="VerifyAssembly" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="VerifyIgnoreCodes" type="xs:string">
|
||||
<xs:annotation>
|
||||
<xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="GenerateXsd" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
14
ClientApp/Models/Info.cs
Normal file
14
ClientApp/Models/Info.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using ClientApp.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ClientApp.Models
|
||||
{
|
||||
class Info : ObservableObject
|
||||
{
|
||||
public bool ConnectedToServer { get; set; }
|
||||
public bool ConnectedToVREngine { get; set; }
|
||||
public bool DoctorConnected { get; set; }
|
||||
}
|
||||
}
|
||||
291
ClientApp/Utils/Client.cs
Normal file
291
ClientApp/Utils/Client.cs
Normal file
@@ -0,0 +1,291 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using ClientApp.ViewModels;
|
||||
using ProftaakRH;
|
||||
|
||||
namespace ClientApp.Utils
|
||||
{
|
||||
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 EngineConnection engineConnection;
|
||||
private bool sessionRunning = false;
|
||||
private IHandler handler = null;
|
||||
private LoginViewModel LoginViewModel;
|
||||
|
||||
|
||||
public Client() : this("localhost", 5555)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Client(string adress, int port)
|
||||
{
|
||||
this.client = new TcpClient();
|
||||
this.connected = false;
|
||||
client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// initializes the VR engine and sets the callbacks
|
||||
/// </summary>
|
||||
private void initEngine()
|
||||
{
|
||||
engineConnection = EngineConnection.INSTANCE;
|
||||
engineConnection.OnNoTunnelId = retryEngineConnection;
|
||||
engineConnection.OnSuccessFullConnection = engineConnected;
|
||||
if (!engineConnection.Connected) engineConnection.Connect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// retries to connect to the VR engine if no tunnel id was found
|
||||
/// </summary>
|
||||
private void retryEngineConnection()
|
||||
{
|
||||
Console.WriteLine("-- Could not connect to the VR engine. Please make sure you are running the simulation!");
|
||||
Console.WriteLine("-- Press ENTER to retry connecting to the VR engine.");
|
||||
Console.WriteLine("-- Press 'q' and then ENTER to not connect to the VR engine");
|
||||
string input = Console.ReadLine();
|
||||
if (input == string.Empty) engineConnection.CreateConnection();
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Skipping connecting to VR engine...");
|
||||
engineConnection.Stop();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void engineConnected()
|
||||
{
|
||||
Console.WriteLine("successfully connected to VR engine");
|
||||
engineConnection.initScene();
|
||||
if (engineConnection.Connected && sessionRunning && !engineConnection.FollowingRoute) engineConnection.StartRouteFollow();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method for when the TCP client is connected
|
||||
/// </summary>
|
||||
/// <param name="ar">the result of the async read</param>
|
||||
private void OnConnect(IAsyncResult ar)
|
||||
{
|
||||
this.client.EndConnect(ar);
|
||||
Console.WriteLine("TCP client Verbonden!");
|
||||
|
||||
|
||||
this.stream = this.client.GetStream();
|
||||
|
||||
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method for when there is a message read
|
||||
/// </summary>
|
||||
/// <param name="ar">the result of the async read</param>
|
||||
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")
|
||||
{
|
||||
Console.WriteLine("Username and password correct!");
|
||||
this.LoginViewModel.setLoginStatus(true);
|
||||
this.connected = true;
|
||||
initEngine();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"login failed \"{responseStatus}\"");
|
||||
}
|
||||
break;
|
||||
case DataParser.START_SESSION:
|
||||
Console.WriteLine("Session started!");
|
||||
this.sessionRunning = true;
|
||||
if (engineConnection.Connected && !engineConnection.FollowingRoute) engineConnection.StartRouteFollow();
|
||||
sendMessage(DataParser.getStartSessionJson());
|
||||
break;
|
||||
case DataParser.STOP_SESSION:
|
||||
Console.WriteLine("Stop session identifier");
|
||||
this.sessionRunning = false;
|
||||
sendMessage(DataParser.getStopSessionJson());
|
||||
break;
|
||||
case DataParser.SET_RESISTANCE:
|
||||
Console.WriteLine("Set resistance identifier");
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// starts sending a message to the server
|
||||
/// </summary>
|
||||
/// <param name="message">the message to send</param>
|
||||
private void sendMessage(byte[] message)
|
||||
{
|
||||
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method for when a message is fully written to the server
|
||||
/// </summary>
|
||||
/// <param name="ar">the async result representing the asynchronous call</param>
|
||||
private void OnWrite(IAsyncResult ar)
|
||||
{
|
||||
this.stream.EndWrite(ar);
|
||||
}
|
||||
|
||||
#region interface
|
||||
//maybe move this to other place
|
||||
/// <summary>
|
||||
/// bpm method for receiving the BPM value from the bluetooth bike or the simulation
|
||||
/// </summary>
|
||||
/// <param name="bytes">the message</param>
|
||||
public void BPM(byte[] bytes)
|
||||
{
|
||||
if (!sessionRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
throw new ArgumentNullException("no bytes");
|
||||
}
|
||||
byte[] message = DataParser.GetRawDataMessage(bytes);
|
||||
|
||||
if (engineConnection.Connected && engineConnection.FollowingRoute)
|
||||
{
|
||||
engineConnection.BikeBPM = bytes[1];
|
||||
engineConnection.UpdateInfoPanel();
|
||||
}
|
||||
|
||||
|
||||
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// method for receiving the bike message from the bluetooth bike or the simulation
|
||||
/// </summary>
|
||||
/// <param name="bytes">the message</param>
|
||||
public void Bike(byte[] bytes)
|
||||
{
|
||||
if (!sessionRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
throw new ArgumentNullException("no bytes");
|
||||
}
|
||||
byte[] message = DataParser.GetRawDataMessage(bytes);
|
||||
switch (bytes[0])
|
||||
{
|
||||
case 0x10:
|
||||
|
||||
engineConnection.BikeSpeed = (bytes[4] | (bytes[5] << 8)) * 0.01f;
|
||||
break;
|
||||
case 0x19:
|
||||
engineConnection.BikePower = (bytes[5]) | (bytes[6] & 0b00001111) << 8;
|
||||
break;
|
||||
}
|
||||
if (engineConnection.Connected && engineConnection.FollowingRoute)
|
||||
engineConnection.UpdateInfoPanel();
|
||||
|
||||
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// wether or not the client stream is connected
|
||||
/// </summary>
|
||||
/// <returns>true if it's connected, false if not</returns>
|
||||
public bool IsConnected()
|
||||
{
|
||||
return this.connected;
|
||||
}
|
||||
/// <summary>
|
||||
/// tries to log in to the server by asking for a username and password
|
||||
/// </summary>
|
||||
public void tryLogin(string username, string password)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sets the handler for the client, so either the bike simulator or the bluetooth bike handler
|
||||
/// </summary>
|
||||
/// <param name="handler"></param>
|
||||
public void SetHandler(IHandler handler)
|
||||
{
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
internal void SetLoginViewModel(LoginViewModel loginViewModel)
|
||||
{
|
||||
this.LoginViewModel = loginViewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
206
ClientApp/Utils/DataParser.cs
Normal file
206
ClientApp/Utils/DataParser.cs
Normal 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 ClientApp.Utils
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
315
ClientApp/Utils/EngineConnection.cs
Normal file
315
ClientApp/Utils/EngineConnection.cs
Normal file
@@ -0,0 +1,315 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RH_Engine;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ClientApp.Utils
|
||||
{
|
||||
public delegate void HandleSerial(string message);
|
||||
public delegate void HandleNoTunnelId();
|
||||
public delegate void OnSuccessfullConnection();
|
||||
|
||||
public sealed class EngineConnection
|
||||
{
|
||||
private static EngineConnection instance = null;
|
||||
private static readonly object padlock = new object();
|
||||
public HandleNoTunnelId OnNoTunnelId;
|
||||
public OnSuccessfullConnection OnSuccessFullConnection;
|
||||
|
||||
|
||||
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 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;
|
||||
|
||||
public float BikeSpeed { get; set; }
|
||||
public float BikePower { get; set; }
|
||||
public float BikeBPM { get; set; }
|
||||
public float BikeResistance { get; set; }
|
||||
|
||||
public bool FollowingRoute = false;
|
||||
|
||||
private static NetworkStream stream;
|
||||
|
||||
private static Dictionary<string, HandleSerial> serialResponses = new Dictionary<string, HandleSerial>();
|
||||
private Command mainCommand;
|
||||
|
||||
public bool Connected = false;
|
||||
|
||||
EngineConnection()
|
||||
{
|
||||
BikeSpeed = 0;
|
||||
BikePower = 0;
|
||||
BikeBPM = 0;
|
||||
BikeResistance = 50;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Singleton constructor
|
||||
/// </summary>
|
||||
public static EngineConnection INSTANCE
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (padlock)
|
||||
{
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new EngineConnection();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// connects to the vr engine and initalizes the serverResponseReader
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
TcpClient client = new TcpClient("145.48.6.10", 6666);
|
||||
stream = client.GetStream();
|
||||
initReader();
|
||||
CreateConnection();
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
#region VR Message traffic
|
||||
/// <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);
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// <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);
|
||||
Console.WriteLine("set tunnel id to " + tunnelId);
|
||||
if (tunnelId == null)
|
||||
{
|
||||
Write("could not find a valid tunnel id!");
|
||||
OnNoTunnelId?.Invoke();
|
||||
Connected = false;
|
||||
FollowingRoute = false;
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
Write("got tunnel id! " + tunnelId);
|
||||
Connected = true;
|
||||
OnSuccessFullConnection?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public void initScene()
|
||||
{
|
||||
Write("initializing scene...");
|
||||
mainCommand = new Command(tunnelId);
|
||||
|
||||
// reset the scene
|
||||
WriteTextMessage(mainCommand.ResetScene());
|
||||
|
||||
//Get sceneinfo and set the id's
|
||||
SendMessageAndOnResponse(mainCommand.GetSceneInfoCommand("sceneinfo"), "sceneinfo",
|
||||
(message) =>
|
||||
{
|
||||
//Console.WriteLine("\r\n\r\n\r\nscene info" + message);
|
||||
cameraId = JSONParser.GetIdSceneInfoChild(message, "Camera");
|
||||
string headId = JSONParser.GetIdSceneInfoChild(message, "Head");
|
||||
string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand");
|
||||
string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand");
|
||||
|
||||
//Force(stream, mainCommand.DeleteNode(handLeftId, "deleteHandL"), "deleteHandL", (message) => Console.WriteLine("Left hand deleted"));
|
||||
//Force(stream, mainCommand.DeleteNode(handRightId, "deleteHandR"), "deleteHandR", (message) => Console.WriteLine("Right hand deleted"));
|
||||
});
|
||||
// add the route and set the route id
|
||||
SendMessageAndOnResponse(mainCommand.RouteCommand("routeID"), "routeID", (message) => routeId = JSONParser.GetResponseUuid(message));
|
||||
}
|
||||
|
||||
internal void StartRouteFollow()
|
||||
{
|
||||
Write("Starting route follow...");
|
||||
FollowingRoute = true;
|
||||
|
||||
SendMessageAndOnResponse(mainCommand.AddBikeModel("bikeID"), "bikeID",
|
||||
(message) =>
|
||||
{
|
||||
bikeId = JSONParser.GetResponseUuid(message);
|
||||
SendMessageAndOnResponse(mainCommand.addPanel("panelAdd", bikeId), "panelAdd",
|
||||
(message) =>
|
||||
{
|
||||
|
||||
panelId = JSONParser.getPanelID(message);
|
||||
|
||||
WriteTextMessage(mainCommand.ColorPanel(panelId));
|
||||
UpdateInfoPanel();
|
||||
|
||||
while (cameraId == string.Empty) { }
|
||||
SetFollowSpeed(5.0f);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void UpdateInfoPanel()
|
||||
{
|
||||
ShowPanel(BikeSpeed, (int)BikeBPM, (int)BikePower, (int)BikeResistance);
|
||||
WriteTextMessage(mainCommand.RouteSpeed(BikeSpeed, bikeId));
|
||||
WriteTextMessage(mainCommand.RouteSpeed(BikeSpeed, cameraId));
|
||||
}
|
||||
|
||||
public void ShowPanel(double bikeSpeed, int bpm, int power, int resistance)
|
||||
{
|
||||
WriteTextMessage(mainCommand.ClearPanel(panelId));
|
||||
|
||||
SendMessageAndOnResponse(mainCommand.showBikespeed(panelId, "bikeSpeed", bikeSpeed), "bikeSpeed",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(mainCommand.showHeartrate(panelId, "bpm", bpm), "bpm",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(mainCommand.showPower(panelId, "power", power), "power",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(mainCommand.showResistance(panelId, "resistance", resistance), "resistance",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
|
||||
// Check if every text is drawn!
|
||||
|
||||
WriteTextMessage(mainCommand.SwapPanel(panelId));
|
||||
}
|
||||
|
||||
private void SetFollowSpeed(float speed)
|
||||
{
|
||||
WriteTextMessage(mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 }));
|
||||
WriteTextMessage(mainCommand.RouteFollow(routeId, cameraId, speed));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region message send/receive
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (serialResponses.ContainsKey(serial))
|
||||
{
|
||||
serialResponses[serial] = action;
|
||||
}
|
||||
else
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
serverResponseReader.Stop();
|
||||
|
||||
}
|
||||
public void Write(string msg)
|
||||
{
|
||||
Console.WriteLine("[ENGINECONNECT] " + msg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
12
ClientApp/Utils/ObservableObject.cs
Normal file
12
ClientApp/Utils/ObservableObject.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
|
||||
namespace ClientApp.Utils
|
||||
{
|
||||
public abstract class ObservableObject : INotifyPropertyChanged
|
||||
{
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
}
|
||||
}
|
||||
42
ClientApp/Utils/Program.cs
Normal file
42
ClientApp/Utils/Program.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using Hardware;
|
||||
using Hardware.Simulators;
|
||||
using RH_Engine;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace ClientApp.Utils
|
||||
{
|
||||
class Program
|
||||
{
|
||||
//static void Main(string[] args)
|
||||
//{
|
||||
// Console.WriteLine("// Connecting... //");
|
||||
// //connect fiets?
|
||||
|
||||
// Client client = new Client();
|
||||
|
||||
|
||||
// while (!client.IsConnected())
|
||||
// {
|
||||
|
||||
// }
|
||||
// //BLEHandler bLEHandler = new BLEHandler(client);
|
||||
|
||||
// //bLEHandler.Connect();
|
||||
|
||||
// //client.setHandler(bLEHandler);
|
||||
|
||||
|
||||
// BikeSimulator bikeSimulator = new BikeSimulator(client);
|
||||
|
||||
// bikeSimulator.StartSimulation();
|
||||
|
||||
// client.setHandler(bikeSimulator);
|
||||
|
||||
// while (true)
|
||||
// {
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
38
ClientApp/ViewModels/LoginViewModel.cs
Normal file
38
ClientApp/ViewModels/LoginViewModel.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using ClientApp.Utils;
|
||||
using GalaSoft.MvvmLight.Command;
|
||||
|
||||
namespace ClientApp.ViewModels
|
||||
{
|
||||
class LoginViewModel : ObservableObject
|
||||
{
|
||||
public string Username { get; set; }
|
||||
private MainWindowViewModel mainWindowViewModel;
|
||||
public LoginViewModel(MainWindowViewModel mainWindowViewModel)
|
||||
{
|
||||
this.mainWindowViewModel = mainWindowViewModel;
|
||||
LoginCommand = new RelayCommand<object>((parameter) =>
|
||||
{
|
||||
//TODO send username and password to server
|
||||
this.mainWindowViewModel.client.tryLogin(Username, ((PasswordBox)parameter).Password);
|
||||
});
|
||||
}
|
||||
|
||||
public ICommand LoginCommand { get; set; }
|
||||
|
||||
internal void setLoginStatus(bool status)
|
||||
{
|
||||
this.mainWindowViewModel.InfoModel.ConnectedToServer = true;
|
||||
if (status)
|
||||
{
|
||||
this.mainWindowViewModel.SelectedViewModel = new MainViewModel(mainWindowViewModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
30
ClientApp/ViewModels/MainViewModel.cs
Normal file
30
ClientApp/ViewModels/MainViewModel.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using ClientApp.Models;
|
||||
using ClientApp.Utils;
|
||||
using GalaSoft.MvvmLight.Command;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace ClientApp.ViewModels
|
||||
{
|
||||
class MainViewModel : ObservableObject
|
||||
{
|
||||
public ICommand RetryServerCommand { get; set; }
|
||||
public ICommand RetryVREngineCommand { get; set; }
|
||||
public MainWindowViewModel MainWindowViewModel;
|
||||
|
||||
|
||||
public MainViewModel(MainWindowViewModel mainWindowViewModel)
|
||||
{
|
||||
this.MainWindowViewModel = mainWindowViewModel;
|
||||
this.RetryServerCommand = new RelayCommand(() =>
|
||||
{
|
||||
//try connect server
|
||||
this.MainWindowViewModel.InfoModel.ConnectedToServer = true;
|
||||
});
|
||||
this.RetryVREngineCommand = new RelayCommand(() =>
|
||||
{
|
||||
//try connect vr-engine
|
||||
this.MainWindowViewModel.InfoModel.ConnectedToVREngine = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
26
ClientApp/ViewModels/MainWindowViewModel.cs
Normal file
26
ClientApp/ViewModels/MainWindowViewModel.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using ClientApp.Models;
|
||||
using ClientApp.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ClientApp.ViewModels
|
||||
{
|
||||
class MainWindowViewModel : ObservableObject
|
||||
{
|
||||
public Info InfoModel { get; set; }
|
||||
|
||||
public ObservableObject SelectedViewModel { get; set; }
|
||||
public Client client { get; }
|
||||
|
||||
public MainWindowViewModel(Client client)
|
||||
{
|
||||
this.InfoModel = new Info();
|
||||
this.client = client;
|
||||
LoginViewModel loginViewModel = new LoginViewModel(this);
|
||||
SelectedViewModel = loginViewModel;
|
||||
this.client.SetLoginViewModel(loginViewModel);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
18
ClientApp/Views/LoginView.xaml
Normal file
18
ClientApp/Views/LoginView.xaml
Normal file
@@ -0,0 +1,18 @@
|
||||
<UserControl x:Class="ClientApp.Views.LoginView"
|
||||
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:ClientApp.Views"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="450" d:DesignWidth="800">
|
||||
<DockPanel>
|
||||
<StackPanel VerticalAlignment="Center" Width="auto">
|
||||
<Label Content="Username" HorizontalContentAlignment="Center" />
|
||||
<TextBox x:Name="Username" Text="{Binding Username}" TextWrapping="Wrap" Width="120"/>
|
||||
<Label Content="Password" HorizontalContentAlignment="Center"/>
|
||||
<PasswordBox x:Name="Password" Width="120"/>
|
||||
<Button x:Name="Login" Content="Login" Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=Password}" Margin="0,20,0,0" Width="120"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
26
ClientApp/Views/LoginView.xaml.cs
Normal file
26
ClientApp/Views/LoginView.xaml.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
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 ClientApp.Views
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for LoginView.xaml
|
||||
/// </summary>
|
||||
public partial class LoginView : UserControl
|
||||
{
|
||||
public LoginView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
52
ClientApp/Views/MainView.xaml
Normal file
52
ClientApp/Views/MainView.xaml
Normal file
@@ -0,0 +1,52 @@
|
||||
<UserControl x:Class="ClientApp.Views.MainView"
|
||||
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:ClientApp.Views"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="450" d:DesignWidth="800">
|
||||
<DockPanel>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition/>
|
||||
<RowDefinition/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<StackPanel Grid.Column="0" Grid.Row="0" Orientation="Horizontal" Margin="10">
|
||||
<Label Content="Connected to server:"/>
|
||||
<Label Content="{Binding Path=MainWindowViewModel.InfoModel.ConnectedToServer}"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="1" Grid.Row="0" Orientation="Horizontal" Margin="10">
|
||||
<Label Content="Connected to VR-Engine:"/>
|
||||
<Label Content="{Binding Path=MainWindowViewModel.InfoModel.ConnectedToVREngine}"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="2" Grid.Row="0" Orientation="Horizontal" Margin="10">
|
||||
<Label Content="Doctor connected:"/>
|
||||
<Label Content="{Binding Path=MainWindowViewModel.InfoModel.DoctorConnected}"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Column="0" Grid.Row="1" Command="{Binding RetryServerCommand}" Width="50" Height="20">
|
||||
<Button.Content>
|
||||
<TextBlock TextWrapping="Wrap" Text="retry"/>
|
||||
</Button.Content>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="1" Grid.Row="1" Command="{Binding RetryVREngineCommand}" Width="50" Height="20">
|
||||
<Button.Content>
|
||||
<TextBlock TextWrapping="Wrap" Text="retry"/>
|
||||
</Button.Content>
|
||||
</Button>
|
||||
|
||||
</Grid>
|
||||
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
27
ClientApp/Views/MainView.xaml.cs
Normal file
27
ClientApp/Views/MainView.xaml.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using ClientApp.ViewModels;
|
||||
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 ClientApp.Views
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainView.xaml
|
||||
/// </summary>
|
||||
public partial class MainView : UserControl
|
||||
{
|
||||
public MainView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
16
ClientApp/Views/MainWindow.xaml
Normal file
16
ClientApp/Views/MainWindow.xaml
Normal file
@@ -0,0 +1,16 @@
|
||||
<Window x:Class="ClientApp.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:ClientApp"
|
||||
xmlns:views="clr-namespace:ClientApp.Views"
|
||||
mc:Ignorable="d"
|
||||
Title="Whaazzzzuuuuuuuup" Height="450" Width="800">
|
||||
|
||||
|
||||
<DockPanel>
|
||||
<Label Content="gemaakt door: mensen" DockPanel.Dock="Bottom" HorizontalAlignment="Right" VerticalAlignment="Bottom" FontStyle="Italic" Foreground="Gray"/>
|
||||
<ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Content="{Binding SelectedViewModel}" />
|
||||
</DockPanel>
|
||||
</Window>
|
||||
54
ClientApp/Views/MainWindow.xaml.cs
Normal file
54
ClientApp/Views/MainWindow.xaml.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using ClientApp.ViewModels;
|
||||
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;
|
||||
using ClientApp.Utils;
|
||||
using Hardware.Simulators;
|
||||
using System.Threading;
|
||||
|
||||
namespace ClientApp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
Client client = new Client();
|
||||
|
||||
|
||||
InitializeComponent();
|
||||
DataContext = new MainWindowViewModel(client);
|
||||
|
||||
|
||||
//BLEHandler bLEHandler = new BLEHandler(client);
|
||||
|
||||
//bLEHandler.Connect();
|
||||
|
||||
//client.setHandler(bLEHandler);
|
||||
|
||||
|
||||
BikeSimulator bikeSimulator = new BikeSimulator(client);
|
||||
|
||||
Thread newThread = new Thread(new ThreadStart(bikeSimulator.StartSimulation));
|
||||
newThread.Start();
|
||||
|
||||
|
||||
client.SetHandler(bikeSimulator);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
9
DokterApp/App.xaml
Normal file
9
DokterApp/App.xaml
Normal 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
17
DokterApp/App.xaml.cs
Normal 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
10
DokterApp/AssemblyInfo.cs
Normal 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
196
DokterApp/Client.cs
Normal 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
206
DokterApp/DataParser.cs
Normal 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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
20
DokterApp/DokterApp.csproj
Normal file
20
DokterApp/DokterApp.csproj
Normal 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
28
DokterApp/ITab.cs
Normal 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
29
DokterApp/MainWindow.xaml
Normal 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>
|
||||
54
DokterApp/MainWindow.xaml.cs
Normal file
54
DokterApp/MainWindow.xaml.cs
Normal 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);
|
||||
}
|
||||
92
DokterApp/UserControlForTab.xaml
Normal file
92
DokterApp/UserControlForTab.xaml
Normal file
@@ -0,0 +1,92 @@
|
||||
<UserControl x:Class="DokterApp.UserControlForTab"
|
||||
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
|
||||
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"
|
||||
xmlns:constantChanges="clr-namespace:DokterApp"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="450" d:DesignWidth="800" d:DataContext="{d:DesignInstance constantChanges:UserControlForTab}">
|
||||
<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"/>
|
||||
<lvc:CartesianChart Grid.Row="3" AnimationsSpeed="0:0:0.5" Hoverable="False" DataTooltip="{x:Null}" Margin="-10,33,10,0">
|
||||
<lvc:CartesianChart.Series>
|
||||
<lvc:LineSeries Values="{Binding ChartValues}"
|
||||
PointGeometry="{x:Null}"
|
||||
LineSmoothness="1"
|
||||
StrokeThickness="6"
|
||||
Stroke="#F34336"
|
||||
Fill="Transparent"/>
|
||||
</lvc:CartesianChart.Series>
|
||||
<lvc:CartesianChart.AxisX>
|
||||
<lvc:Axis LabelFormatter="{Binding DateTimeFormatter}"
|
||||
MaxValue="{Binding AxisMax}"
|
||||
MinValue="{Binding AxisMin}"
|
||||
Unit="{Binding AxisUnit}">
|
||||
<lvc:Axis.Separator>
|
||||
<lvc:Separator Step="{Binding AxisStep}" />
|
||||
</lvc:Axis.Separator>
|
||||
</lvc:Axis>
|
||||
</lvc:CartesianChart.AxisX>
|
||||
</lvc:CartesianChart>
|
||||
<ComboBox Name="DropBox" HorizontalAlignment="Left" Margin="0,6,0,0" Grid.Row="3" VerticalAlignment="Top" Width="190" SelectionChanged="InjectStopOnClick">
|
||||
<ComboBoxItem Content="Speed"/>
|
||||
<ComboBoxItem Content="BPM"/>
|
||||
<ComboBoxItem Content="Resistance"/>
|
||||
</ComboBox>
|
||||
<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>
|
||||
190
DokterApp/UserControlForTab.xaml.cs
Normal file
190
DokterApp/UserControlForTab.xaml.cs
Normal file
@@ -0,0 +1,190 @@
|
||||
using LiveCharts;
|
||||
using LiveCharts.Configurations;
|
||||
using LiveCharts.Wpf;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
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 UserControlForTab.xaml
|
||||
/// </summary>
|
||||
public partial class UserControlForTab : UserControl, INotifyPropertyChanged
|
||||
{
|
||||
|
||||
private double _axisMax;
|
||||
private double _axisMin;
|
||||
private double _trend;
|
||||
public UserControlForTab()
|
||||
{
|
||||
InitializeComponent();
|
||||
Username_Label.Content = "Bob";
|
||||
Status_Label.Content = "Status: Dead";
|
||||
|
||||
//To handle live data easily, in this case we built a specialized type
|
||||
//the MeasureModel class, it only contains 2 properties
|
||||
//DateTime and Value
|
||||
//We need to configure LiveCharts to handle MeasureModel class
|
||||
//The next code configures MeasureModel globally, this means
|
||||
//that LiveCharts learns to plot MeasureModel and will use this config every time
|
||||
//a IChartValues instance uses this type.
|
||||
//this code ideally should only run once
|
||||
//you can configure series in many ways, learn more at
|
||||
//http://lvcharts.net/App/examples/v1/wpf/Types%20and%20Configuration
|
||||
|
||||
var mapper = Mappers.Xy<MeasureModel>()
|
||||
.X(model => model.DateTime.Ticks) //use DateTime.Ticks as X
|
||||
.Y(model => model.Value); //use the value property as Y
|
||||
|
||||
//lets save the mapper globally.
|
||||
Charting.For<MeasureModel>(mapper);
|
||||
|
||||
//the values property will store our values array
|
||||
ChartValues = new ChartValues<MeasureModel>();
|
||||
|
||||
//lets set how to display the X Labels
|
||||
DateTimeFormatter = value => new DateTime((long)value).ToString("mm:ss");
|
||||
|
||||
//AxisStep forces the distance between each separator in the X axis
|
||||
AxisStep = TimeSpan.FromSeconds(1).Ticks;
|
||||
//AxisUnit forces lets the axis know that we are plotting seconds
|
||||
//this is not always necessary, but it can prevent wrong labeling
|
||||
AxisUnit = TimeSpan.TicksPerSecond;
|
||||
|
||||
SetAxisLimits(DateTime.Now);
|
||||
|
||||
//The next code simulates data changes every 300 ms
|
||||
|
||||
IsReading = false;
|
||||
|
||||
DataContext = this;
|
||||
}
|
||||
|
||||
public double AxisMax
|
||||
{
|
||||
get { return _axisMax; }
|
||||
set
|
||||
{
|
||||
_axisMax = value;
|
||||
OnPropertyChanged("AxisMax");
|
||||
}
|
||||
}
|
||||
public double AxisMin
|
||||
{
|
||||
get { return _axisMin; }
|
||||
set
|
||||
{
|
||||
_axisMin = value;
|
||||
OnPropertyChanged("AxisMin");
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsReading { get; set; }
|
||||
|
||||
private void Read()
|
||||
{
|
||||
var r = new Random();
|
||||
|
||||
while (IsReading)
|
||||
{
|
||||
Thread.Sleep(150);
|
||||
var now = DateTime.Now;
|
||||
|
||||
_trend += r.Next(-8, 10);
|
||||
|
||||
ChartValues.Add(new MeasureModel
|
||||
{
|
||||
DateTime = now,
|
||||
Value = _trend
|
||||
});
|
||||
|
||||
SetAxisLimits(now);
|
||||
|
||||
//lets only use the last 150 values
|
||||
if (ChartValues.Count > 150) ChartValues.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetAxisLimits(DateTime now)
|
||||
{
|
||||
AxisMax = now.Ticks + TimeSpan.FromSeconds(1).Ticks; // lets force the axis to be 1 second ahead
|
||||
AxisMin = now.Ticks - TimeSpan.FromSeconds(8).Ticks; // and 8 seconds behind
|
||||
}
|
||||
|
||||
private void InjectStopOnClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
IsReading = !IsReading;
|
||||
if (IsReading) Task.Factory.StartNew(Read);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
|
||||
protected virtual void OnPropertyChanged(string propertyName = null)
|
||||
{
|
||||
if (PropertyChanged != null)
|
||||
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
|
||||
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" +
|
||||
"Lastname:\t\tde Bouwer");
|
||||
}
|
||||
|
||||
private void DropBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
//TODO
|
||||
//Andere graph
|
||||
}
|
||||
|
||||
public ChartValues<MeasureModel> ChartValues { get; set; }
|
||||
public Func<double, string> DateTimeFormatter { get; set; }
|
||||
public double AxisStep { get; set; }
|
||||
public double AxisUnit { get; set; }
|
||||
}
|
||||
|
||||
public class MeasureModel
|
||||
{
|
||||
public DateTime DateTime { get; set; }
|
||||
public double Value { get; set; }
|
||||
}
|
||||
}
|
||||
14
DokterApp/UserTab.cs
Normal file
14
DokterApp/UserTab.cs
Normal 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
16
DokterApp/WindowTabs.xaml
Normal 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>
|
||||
53
DokterApp/WindowTabs.xaml.cs
Normal file
53
DokterApp/WindowTabs.xaml.cs
Normal 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
BIN
DokterApp/favicon (1).ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
27
Hashing/Hasher.cs
Normal file
27
Hashing/Hasher.cs
Normal 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
14
Hashing/Hashing.projitems
Normal 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
13
Hashing/Hashing.shproj
Normal 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>
|
||||
71
Message/Message.cs
Normal file
71
Message/Message.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace Message
|
||||
{
|
||||
/// <summary>
|
||||
/// Message class to handle traffic between clients and server
|
||||
/// </summary>
|
||||
public class Message
|
||||
{
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// identifier for the message
|
||||
/// </summary>
|
||||
public Identifier Identifier
|
||||
{
|
||||
get;set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// payload of the message, the actual text
|
||||
/// </summary>
|
||||
public string Payload
|
||||
{
|
||||
get;set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// constructs a new message with the given parameters
|
||||
/// </summary>
|
||||
/// <param name="identifier">the identifier</param>
|
||||
/// <param name="payload">the payload</param>
|
||||
public Message(Identifier identifier, string payload)
|
||||
{
|
||||
this.Identifier = identifier;
|
||||
this.Payload = payload;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// serializes this object to a JSON string
|
||||
/// </summary>
|
||||
/// <returns>a JSON representation of this object</returns>
|
||||
public string Serialize()
|
||||
{
|
||||
return JsonConvert.SerializeObject(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// deserializes a JSON string into a new Message object
|
||||
/// </summary>
|
||||
/// <param name="json">the JSON string to deserialize</param>
|
||||
/// <returns>a new <c>Message</c> object from the JSON string</returns>
|
||||
public static Message Deserialize(string json)
|
||||
{
|
||||
return (Message)JsonConvert.DeserializeObject(json);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Identifier enum for the Message objects
|
||||
/// </summary>
|
||||
public enum Identifier
|
||||
{
|
||||
LOGIN,
|
||||
CHAT,
|
||||
}
|
||||
}
|
||||
12
Message/Message.csproj
Normal file
12
Message/Message.csproj
Normal file
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -4,25 +4,49 @@ using System.Text;
|
||||
using Avans.TI.BLE;
|
||||
using System.Threading;
|
||||
using System.Security.Cryptography;
|
||||
using ProftaakRH;
|
||||
|
||||
namespace Hardware
|
||||
{
|
||||
class BLEHandler
|
||||
/// <summary>
|
||||
/// <c>BLEHandler</c> class that handles connection and traffic to and from the bike
|
||||
/// </summary>
|
||||
public class BLEHandler : IHandler
|
||||
{
|
||||
IDataConverter dataConverter;
|
||||
List<IDataReceiver> dataReceivers;
|
||||
private BLE bleBike;
|
||||
private BLE bleHeart;
|
||||
public bool Running { get; set; }
|
||||
|
||||
public BLEHandler(IDataConverter dataConverter)
|
||||
/// <summary>
|
||||
/// Makes a new BLEHandler object
|
||||
/// </summary>
|
||||
/// <param name="dataReceiver">the dataconverter object</param>
|
||||
public BLEHandler(IDataReceiver dataReceiver)
|
||||
{
|
||||
this.dataConverter = dataConverter;
|
||||
bool running = false;
|
||||
this.dataReceivers = new List<IDataReceiver> { dataReceiver };
|
||||
|
||||
}
|
||||
|
||||
public BLEHandler(List<IDataReceiver> dataReceivers)
|
||||
{
|
||||
this.dataReceivers = dataReceivers;
|
||||
|
||||
}
|
||||
|
||||
public void addDataReceiver(IDataReceiver dataReceiver)
|
||||
{
|
||||
this.dataReceivers.Add(dataReceiver);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks for available devices to connect to, and if one is found, it connects to it
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
|
||||
BLE bleBike = new BLE();
|
||||
|
||||
Thread.Sleep(1000); // We need some time to list available devices
|
||||
|
||||
// List available devices
|
||||
@@ -40,6 +64,11 @@ namespace Hardware
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the device with the given name
|
||||
/// </summary>
|
||||
/// <param name="deviceName">The name of the device to connect to</param>
|
||||
public async void Connect(string deviceName)
|
||||
{
|
||||
int errorCode = 0;
|
||||
@@ -95,23 +124,32 @@ namespace Hardware
|
||||
|
||||
Console.WriteLine("connected to BLE");
|
||||
this.Running = true;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback for when the subscription value of the ble bike has changed
|
||||
/// </summary>
|
||||
/// <param name="sender"> the sender object</param>
|
||||
/// <param name="e">the value changed event</param>
|
||||
private void BleBike_SubscriptionValueChanged(object sender, BLESubscriptionValueChangedEventArgs e)
|
||||
{
|
||||
//Console.WriteLine("Received from {0}: {1}", e.ServiceName,
|
||||
// BitConverter.ToString(e.Data).Replace("-", " "));
|
||||
//send to dataconverter
|
||||
|
||||
if (e.ServiceName == "6e40fec2-b5a3-f393-e0a9-e50e24dcca9e")
|
||||
{
|
||||
byte[] payload = new byte[8];
|
||||
Array.Copy(e.Data, 4, payload, 0, 8);
|
||||
this.dataConverter.Bike(payload);
|
||||
foreach (IDataReceiver dataReceiver in this.dataReceivers)
|
||||
{
|
||||
dataReceiver.Bike(payload);
|
||||
}
|
||||
}
|
||||
else if (e.ServiceName == "00002a37-0000-1000-8000-00805f9b34fb")
|
||||
{
|
||||
this.dataConverter.BPM(e.Data);
|
||||
foreach (IDataReceiver dataReceiver in this.dataReceivers)
|
||||
{
|
||||
dataReceiver.BPM(e.Data);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -120,6 +158,9 @@ namespace Hardware
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of the current BLE object, if it exists.
|
||||
/// </summary>
|
||||
private void disposeBLE()
|
||||
{
|
||||
this.bleBike?.Dispose();
|
||||
@@ -127,8 +168,17 @@ namespace Hardware
|
||||
this.Running = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method <c>setResistance</c> converts the input percentage to bytes and sends it to the bike.
|
||||
/// </summary>
|
||||
/// <param name="percentage">The precentage of resistance to set</param>
|
||||
public void setResistance(float percentage)
|
||||
{
|
||||
if (!this.Running)
|
||||
{
|
||||
Console.WriteLine("BLE is not running");
|
||||
return;
|
||||
}
|
||||
byte[] antMessage = new byte[13];
|
||||
antMessage[0] = 0x4A;
|
||||
antMessage[1] = 0x09;
|
||||
@@ -140,7 +190,7 @@ namespace Hardware
|
||||
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++)
|
||||
@@ -151,7 +201,7 @@ namespace Hardware
|
||||
antMessage[12] = checksum;//reminder that i am dumb :P
|
||||
|
||||
|
||||
bleBike.WriteCharacteristic("6E40FEC3-B5A3-F393-E0A9-E50E24DCCA9E", antMessage);
|
||||
bleBike.WriteCharacteristic("6e40fec3-b5a3-f393-e0a9-e50e24dcca9e", antMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using LibNoise.Primitive;
|
||||
using ProftaakRH;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -9,9 +10,9 @@ using System.Threading;
|
||||
|
||||
namespace Hardware.Simulators
|
||||
{
|
||||
class BikeSimulator : IHandler
|
||||
public class BikeSimulator : IHandler
|
||||
{
|
||||
IDataConverter dataConverter;
|
||||
List<IDataReceiver> dataReceivers;
|
||||
private int elapsedTime = 0;
|
||||
private int eventCounter = 0;
|
||||
private double distanceTraveled = 0;
|
||||
@@ -20,33 +21,52 @@ namespace Hardware.Simulators
|
||||
private int BPM = 0;
|
||||
private int cadence = 0;
|
||||
private double resistance = 0;
|
||||
private double power;
|
||||
private double accPower;
|
||||
|
||||
byte[] array;
|
||||
byte[] speedArray;
|
||||
byte[] powerArray;
|
||||
byte[] accPowerArray;
|
||||
|
||||
|
||||
|
||||
public BikeSimulator(IDataConverter dataConverter)
|
||||
public BikeSimulator(IDataReceiver dataReceiver)
|
||||
{
|
||||
this.dataConverter = dataConverter;
|
||||
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()
|
||||
{
|
||||
Console.WriteLine("simulating bike...");
|
||||
//Example BLE Message
|
||||
//4A-09-4E-05-19-16-00-FF-28-00-00-20-F0
|
||||
|
||||
float x = 0.0f;
|
||||
|
||||
//Perlin for Random values
|
||||
ImprovedPerlin improvedPerlin = new ImprovedPerlin(0,LibNoise.NoiseQuality.Best);
|
||||
ImprovedPerlin improvedPerlin = new ImprovedPerlin(0, LibNoise.NoiseQuality.Best);
|
||||
|
||||
while (true)
|
||||
{
|
||||
CalculateVariables(improvedPerlin.GetValue(x)+1);
|
||||
CalculateVariables(improvedPerlin.GetValue(x) + 1);
|
||||
|
||||
//Simulate sending data
|
||||
dataConverter.Bike(GenerateBike0x19());
|
||||
dataConverter.Bike(GenerateBike0x10());
|
||||
dataConverter.BPM(GenerateHeart());
|
||||
foreach (IDataReceiver dataReceiver in this.dataReceivers)
|
||||
{
|
||||
dataReceiver.Bike(GenerateBike0x19());
|
||||
dataReceiver.Bike(GenerateBike0x10());
|
||||
dataReceiver.BPM(GenerateHeart());
|
||||
}
|
||||
|
||||
Thread.Sleep(1000);
|
||||
|
||||
@@ -60,79 +80,50 @@ namespace Hardware.Simulators
|
||||
//Generate an ANT message for page 0x19
|
||||
private byte[] GenerateBike0x19()
|
||||
{
|
||||
byte[] bikeByte = { 0x19, Convert.ToByte(eventCounter%256), 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
|
||||
byte statByte = (byte)(powerArray[1] >> 4);
|
||||
byte[] bikeByte = { 0x19, Convert.ToByte(eventCounter % 256), Convert.ToByte(cadence % 254), accPowerArray[0], accPowerArray[1], powerArray[0], statByte, 0x20 };
|
||||
return bikeByte;
|
||||
}
|
||||
|
||||
//Generate an ANT message for page 0x10
|
||||
private byte[] GenerateBike0x10()
|
||||
{
|
||||
byte[] bikeByte = { 0x10, Convert.ToByte(equipmentType), Convert.ToByte(elapsedTime*4%64), Convert.ToByte(distanceTraveled), array[0], array[1], Convert.ToByte(BPM), 0xFF };
|
||||
byte[] bikeByte = { 0x10, Convert.ToByte(equipmentType), Convert.ToByte(elapsedTime * 4 % 64), Convert.ToByte(distanceTraveled), speedArray[0], speedArray[1], Convert.ToByte(BPM), 0xFF };
|
||||
return bikeByte;
|
||||
}
|
||||
|
||||
//Generate an ANT message for BPM
|
||||
private byte[] GenerateHeart()
|
||||
{
|
||||
byte[] hartByte = { 0x00, Convert.ToByte(BPM)};
|
||||
byte[] hartByte = { 0x00, Convert.ToByte(BPM) };
|
||||
return hartByte;
|
||||
}
|
||||
|
||||
//Generate an ANT message for resistance
|
||||
public byte[] GenerateResistance(float percentage)
|
||||
{
|
||||
byte[] antMessage = new byte[13];
|
||||
antMessage[0] = 0x4A;
|
||||
antMessage[1] = 0x09;
|
||||
antMessage[2] = 0x4E;
|
||||
antMessage[3] = 0x05;
|
||||
antMessage[4] = 0x30;
|
||||
for (int i = 5; i < 11; i++)
|
||||
{
|
||||
antMessage[i] = 0xFF;
|
||||
}
|
||||
antMessage[11] = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0);
|
||||
//antMessage[11] = 50; //hardcoded for testing
|
||||
|
||||
byte checksum = 0;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
checksum ^= antMessage[i];
|
||||
}
|
||||
|
||||
antMessage[12] = checksum;//reminder that i am dumb :P
|
||||
|
||||
return antMessage;
|
||||
}
|
||||
|
||||
//Calculates the needed variables
|
||||
//Input perlin value
|
||||
private void CalculateVariables(float perlin)
|
||||
{
|
||||
this.speed = perlin * 5 / 0.01 ;
|
||||
this.speed = perlin * 5 / 0.01;
|
||||
short sped = (short)speed;
|
||||
array = BitConverter.GetBytes(sped);
|
||||
this.distanceTraveled = (distanceTraveled+(speed*0.01)) % 256;
|
||||
this.BPM = (int) (perlin * 80);
|
||||
this.cadence = (int)speed * 4;
|
||||
|
||||
speedArray = BitConverter.GetBytes(sped);
|
||||
this.distanceTraveled = (distanceTraveled + (speed * 0.01)) % 256;
|
||||
this.BPM = (int)(perlin * 80);
|
||||
this.cadence = (int)speed / 6;
|
||||
this.power = ((1 + resistance) * speed) / 14 % 4094;
|
||||
this.accPower = (this.accPower + this.power) % 65536;
|
||||
// TO DO power to power LSB & MSN
|
||||
powerArray = BitConverter.GetBytes((short)this.power);
|
||||
accPowerArray = BitConverter.GetBytes((short)accPower);
|
||||
}
|
||||
|
||||
//Set resistance in simulated bike
|
||||
public void setResistance(byte[] bytes)
|
||||
public void setResistance(float percentage)
|
||||
{
|
||||
//TODO check if message is correct
|
||||
if(bytes.Length == 13)
|
||||
{
|
||||
this.resistance = Convert.ToDouble(bytes[11])/2;
|
||||
}
|
||||
}
|
||||
this.resistance = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0);
|
||||
}
|
||||
|
||||
//Interface for receiving a message on the simulated bike
|
||||
interface IHandler
|
||||
{
|
||||
void setResistance(byte[] bytes);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
using System;
|
||||
using ProftaakRH;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Hardware
|
||||
{
|
||||
class DataConverter : IDataConverter
|
||||
/// <summary>
|
||||
/// DataConverter class that handles all conversion of received data from the BLE bike.
|
||||
/// </summary>
|
||||
class DataConverter : IDataReceiver
|
||||
{
|
||||
/// <summary>
|
||||
/// Receives, parses and displays any incoming data from the bike.
|
||||
/// </summary>
|
||||
/// <param name="bytes">the array of bytes that was received</param>
|
||||
public void Bike(byte[] bytes)
|
||||
{
|
||||
if (bytes == null)
|
||||
@@ -30,7 +38,7 @@ namespace Hardware
|
||||
Console.WriteLine($"Speed is : {input * 0.01}m/s (Range 65.534m/4)");
|
||||
if (bytes[6] != 0xFF)
|
||||
{
|
||||
Console.WriteLine("Heart rate byte: {0}", Convert.ToString(bytes[6],2));
|
||||
Console.WriteLine("Heart rate byte: {0}", Convert.ToString(bytes[6], 2));
|
||||
}
|
||||
break;
|
||||
case 0x19:
|
||||
@@ -44,16 +52,17 @@ namespace Hardware
|
||||
|
||||
Console.WriteLine($"Accumulated power: {accumPower} watt (Rollover 65536)");
|
||||
|
||||
int instantPower = (bytes[5]) | (bytes[6]>>4)<<8;
|
||||
int instantPower = (bytes[5]) | (bytes[6] & 0b00001111) << 8;
|
||||
|
||||
|
||||
if (instantPower != 0xFFF)
|
||||
Console.WriteLine($"Instant power: {instantPower} watt (Range 0-4094)");
|
||||
|
||||
int trainerStatus = bytes[6] & 0b00001111; // bit 4-7
|
||||
int trainerStatus = bytes[6] & 0b11110000; // bit 4-7
|
||||
int flags = bytes[7] >> 4;
|
||||
int FEState = bytes[7] & 0b00001111;
|
||||
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -68,6 +77,10 @@ namespace Hardware
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets and prints the BPM from the message received from the bike.
|
||||
/// </summary>
|
||||
/// <param name="bytes">The array with bytes that was received</param>
|
||||
public void BPM(byte[] bytes)
|
||||
{
|
||||
if (bytes == null)
|
||||
@@ -91,10 +104,4 @@ namespace Hardware
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
|
||||
interface IDataConverter
|
||||
{
|
||||
void BPM(byte[] bytes);
|
||||
void Bike(byte[] bytes);
|
||||
}
|
||||
}
|
||||
|
||||
12
ProftaakRH/IDataReceiver.cs
Normal file
12
ProftaakRH/IDataReceiver.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ProftaakRH
|
||||
{
|
||||
public interface IDataReceiver
|
||||
{
|
||||
void BPM(byte[] bytes);
|
||||
void Bike(byte[] bytes);
|
||||
}
|
||||
}
|
||||
11
ProftaakRH/IHandler.cs
Normal file
11
ProftaakRH/IHandler.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ProftaakRH
|
||||
{
|
||||
public interface IHandler
|
||||
{
|
||||
void setResistance(float percentage);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using Hardware;
|
||||
@@ -11,12 +11,34 @@ namespace ProftaakRH
|
||||
{
|
||||
static void Main(string[] agrs)
|
||||
{
|
||||
IDataConverter dataConverter = new DataConverter();
|
||||
BikeSimulator bikeSimulator = new BikeSimulator(dataConverter);
|
||||
bikeSimulator.setResistance(bikeSimulator.GenerateResistance(1f));
|
||||
IDataReceiver dataReceiver = new DataConverter();
|
||||
BLEHandler bLEHandler = new BLEHandler(dataReceiver);
|
||||
BikeSimulator bikeSimulator = new BikeSimulator(dataReceiver);
|
||||
bikeSimulator.setResistance(1);
|
||||
bikeSimulator.StartSimulation();
|
||||
|
||||
Console.ReadLine();
|
||||
|
||||
bool running = true;
|
||||
while (running)
|
||||
{
|
||||
string input = Console.ReadLine();
|
||||
input.ToLower();
|
||||
input.Trim();
|
||||
if (input == "quit")
|
||||
{
|
||||
running = false;
|
||||
break;
|
||||
}
|
||||
try
|
||||
{
|
||||
int resistance = Int32.Parse(input);
|
||||
bLEHandler.setResistance(resistance);
|
||||
}
|
||||
catch
|
||||
{
|
||||
//do nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="LibNoise" Version="0.2.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="BLELibrary">
|
||||
|
||||
@@ -3,9 +3,27 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30413.136
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProftaakRH", "ProftaakRH.csproj", "{0F053CC5-D969-4970-9501-B3428EA3D777}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProftaakRH", "ProftaakRH.csproj", "{0F053CC5-D969-4970-9501-B3428EA3D777}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RH-Engine", "..\RH-Engine\RH-Engine.csproj", "{984E295E-47A2-41E7-90E5-50FDB9E67694}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "..\Server\Server.csproj", "{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}"
|
||||
EndProject
|
||||
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
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientApp", "..\ClientApp\ClientApp.csproj", "{013AADBA-1D27-4A52-81D8-217697E91039}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SharedMSBuildProjectFiles) = preSolution
|
||||
..\Hashing\Hashing.projitems*{013aadba-1d27-4a52-81d8-217697e91039}*SharedItemsImports = 5
|
||||
..\Hashing\Hashing.projitems*{70277749-d423-4871-b692-2efc5a6ed932}*SharedItemsImports = 13
|
||||
..\Hashing\Hashing.projitems*{b150f08b-13da-4d17-bd96-7e89f52727c6}*SharedItemsImports = 5
|
||||
..\Hashing\Hashing.projitems*{b1ab6f51-a20d-4162-9a7f-b3350b7510fd}*SharedItemsImports = 5
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
@@ -15,6 +33,26 @@ Global
|
||||
{0F053CC5-D969-4970-9501-B3428EA3D777}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0F053CC5-D969-4970-9501-B3428EA3D777}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0F053CC5-D969-4970-9501-B3428EA3D777}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{984E295E-47A2-41E7-90E5-50FDB9E67694}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{984E295E-47A2-41E7-90E5-50FDB9E67694}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{984E295E-47A2-41E7-90E5-50FDB9E67694}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{984E295E-47A2-41E7-90E5-50FDB9E67694}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B1AB6F51-A20D-4162-9A7F-B3350B7510FD}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9ED6832D-B0FB-4460-9BCD-FAA58863B0CE}.Debug|Any CPU.ActiveCfg = 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.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
|
||||
{013AADBA-1D27-4A52-81D8-217697E91039}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{013AADBA-1D27-4A52-81D8-217697E91039}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{013AADBA-1D27-4A52-81D8-217697E91039}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{013AADBA-1D27-4A52-81D8-217697E91039}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
52
ProftaakRH/VRMessage.cs
Normal file
52
ProftaakRH/VRMessage.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
class VRMessage
|
||||
{
|
||||
public VRMessage(string id, params JObject[] data)
|
||||
{
|
||||
this.Id = id;
|
||||
this.Data = data;
|
||||
}
|
||||
|
||||
public string Id
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public JObject[] Data
|
||||
{
|
||||
get;set;
|
||||
}
|
||||
|
||||
public string GetCommand()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter writer = new JsonTextWriter(sw))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WritePropertyName("id");
|
||||
writer.WriteValue(this.Id);
|
||||
writer.WritePropertyName("data");
|
||||
writer.WriteStartArray();
|
||||
foreach (JObject o in Data)
|
||||
{
|
||||
writer.WriteValue(o);
|
||||
}
|
||||
writer.WriteEndArray();
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
512
RH-Engine/Command.cs
Normal file
512
RH-Engine/Command.cs
Normal file
@@ -0,0 +1,512 @@
|
||||
using LibNoise.Primitive;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
public class Command
|
||||
{
|
||||
public const string STANDARD_HEAD = "Head";
|
||||
public const string STANDARD_GROUND = "GroundPlane";
|
||||
public const string STANDARD_SUN = "SunLight";
|
||||
public const string STANDARD_LEFTHAND = "LeftHand";
|
||||
public const string STANDARD_RIGHTHAND = "RightHand";
|
||||
|
||||
private string tunnelID;
|
||||
|
||||
public Command(string tunnelID)
|
||||
{
|
||||
this.tunnelID = tunnelID;
|
||||
}
|
||||
|
||||
public string TerrainCommand(int[] sizeArray, float[] heightsArray)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/terrain/add",
|
||||
data = new
|
||||
{
|
||||
size = sizeArray,
|
||||
heights = heightsArray
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string AddLayer(string uid, string texture)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/addlayer",
|
||||
data = new
|
||||
{
|
||||
id = uid,
|
||||
diffuse = @"C:\Users\woute\Downloads\NetworkEngine.18.10.10.1\NetworkEngine\data\NetworkEngine\textures\terrain\adesert_cracks_d.jpg",
|
||||
normal = @"C:\Users\woute\Downloads\NetworkEngine.18.10.10.1\NetworkEngine\data\NetworkEngine\textures\terrain\adesert_mntn_d.jpg",
|
||||
minHeight = 0,
|
||||
maxHeight = 10,
|
||||
fadeDist = 1
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string UpdateTerrain()
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/terrain/update",
|
||||
data = new
|
||||
{
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string AddNodeCommand()
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/add",
|
||||
data = new
|
||||
{
|
||||
name = "newNode",
|
||||
components = new
|
||||
{
|
||||
terrain = new
|
||||
{
|
||||
smoothnormals = true
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string DeleteNode(string uuid, string serialCode)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/delete",
|
||||
serial = serialCode,
|
||||
data = new
|
||||
{
|
||||
id = uuid,
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string addPanel(string serialToSend, string uuidBike)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/add",
|
||||
serial = serialToSend,
|
||||
data = new
|
||||
{
|
||||
name = "dashboard",
|
||||
parent = uuidBike,
|
||||
components = new
|
||||
{
|
||||
transform = new
|
||||
{
|
||||
position = new float[]
|
||||
{
|
||||
-1.5f, 1f, 0f
|
||||
},
|
||||
scale = 1,
|
||||
rotation = new int[]
|
||||
{
|
||||
-30, 90,0
|
||||
}
|
||||
},
|
||||
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 ColorPanel(string uuidPanel)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/panel/setclearcolor",
|
||||
data = new
|
||||
{
|
||||
id = uuidPanel,
|
||||
color = new float[] { 0f, 0f, 0f, 0f }
|
||||
}
|
||||
};
|
||||
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string SwapPanel(string uuid)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/panel/swap",
|
||||
data = new
|
||||
{
|
||||
id = uuid
|
||||
}
|
||||
};
|
||||
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
private string showOnPanel(string uuidPanel, string serialCode, string mText, int index)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/panel/drawtext",
|
||||
serial = serialCode,
|
||||
data = new
|
||||
{
|
||||
id = uuidPanel,
|
||||
text = mText,
|
||||
position = new int[] { 4, 24 + index * 32 },
|
||||
size = 32.0,
|
||||
color = new int[] { 0, 0, 0, 1 },
|
||||
font = "segoeui"
|
||||
}
|
||||
};
|
||||
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
|
||||
public string showBikespeed(string uuidPanel, string serialCode, double speed)
|
||||
{
|
||||
//dynamic payload = new
|
||||
//{
|
||||
// id = "scene/panel/drawtext",
|
||||
// serial = serialCode,
|
||||
// data = new
|
||||
// {
|
||||
// id = uuidPanel,
|
||||
// text = "Speed: " + speed + " m/s",
|
||||
// position = new int[] { 4, 24 },
|
||||
// size = 36.0,
|
||||
// color = new int[] { 0, 0, 0, 1 },
|
||||
// font = "segoeui"
|
||||
// }
|
||||
//};
|
||||
|
||||
//return JsonConvert.SerializeObject(Payload(payload));
|
||||
return showOnPanel(uuidPanel, serialCode, "Speed: " + speed + " m/s", 0);
|
||||
}
|
||||
|
||||
public string showHeartrate(string uuidPanel, string serialCode, int bpm)
|
||||
{
|
||||
return showOnPanel(uuidPanel, serialCode, "Heartrate: " + bpm + " bpm", 1);
|
||||
}
|
||||
|
||||
public string showPower(string uuidPanel, string serialCode, double power)
|
||||
{
|
||||
return showOnPanel(uuidPanel, serialCode, "Inst. Power: " + power + " W", 2);
|
||||
}
|
||||
|
||||
public string showResistance(string uuidPanel, string serialCode, double resistance)
|
||||
{
|
||||
return showOnPanel(uuidPanel, serialCode, "Resistance: " + resistance + " %", 3);
|
||||
}
|
||||
|
||||
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;
|
||||
bool animatedBool = false;
|
||||
if (animationLocation != null)
|
||||
{
|
||||
animatedBool = true;
|
||||
}
|
||||
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/add",
|
||||
serial = serialToSend,
|
||||
data = new
|
||||
{
|
||||
name = namename,
|
||||
components = new
|
||||
{
|
||||
transform = new
|
||||
{
|
||||
position = positionVector,
|
||||
scale = scalar,
|
||||
rotation = rotationVector
|
||||
},
|
||||
model = new
|
||||
{
|
||||
file = fileLocation,
|
||||
cullbackfaces = true,
|
||||
animated = animatedBool,
|
||||
animation = animationLocation
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string MoveTo(string uuid, string serial, float[] positionVector, string rotateValue, int speedValue, int timeValue)
|
||||
{
|
||||
return MoveTo(uuid, serial, "stop", positionVector, rotateValue, "linear", false, speedValue, timeValue);
|
||||
}
|
||||
|
||||
private string MoveTo(string uuid, string serialCode, string stopValue, float[] positionVector, string rotateValue, string interpolateValue, bool followHeightValue, int speedValue, int timeValue)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/moveto",
|
||||
serial = serialCode,
|
||||
data = new
|
||||
{
|
||||
id = uuid,
|
||||
stop = stopValue,
|
||||
position = positionVector,
|
||||
rotate = rotateValue,
|
||||
interpolate = interpolateValue,
|
||||
followheight = followHeightValue,
|
||||
speed = speedValue,
|
||||
time = timeValue
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string RouteCommand(string serialToSend)
|
||||
{
|
||||
ImprovedPerlin improvedPerlin = new ImprovedPerlin(4325, LibNoise.NoiseQuality.Best);
|
||||
Random r = new Random();
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "route/add",
|
||||
serial = serialToSend,
|
||||
data = new
|
||||
{
|
||||
nodes = new dynamic[]
|
||||
{
|
||||
new
|
||||
{
|
||||
/*pos = GetPos(0.6f, improvedPerlin)*/
|
||||
pos = new int[] {0,0,5 },
|
||||
dir = new int[] { r.Next(20,100),0,-r.Next(20, 100) }
|
||||
},
|
||||
new
|
||||
{
|
||||
//pos = GetPos(1.6f, improvedPerlin),
|
||||
pos = new int[] {50,0,0 },
|
||||
dir = new int[] { r.Next(20, 100),0,r.Next(20, 100) }
|
||||
},
|
||||
new
|
||||
{
|
||||
//pos = GetPos(2.654f, improvedPerlin),
|
||||
pos = new int[] {20,0,20 },
|
||||
dir = new int[] { r.Next(20, 100),0,r.Next(20, 100) }
|
||||
},
|
||||
new
|
||||
{
|
||||
//pos = GetPos(3.6543f, improvedPerlin),
|
||||
pos = new int[] {10,0,50 },
|
||||
dir = new int[] { -r.Next(3,7),0,r.Next(3,7) }
|
||||
},
|
||||
new
|
||||
{
|
||||
pos = new int[] {0,0,50 },
|
||||
dir = new int[] { -r.Next(20, 50),0,-r.Next(20, 50) }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
//Console.WriteLine("route command: " + JsonConvert.SerializeObject(Payload(payload)));
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
private float[] GetPos(float n, ImprovedPerlin improvedPerlin)
|
||||
{
|
||||
float[] res = new float[] { improvedPerlin.GetValue(n) * 50, 0, improvedPerlin.GetValue(n) * 50 };
|
||||
return res;
|
||||
}
|
||||
|
||||
private int[] GetDir()
|
||||
{
|
||||
Random rng = new Random();
|
||||
int[] dir = { rng.Next(50), 0, rng.Next(50) };
|
||||
return dir;
|
||||
}
|
||||
|
||||
public string RouteFollow(string routeID, string nodeID, float speedValue)
|
||||
{
|
||||
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 RouteSpeed(float speedValue,string nodeID)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "route/follow/speed",
|
||||
data = new
|
||||
{
|
||||
node = nodeID,
|
||||
speed = speedValue
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string RoadCommand(string uuid_route)
|
||||
{
|
||||
Console.WriteLine("road");
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/road/add",
|
||||
data = new
|
||||
{
|
||||
route = uuid_route,
|
||||
diffuse = "data/NetworkEngine/textures/tarmac_diffuse.png",
|
||||
normal = "data/NetworkEngine/textures/tarmac_normale.png",
|
||||
specular = "data/NetworkEngine/textures/tarmac_specular.png",
|
||||
heightoffset = 1f
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string GetSceneInfoCommand(string serialToSend)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/get",
|
||||
serial = serialToSend
|
||||
};
|
||||
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string ResetScene()
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/reset",
|
||||
serial = "reset"
|
||||
};
|
||||
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string SkyboxCommand(double timeToSet)
|
||||
{
|
||||
if (timeToSet < 0 || timeToSet > 24)
|
||||
{
|
||||
throw new Exception("The time must be between 0 and 24!");
|
||||
}
|
||||
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/skybox/settime",
|
||||
data = new
|
||||
{
|
||||
time = timeToSet
|
||||
}
|
||||
};
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
private object Payload(dynamic message)
|
||||
{
|
||||
return new
|
||||
{
|
||||
id = "tunnel/send",
|
||||
data = new
|
||||
{
|
||||
dest = tunnelID,
|
||||
data = message,
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
116
RH-Engine/JSONParser.cs
Normal file
116
RH-Engine/JSONParser.cs
Normal file
@@ -0,0 +1,116 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
public class JSONParser
|
||||
{
|
||||
/// <summary>
|
||||
/// returns all the users from the given response
|
||||
/// </summary>
|
||||
/// <param name="msg">the message gotten from the server, without the length prefix</param>
|
||||
/// <returns></returns>
|
||||
public static PC[] GetUsers(string msg)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(msg);
|
||||
Newtonsoft.Json.Linq.JArray data = jsonData.data;
|
||||
PC[] res = new PC[data.Count];
|
||||
int counter = 0;
|
||||
foreach (dynamic d in data)
|
||||
{
|
||||
res[counter] = new PC((string)d.clientinfo.host, (string)d.clientinfo.user);
|
||||
counter++;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
public static string GetIdSceneInfoChild(string msg, string nodeName)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(msg);
|
||||
Newtonsoft.Json.Linq.JArray children = jsonData.data.data.data.children;
|
||||
foreach (dynamic d in children)
|
||||
{
|
||||
if (d.name == nodeName)
|
||||
{
|
||||
return d.uuid;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string GetSessionID(string msg, PC[] PCs)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(msg);
|
||||
Newtonsoft.Json.Linq.JArray data = jsonData.data;
|
||||
for (int i = data.Count - 1; i >= 0; i--)
|
||||
{
|
||||
dynamic d = data[i];
|
||||
foreach (PC pc in PCs)
|
||||
{
|
||||
if (d.clientinfo.host == pc.host && d.clientinfo.user == pc.user)
|
||||
{
|
||||
Console.WriteLine("[JSONPARSER] connecting to {0}, on {1} with id {2}", pc.user, pc.host, d.id);
|
||||
return d.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(json);
|
||||
if (jsonData.data.status == "ok")
|
||||
{
|
||||
return jsonData.data.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
if (jsonData.data.data.status == "ok")
|
||||
{
|
||||
return jsonData.data.data.data.uuid;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
394
RH-Engine/Program.cs
Normal file
394
RH-Engine/Program.cs
Normal file
@@ -0,0 +1,394 @@
|
||||
using LibNoise.Primitive;
|
||||
using Microsoft.VisualBasic.FileIO;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
public delegate void HandleSerial(string message);
|
||||
|
||||
public class Program
|
||||
{
|
||||
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 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)
|
||||
{
|
||||
TcpClient client = new TcpClient("145.48.6.10", 6666);
|
||||
|
||||
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);
|
||||
serialResponses.Remove(serial);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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 static void WriteTextMessage(NetworkStream stream, 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);
|
||||
|
||||
//Console.WriteLine("sent message " + message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// connects to the server and creates the tunnel
|
||||
/// </summary>
|
||||
/// <param name="stream">the network stream to use</param>
|
||||
private static void CreateConnection(NetworkStream stream)
|
||||
{
|
||||
initReader(stream);
|
||||
|
||||
WriteTextMessage(stream, "{\r\n\"id\" : \"session/list\",\r\n\"serial\" : \"list\"\r\n}");
|
||||
|
||||
// wait until we have got a sessionId
|
||||
while (sessionId == string.Empty) { }
|
||||
|
||||
string tunnelCreate = "{\"id\" : \"tunnel/create\", \"data\" : {\"session\" : \"" + sessionId + "\"}}";
|
||||
|
||||
WriteTextMessage(stream, tunnelCreate);
|
||||
|
||||
// wait until we have a tunnel id
|
||||
while (tunnelId == string.Empty) { }
|
||||
Console.WriteLine("got tunnel id! sending commands...");
|
||||
sendCommands(stream, tunnelId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sends all the commands to the server
|
||||
/// </summary>
|
||||
/// <param name="stream">the network stream to use</param>
|
||||
/// <param name="tunnelID">the tunnel id to use</param>
|
||||
private static void sendCommands(NetworkStream stream, string tunnelID)
|
||||
{
|
||||
Command mainCommand = new Command(tunnelID);
|
||||
|
||||
// Reset scene
|
||||
WriteTextMessage(stream, mainCommand.ResetScene());
|
||||
//headId = GetId("Root", stream, mainCommand);
|
||||
//while (headId == string.Empty) { }
|
||||
|
||||
//Get sceneinfo
|
||||
SendMessageAndOnResponse(stream, mainCommand.GetSceneInfoCommand("sceneinfo"), "sceneinfo",
|
||||
(message) =>
|
||||
{
|
||||
//Console.WriteLine("\r\n\r\n\r\nscene info" + message);
|
||||
cameraId = JSONParser.GetIdSceneInfoChild(message, "Camera");
|
||||
string headId = JSONParser.GetIdSceneInfoChild(message, "Head");
|
||||
string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand");
|
||||
string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand");
|
||||
|
||||
//Force(stream, mainCommand.DeleteNode(handLeftId, "deleteHandL"), "deleteHandL", (message) => Console.WriteLine("Left hand deleted"));
|
||||
//Force(stream, mainCommand.DeleteNode(handRightId, "deleteHandR"), "deleteHandR", (message) => Console.WriteLine("Right hand deleted"));
|
||||
});
|
||||
|
||||
//Add route, bike and put camera and bike to follow route at same speed.
|
||||
SendMessageAndOnResponse(stream, mainCommand.RouteCommand("routeID"), "routeID", (message) => routeId = JSONParser.GetResponseUuid(message));
|
||||
SendMessageAndOnResponse(stream, mainCommand.AddBikeModel("bikeID"), "bikeID",
|
||||
(message) =>
|
||||
{
|
||||
bikeId = JSONParser.GetResponseUuid(message);
|
||||
SendMessageAndOnResponse(stream, mainCommand.addPanel("panelAdd", bikeId), "panelAdd",
|
||||
(message) =>
|
||||
{
|
||||
bool speedReplied = false;
|
||||
bool moveReplied = true;
|
||||
panelId = JSONParser.getPanelID(message);
|
||||
WriteTextMessage(stream, mainCommand.ColorPanel(panelId));
|
||||
WriteTextMessage(stream, mainCommand.ClearPanel(panelId));
|
||||
|
||||
|
||||
showPanel(stream, mainCommand, 5.3, 83, 52, 53);
|
||||
|
||||
|
||||
//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));
|
||||
|
||||
//command = mainCommand.AddModel("car", "data\\customModels\\TeslaRoadster.fbx");
|
||||
//WriteTextMessage(stream, command);
|
||||
|
||||
//command = mainCommand.addPanel();
|
||||
// WriteTextMessage(stream, command);
|
||||
// string response = ReadPrefMessage(stream);
|
||||
// Console.WriteLine("add Panel response: \n\r" + response);
|
||||
// string uuidPanel = JSONParser.getPanelID(response);
|
||||
// WriteTextMessage(stream, mainCommand.ClearPanel(uuidPanel));
|
||||
// Console.WriteLine(ReadPrefMessage(stream));
|
||||
// WriteTextMessage(stream, mainCommand.bikeSpeed(uuidPanel, 2.42));
|
||||
// Console.WriteLine(ReadPrefMessage(stream));
|
||||
// WriteTextMessage(stream, mainCommand.ColorPanel(uuidPanel));
|
||||
// Console.WriteLine("Color panel: " + ReadPrefMessage(stream));
|
||||
// WriteTextMessage(stream, mainCommand.SwapPanel(uuidPanel));
|
||||
// Console.WriteLine("Swap panel: " + ReadPrefMessage(stream));
|
||||
Console.WriteLine("id of head " + GetId(Command.STANDARD_HEAD, stream, mainCommand));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// gets the id of the object with the given name
|
||||
/// </summary>
|
||||
/// <param name="name">the name of the object</param>
|
||||
/// <param name="stream">the network stream to send requests to</param>
|
||||
/// <param name="createGraphics">the create graphics object to create all the commands</param>
|
||||
/// <returns> the uuid of the object with the given name, <c>null</c> otherwise.</returns>
|
||||
public static string GetId(string name, NetworkStream stream, Command createGraphics)
|
||||
{
|
||||
JArray children = GetChildren(stream, createGraphics);
|
||||
|
||||
foreach (dynamic child in children)
|
||||
{
|
||||
if (child.name == name)
|
||||
{
|
||||
return child.uuid;
|
||||
}
|
||||
}
|
||||
Console.WriteLine("Could not find id of " + name);
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void CreateTerrain(NetworkStream stream, Command createGraphics)
|
||||
{
|
||||
float x = 0f;
|
||||
float[] height = new float[256 * 256];
|
||||
ImprovedPerlin improvedPerlin = new ImprovedPerlin(0, LibNoise.NoiseQuality.Best);
|
||||
for (int i = 0; i < 256 * 256; i++)
|
||||
{
|
||||
height[i] = improvedPerlin.GetValue(x / 10, x / 10, x * 100) + 1;
|
||||
x += 0.001f;
|
||||
}
|
||||
WriteTextMessage(stream, createGraphics.TerrainCommand(new int[] { 256, 256 }, height));
|
||||
|
||||
WriteTextMessage(stream, createGraphics.AddNodeCommand());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// gets all the children in the current scene
|
||||
/// </summary>
|
||||
/// <param name="stream">the network stream to send requests to</param>
|
||||
/// <param name="createGraphics">the create graphics object to create all the commands</param>
|
||||
/// <returns>all the children objects in the current scene</returns>
|
||||
public static JArray GetChildren(NetworkStream stream, Command createGraphics)
|
||||
{
|
||||
JArray res = null;
|
||||
SendMessageAndOnResponse(stream, createGraphics.GetSceneInfoCommand("getChildren"), "getChildren", (message) =>
|
||||
{
|
||||
dynamic response = JsonConvert.DeserializeObject(message);
|
||||
res = response.data.data.data.children;
|
||||
});
|
||||
while (res == null) { }
|
||||
return res;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// returns all objects in the current scene, as name-uuid tuples.
|
||||
/// </summary>
|
||||
/// <param name="stream">the network stream to send requests to</param>
|
||||
/// <param name="createGraphics">the create graphics object to create all the commands</param>
|
||||
/// <returns>an array of name-uuid tuples for each object</returns>
|
||||
public static (string, string)[] GetObjectsInScene(NetworkStream stream, Command createGraphics)
|
||||
{
|
||||
JArray children = GetChildren(stream, createGraphics);
|
||||
(string, string)[] res = new (string, string)[children.Count];
|
||||
|
||||
int i = 0;
|
||||
foreach (dynamic child in children)
|
||||
{
|
||||
res[i] = (child.name, child.uuid);
|
||||
i++;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
private static void showPanel(NetworkStream stream, Command mainCommand, double bikeSpeed, int bpm, int power, int resistance)
|
||||
{
|
||||
SendMessageAndOnResponse(stream, mainCommand.showBikespeed(panelId, "bikeSpeed", bikeSpeed), "bikeSpeed",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(stream, mainCommand.showHeartrate(panelId, "bpm", bpm), "bpm",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(stream, mainCommand.showPower(panelId, "power", power), "power",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
SendMessageAndOnResponse(stream, mainCommand.showResistance(panelId, "resistance", resistance), "resistance",
|
||||
(message) =>
|
||||
{
|
||||
// TODO check if is drawn
|
||||
});
|
||||
|
||||
// Check if every text is drawn!
|
||||
|
||||
WriteTextMessage(stream, mainCommand.SwapPanel(panelId));
|
||||
}
|
||||
|
||||
private static void SetFollowSpeed(float speed, NetworkStream stream, Command mainCommand)
|
||||
{
|
||||
WriteTextMessage(stream, mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 }));
|
||||
WriteTextMessage(stream, mainCommand.RouteFollow(routeId, cameraId, speed));
|
||||
}
|
||||
//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>
|
||||
/// struct used to store the host pc name and user
|
||||
/// </summary>
|
||||
public readonly struct PC
|
||||
{
|
||||
public PC(string host, string user)
|
||||
{
|
||||
this.host = host;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public string host { get; }
|
||||
public string user { get; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "PC - host:" + host + " - user:" + user;
|
||||
}
|
||||
}
|
||||
}
|
||||
8
RH-Engine/Properties/launchSettings.json
Normal file
8
RH-Engine/Properties/launchSettings.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"RH-Engine": {
|
||||
"commandName": "Project",
|
||||
"nativeDebugging": true
|
||||
}
|
||||
}
|
||||
}
|
||||
14
RH-Engine/RH-Engine.csproj
Normal file
14
RH-Engine/RH-Engine.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
<RootNamespace>RH_Engine</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="LibNoise" Version="0.2.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
25
RH-Engine/RH-Engine.sln
Normal file
25
RH-Engine/RH-Engine.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30503.244
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RH-Engine", "RH-Engine.csproj", "{12E8F82B-C464-4152-B4FB-FCB5E1A9FCFA}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{12E8F82B-C464-4152-B4FB-FCB5E1A9FCFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{12E8F82B-C464-4152-B4FB-FCB5E1A9FCFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{12E8F82B-C464-4152-B4FB-FCB5E1A9FCFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{12E8F82B-C464-4152-B4FB-FCB5E1A9FCFA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {C75B8E99-BE3D-496F-B2F0-03C4069493B2}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
87
RH-Engine/ServerResponseReader.cs
Normal file
87
RH-Engine/ServerResponseReader.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
public delegate void OnResponse(string response);
|
||||
|
||||
public class ServerResponseReader
|
||||
{
|
||||
private bool running;
|
||||
private Thread t;
|
||||
public OnResponse callback
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public NetworkStream Stream { get; }
|
||||
|
||||
public ServerResponseReader(NetworkStream stream)
|
||||
{
|
||||
this.Stream = stream;
|
||||
}
|
||||
|
||||
public void StartRead()
|
||||
{
|
||||
t = new Thread(() =>
|
||||
{
|
||||
if (this.callback == null)
|
||||
{
|
||||
throw new Exception("Callback not initialized!");
|
||||
}
|
||||
else
|
||||
{
|
||||
running = true;
|
||||
Console.WriteLine("[SERVERRESPONSEREADER] Starting loop for reading");
|
||||
while (running)
|
||||
{
|
||||
string res = ReadPrefMessage(Stream);
|
||||
//Console.WriteLine("[SERVERRESPONSEREADER] got message from server: " + res);
|
||||
this.callback(res);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
t.Start();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
running = false;
|
||||
t.Join();
|
||||
Stream.Close();
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
}
|
||||
227
Server/Client.cs
Normal file
227
Server/Client.cs
Normal file
@@ -0,0 +1,227 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
using ClientApp.Utils;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
class Client
|
||||
{
|
||||
private Communication communication;
|
||||
private TcpClient tcpClient;
|
||||
private NetworkStream stream;
|
||||
private byte[] buffer = new byte[1024];
|
||||
private byte[] totalBuffer = new byte[1024];
|
||||
private int totalBufferReceived = 0;
|
||||
private SaveData saveData;
|
||||
private string username = null;
|
||||
private DateTime sessionStart;
|
||||
private string fileName;
|
||||
|
||||
|
||||
|
||||
public string Username { get; set; }
|
||||
|
||||
public Client(Communication communication, TcpClient tcpClient)
|
||||
{
|
||||
this.sessionStart = DateTime.Now;
|
||||
this.communication = communication;
|
||||
this.tcpClient = tcpClient;
|
||||
this.stream = this.tcpClient.GetStream();
|
||||
this.fileName = Directory.GetCurrentDirectory() + "/userInfo.dat";
|
||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
|
||||
}
|
||||
|
||||
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);
|
||||
HandleData(messageBytes);
|
||||
|
||||
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength)); //maybe unsafe idk
|
||||
|
||||
totalBufferReceived -= expectedMessageLength;
|
||||
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
|
||||
if (expectedMessageLength <= 5)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
|
||||
|
||||
}
|
||||
|
||||
private void OnWrite(IAsyncResult ar)
|
||||
{
|
||||
this.stream.EndWrite(ar);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// handles all incoming data from the client
|
||||
/// </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))
|
||||
{
|
||||
// print the raw data
|
||||
Console.WriteLine(BitConverter.ToString(payloadbytes));
|
||||
// TODO change, checking for length is not that safe
|
||||
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)
|
||||
{
|
||||
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
56
Server/Communication.cs
Normal file
56
Server/Communication.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using ClientApp;
|
||||
using ClientApp.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
class Communication
|
||||
{
|
||||
private TcpListener listener;
|
||||
private List<Client> clients;
|
||||
private Client doctor;
|
||||
|
||||
public Communication(TcpListener listener)
|
||||
{
|
||||
this.listener = listener;
|
||||
this.clients = new List<Client>();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
listener.Start();
|
||||
Console.WriteLine($"==========================================================================\n" +
|
||||
$"\tstarted accepting clients at {DateTime.Now}\n" +
|
||||
$"==========================================================================");
|
||||
listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
|
||||
}
|
||||
|
||||
private void OnConnect(IAsyncResult ar)
|
||||
{
|
||||
|
||||
var tcpClient = listener.EndAcceptTcpClient(ar);
|
||||
Console.WriteLine($"Client connected from {tcpClient.Client.RemoteEndPoint}");
|
||||
clients.Add(new Client(this, tcpClient));
|
||||
if (doctor == null)
|
||||
{
|
||||
doctor = clients.ElementAt(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
doctor.sendMessage(DataParser.getLoginResponse("new client"));
|
||||
}
|
||||
listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
|
||||
}
|
||||
|
||||
internal void Disconnect(Client client)
|
||||
{
|
||||
clients.Remove(client);
|
||||
}
|
||||
}
|
||||
}
|
||||
19
Server/Program.cs
Normal file
19
Server/Program.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Communication communication = new Communication(new TcpListener(IPAddress.Any, 5555));
|
||||
communication.Start();
|
||||
|
||||
while (true)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
140
Server/SaveData.cs
Normal file
140
Server/SaveData.cs
Normal file
@@ -0,0 +1,140 @@
|
||||
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 (var fileStream = new FileStream(fileLocation, FileMode.Append, FileAccess.Write, FileShare.None))
|
||||
using (var bw = new BinaryWriter(fileStream))
|
||||
{
|
||||
//sw.BaseStream.Seek(length, SeekOrigin.Begin);
|
||||
bw.Write(data);
|
||||
bw.Flush();
|
||||
//Console.WriteLine("wrote at " + bw.BaseStream.Position);
|
||||
}
|
||||
//using (BinaryReader binaryReader = new BinaryReader(File.Open(fileLocation, FileMode.Open)))
|
||||
//{
|
||||
// byte[] totalArray = new byte[binaryReader.BaseStream.Length];
|
||||
// binaryReader.BaseStream.Read(totalArray, 0, (int)binaryReader.BaseStream.Length);
|
||||
// Console.WriteLine("all data is " + BitConverter.ToString(totalArray));
|
||||
//}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
//Console.WriteLine("length " + length);
|
||||
|
||||
byte[] output = new byte[outputSize];
|
||||
|
||||
int messageSize = 2;
|
||||
int readSize = messageSize * averageOver;
|
||||
byte[] readBuffer = new byte[readSize];
|
||||
|
||||
using (BinaryReader binaryReader = new BinaryReader(File.Open(this.path + rawBPMFilename, FileMode.Open)))
|
||||
{
|
||||
//byte[] totalArray = new byte[binaryReader.BaseStream.Length];
|
||||
//binaryReader.BaseStream.Read(totalArray, 0, (int)binaryReader.BaseStream.Length);
|
||||
//Console.WriteLine("all data is " + BitConverter.ToString(totalArray));
|
||||
for (int i = 1; i <= outputSize; i++)
|
||||
{
|
||||
if (length - (i * readSize) < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
binaryReader.BaseStream.Seek(length - (i * readSize), SeekOrigin.Begin);
|
||||
binaryReader.BaseStream.Read(readBuffer, 0, readSize);
|
||||
//Console.WriteLine("read " + binaryReader.BaseStream.Position + " and size " + readSize + " with value " + BitConverter.ToString(readBuffer));
|
||||
|
||||
//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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
18
Server/Server.csproj
Normal file
18
Server/Server.csproj
Normal file
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ClientApp\ClientApp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user