Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc0e70403f | ||
|
|
acbe3e9d55 | ||
|
|
aea1b4fce4 | ||
|
|
a2937c0427 | ||
|
|
02bd68d142 | ||
|
|
699528bb83 | ||
|
|
e4d192fb06 | ||
|
|
09db19246e | ||
|
|
eb2738168b | ||
|
|
d85c5ff935 | ||
|
|
d420bdc2a4 | ||
|
|
cb2435bf53 | ||
|
|
ca2e61eb8e | ||
|
|
32ef17365e | ||
|
|
fedf8c0e5b | ||
|
|
505c4907d0 | ||
|
|
a5e679e6fb | ||
|
|
3e5f6e46c4 | ||
|
|
adea08cfb7 | ||
|
|
599b79ceee | ||
|
|
bd8994ad5b | ||
|
|
97f9d863aa | ||
|
|
d6b938668f | ||
|
|
45edbe5936 | ||
|
|
a65c36b8d1 | ||
|
|
82f2d6b71c | ||
|
|
6f1ab57fe4 | ||
|
|
341723d1d1 | ||
|
|
0cd3753b76 | ||
|
|
4388b39be5 | ||
|
|
0dc4bb6fad | ||
|
|
3ca3c1ad78 | ||
|
|
d06d621b13 | ||
|
|
7b05fcc898 | ||
|
|
c5b9a7ec09 |
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
@@ -6,7 +6,7 @@ using ProftaakRH;
|
||||
|
||||
namespace Client
|
||||
{
|
||||
class Client : IDataReceiver
|
||||
public class Client : IDataReceiver
|
||||
{
|
||||
private TcpClient client;
|
||||
private NetworkStream stream;
|
||||
@@ -14,6 +14,9 @@ namespace Client
|
||||
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)
|
||||
@@ -28,10 +31,26 @@ namespace Client
|
||||
client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null);
|
||||
}
|
||||
|
||||
private void initEngine()
|
||||
{
|
||||
engineConnection = EngineConnection.INSTANCE;
|
||||
engineConnection.OnNoTunnelId = retryEngineConnection;
|
||||
if (!engineConnection.Connected) engineConnection.Connect();
|
||||
}
|
||||
|
||||
private void retryEngineConnection()
|
||||
{
|
||||
Console.WriteLine("-- Could not connect to the VR engine. Please make sure you are running the simulation!");
|
||||
Console.WriteLine("-- Press any key to retry connecting to the VR engine.");
|
||||
Console.ReadKey();
|
||||
|
||||
engineConnection.CreateConnection();
|
||||
}
|
||||
|
||||
private void OnConnect(IAsyncResult ar)
|
||||
{
|
||||
this.client.EndConnect(ar);
|
||||
Console.WriteLine("Verbonden!");
|
||||
Console.WriteLine("TCP client Verbonden!");
|
||||
|
||||
|
||||
this.stream = this.client.GetStream();
|
||||
@@ -75,6 +94,7 @@ namespace Client
|
||||
if (responseStatus == "OK")
|
||||
{
|
||||
this.connected = true;
|
||||
//initEngine();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -82,6 +102,26 @@ namespace Client
|
||||
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;
|
||||
@@ -100,6 +140,11 @@ namespace Client
|
||||
|
||||
}
|
||||
|
||||
private void sendMessage(byte[] message)
|
||||
{
|
||||
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
private void OnWrite(IAsyncResult ar)
|
||||
{
|
||||
this.stream.EndWrite(ar);
|
||||
@@ -109,6 +154,10 @@ namespace Client
|
||||
//maybe move this to other place
|
||||
public void BPM(byte[] bytes)
|
||||
{
|
||||
if (!sessionRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
throw new ArgumentNullException("no bytes");
|
||||
@@ -119,6 +168,10 @@ namespace Client
|
||||
|
||||
public void Bike(byte[] bytes)
|
||||
{
|
||||
if (!sessionRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
throw new ArgumentNullException("no bytes");
|
||||
@@ -141,9 +194,29 @@ namespace Client
|
||||
Console.WriteLine("enter password");
|
||||
string password = Console.ReadLine();
|
||||
|
||||
byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(username, password));
|
||||
string hashUser = Hashing.Hasher.HashString(username);
|
||||
string hashPassword = Hashing.Hasher.HashString(password);
|
||||
|
||||
byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword));
|
||||
|
||||
|
||||
this.stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
public void tryLoginDoctor(string username, string password)
|
||||
{
|
||||
string hashUser = Hashing.Hasher.HashString(username);
|
||||
string hashPassword = Hashing.Hasher.HashString(password);
|
||||
|
||||
byte[] message = DataParser.getJsonMessage(DataParser.GetLoginJson(hashUser, hashPassword));
|
||||
|
||||
|
||||
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
public void setHandler(IHandler handler)
|
||||
{
|
||||
this.handler = handler;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
<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>
|
||||
|
||||
@@ -3,6 +3,7 @@ using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
using System.Text;
|
||||
|
||||
namespace Client
|
||||
@@ -10,7 +11,10 @@ namespace Client
|
||||
public class DataParser
|
||||
{
|
||||
public const string LOGIN = "LOGIN";
|
||||
public const string LOGIN_RESPONSE = "LOGIN_RESPONSE";
|
||||
public const string LOGIN_RESPONSE = "LOGIN RESPONSE";
|
||||
public const string START_SESSION = "START SESSION";
|
||||
public const string STOP_SESSION = "STOP SESSION";
|
||||
public const string SET_RESISTANCE = "SET RESISTANCE";
|
||||
/// <summary>
|
||||
/// makes the json object with LOGIN identifier and username and password
|
||||
/// </summary>
|
||||
@@ -59,6 +63,15 @@ namespace Client
|
||||
return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01);
|
||||
}
|
||||
|
||||
private static byte[] getJsonMessage(string mIdentifier)
|
||||
{
|
||||
dynamic json = new
|
||||
{
|
||||
identifier = mIdentifier,
|
||||
};
|
||||
return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01);
|
||||
}
|
||||
|
||||
public static byte[] getLoginResponse(string mStatus)
|
||||
{
|
||||
return getJsonMessage(LOGIN_RESPONSE, new { status = mStatus });
|
||||
@@ -150,15 +163,42 @@ namespace Client
|
||||
return getMessage(payload, 0x01);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// constructs a message with the message and clientId
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="clientId"></param>
|
||||
/// <returns>the message ready for sending</returns>
|
||||
public static byte[] getJsonMessage(string message)
|
||||
public static byte[] getStartSessionJson()
|
||||
{
|
||||
return getJsonMessage(Encoding.ASCII.GetBytes(message));
|
||||
return getJsonMessage(START_SESSION);
|
||||
}
|
||||
|
||||
public static byte[] getStopSessionJson()
|
||||
{
|
||||
return getJsonMessage(STOP_SESSION);
|
||||
}
|
||||
|
||||
public static byte[] getSetResistanceJson(float mResistance)
|
||||
{
|
||||
dynamic data = new
|
||||
{
|
||||
resistance = mResistance
|
||||
};
|
||||
return getJsonMessage(SET_RESISTANCE, data);
|
||||
}
|
||||
|
||||
public static byte[] getSetResistanceResponseJson(bool mWorked)
|
||||
{
|
||||
dynamic data = new
|
||||
{
|
||||
worked = mWorked
|
||||
};
|
||||
return getJsonMessage(SET_RESISTANCE, data);
|
||||
}
|
||||
|
||||
public static float getResistanceFromJson(byte[] json)
|
||||
{
|
||||
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.resistance;
|
||||
}
|
||||
|
||||
public static bool getResistanceFromResponseJson(byte[] json)
|
||||
{
|
||||
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.worked;
|
||||
}
|
||||
|
||||
|
||||
|
||||
180
Client/EngineConnection.cs
Normal file
180
Client/EngineConnection.cs
Normal file
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RH_Engine;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Client
|
||||
{
|
||||
public delegate void HandleSerial(string message);
|
||||
public delegate void HandleNoTunnelId();
|
||||
|
||||
public sealed class EngineConnection
|
||||
{
|
||||
private static EngineConnection instance = null;
|
||||
private static readonly object padlock = new object();
|
||||
public HandleNoTunnelId OnNoTunnelId;
|
||||
|
||||
|
||||
private static PC[] PCs = {
|
||||
//new PC("DESKTOP-M2CIH87", "Fabian"),
|
||||
//new PC("T470S", "Shinichi"),
|
||||
//new PC("DESKTOP-DHS478C", "semme"),
|
||||
new PC("HP-ZBOOK-SEM", "Sem")
|
||||
//new PC("DESKTOP-TV73FKO", "Wouter"),
|
||||
//new PC("DESKTOP-SINMKT1", "Ralf van Aert"),
|
||||
//new PC("NA", "Bart")
|
||||
};
|
||||
|
||||
private static ServerResponseReader serverResponseReader;
|
||||
private static string sessionId = string.Empty;
|
||||
private static string tunnelId = string.Empty;
|
||||
private static string routeId = string.Empty;
|
||||
private static string panelId = string.Empty;
|
||||
private static string bikeId = string.Empty;
|
||||
|
||||
private static NetworkStream stream;
|
||||
|
||||
private static Dictionary<string, HandleSerial> serialResponses = new Dictionary<string, HandleSerial>();
|
||||
private Command mainCommand;
|
||||
|
||||
public bool Connected = false;
|
||||
|
||||
EngineConnection()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public static EngineConnection INSTANCE
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (padlock)
|
||||
{
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new EngineConnection();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
TcpClient client = new TcpClient("145.48.6.10", 6666);
|
||||
stream = client.GetStream();
|
||||
initReader();
|
||||
CreateConnection();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// connects to the server and creates the tunnel
|
||||
/// </summary>
|
||||
/// <param name="stream">the network stream to use</param>
|
||||
public void CreateConnection()
|
||||
{
|
||||
|
||||
WriteTextMessage( "{\r\n\"id\" : \"session/list\",\r\n\"serial\" : \"list\"\r\n}");
|
||||
|
||||
// wait until we have got a sessionId
|
||||
while (sessionId == string.Empty) { }
|
||||
|
||||
string tunnelCreate = "{\"id\" : \"tunnel/create\", \"data\" : {\"session\" : \"" + sessionId + "\"}}";
|
||||
|
||||
WriteTextMessage(tunnelCreate);
|
||||
|
||||
// wait until we have a tunnel id
|
||||
while (tunnelId == string.Empty) { }
|
||||
if (tunnelId != null)
|
||||
{
|
||||
Write("got tunnel id! " + tunnelId);
|
||||
}
|
||||
mainCommand = new Command(tunnelId);
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// initializes and starts the reading of the responses from the vr server
|
||||
/// </summary>
|
||||
/// <param name="stream">the networkstream</param>
|
||||
private void initReader()
|
||||
{
|
||||
serverResponseReader = new ServerResponseReader(stream);
|
||||
serverResponseReader.callback = HandleResponse;
|
||||
serverResponseReader.StartRead();
|
||||
Connected = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback method that handles responses from the server
|
||||
/// </summary>
|
||||
/// <param name="message">the response message from the server</param>
|
||||
public void HandleResponse(string message)
|
||||
{
|
||||
string id = JSONParser.GetID(message);
|
||||
|
||||
// because the first messages don't have a serial, we need to check on the id
|
||||
if (id == "session/list")
|
||||
{
|
||||
sessionId = JSONParser.GetSessionID(message, PCs);
|
||||
}
|
||||
else if (id == "tunnel/create")
|
||||
{
|
||||
tunnelId = JSONParser.GetTunnelID(message);
|
||||
if (tunnelId == null)
|
||||
{
|
||||
Write("could not find a valid tunnel id!");
|
||||
OnNoTunnelId?.Invoke();
|
||||
Connected = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (message.Contains("serial"))
|
||||
{
|
||||
//Console.WriteLine("GOT MESSAGE WITH SERIAL: " + message + "\n\n\n");
|
||||
string serial = JSONParser.GetSerial(message);
|
||||
//Console.WriteLine("Got serial " + serial);
|
||||
if (serialResponses.ContainsKey(serial)) serialResponses[serial].Invoke(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// method that sends the speciefied message with the specified serial, and executes the given action upon receivind a reply from the server with this serial.
|
||||
/// </summary>
|
||||
/// <param name="stream">the networkstream to use</param>
|
||||
/// <param name="message">the message to send</param>
|
||||
/// <param name="serial">the serial to check for</param>
|
||||
/// <param name="action">the code to be executed upon reveiving a reply from the server with the specified serial</param>
|
||||
public void SendMessageAndOnResponse(string message, string serial, HandleSerial action)
|
||||
{
|
||||
serialResponses.Add(serial, action);
|
||||
WriteTextMessage(message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// writes a message to the server
|
||||
/// </summary>
|
||||
/// <param name="stream">the network stream to use</param>
|
||||
/// <param name="message">the message to send</param>
|
||||
public void WriteTextMessage(string message)
|
||||
{
|
||||
byte[] msg = Encoding.ASCII.GetBytes(message);
|
||||
byte[] res = new byte[msg.Length + 4];
|
||||
|
||||
Array.Copy(BitConverter.GetBytes(msg.Length), 0, res, 0, 4);
|
||||
Array.Copy(msg, 0, res, 4, msg.Length);
|
||||
|
||||
stream.Write(res);
|
||||
|
||||
//Write("sent message " + message);
|
||||
}
|
||||
public void Write(string msg)
|
||||
{
|
||||
Console.WriteLine( "[ENGINECONNECT] " + msg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
using System;
|
||||
using Hardware;
|
||||
using Hardware.Simulators;
|
||||
using RH_Engine;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace Client
|
||||
{
|
||||
@@ -11,7 +15,7 @@ namespace Client
|
||||
Console.WriteLine("Hello World!");
|
||||
//connect fiets?
|
||||
|
||||
|
||||
Thread.Sleep(20000);
|
||||
Client client = new Client();
|
||||
|
||||
|
||||
@@ -19,13 +23,18 @@ namespace Client
|
||||
{
|
||||
|
||||
}
|
||||
//BLEHandler bLEHandler = new BLEHandler(client);
|
||||
BLEHandler bLEHandler = new BLEHandler(client);
|
||||
|
||||
//bLEHandler.Connect();
|
||||
bLEHandler.Connect();
|
||||
|
||||
BikeSimulator bikeSimulator = new BikeSimulator(client);
|
||||
client.setHandler(bLEHandler);
|
||||
|
||||
bikeSimulator.StartSimulation();
|
||||
|
||||
//BikeSimulator bikeSimulator = new BikeSimulator(client);
|
||||
|
||||
//bikeSimulator.StartSimulation();
|
||||
|
||||
//client.setHandler(bikeSimulator);
|
||||
|
||||
while (true)
|
||||
{
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -6,4 +6,15 @@
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ChartControls" Version="1.3.3" />
|
||||
<PackageReference Include="LiveCharts.Wpf" Version="0.9.7" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ProftaakRH\ProftaakRH.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -17,7 +17,7 @@
|
||||
<ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Grid.ColumnSpan="2" Grid.RowSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Orientation="Vertical">
|
||||
<Label Content="Sensei" Margin="0,0,0,20" HorizontalAlignment="Center"/>
|
||||
<Label x:Name="Label" Content="Yo dokter login" Margin="0,0,0,20" HorizontalAlignment="Center"/>
|
||||
<Label Content="Username" HorizontalContentAlignment="Center"/>
|
||||
<TextBox x:Name="Username" TextWrapping="Wrap" Width="120"/>
|
||||
<Label Content="Password" HorizontalContentAlignment="Center"/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -12,7 +13,6 @@ using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace DokterApp
|
||||
{
|
||||
/// <summary>
|
||||
@@ -20,21 +20,35 @@ namespace DokterApp
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
Del handler;
|
||||
Client client;
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
}
|
||||
|
||||
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void Login_Click_1(object sender, RoutedEventArgs e)
|
||||
{
|
||||
WindowTabs windowTabs = new WindowTabs();
|
||||
handler = windowTabs.NewTab;
|
||||
|
||||
this.Label.Content = "Waiting";
|
||||
this.client = new Client("localhost", 5555, this.Username.Text, this.Password.Text, handler);
|
||||
while (!client.IsConnected())
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
windowTabs.Show();
|
||||
|
||||
this.Close();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public delegate void Del(string message);
|
||||
}
|
||||
|
||||
@@ -31,14 +31,23 @@ namespace DokterApp
|
||||
|
||||
private void Button_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
TabItem newTabItem = new TabItem
|
||||
{
|
||||
Header = "Test",
|
||||
Width = 110,
|
||||
Height = 40
|
||||
};
|
||||
newTabItem.Content = new UserControlForTab();
|
||||
this.tbControl.Items.Add(newTabItem);
|
||||
NewTab("Test");
|
||||
}
|
||||
|
||||
public void NewTab(string username)
|
||||
{
|
||||
Application.Current.Dispatcher.Invoke((Action)delegate {
|
||||
// your code
|
||||
TabItem newTabItem = new TabItem
|
||||
{
|
||||
Header = username,
|
||||
Width = 110,
|
||||
Height = 40
|
||||
};
|
||||
newTabItem.Content = new UserControlForTab();
|
||||
this.tbControl.Items.Add(newTabItem);
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BIN
DokterApp/favicon (1).ico
Normal file
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>
|
||||
@@ -11,7 +11,7 @@ namespace Hardware
|
||||
/// <summary>
|
||||
/// <c>BLEHandler</c> class that handles connection and traffic to and from the bike
|
||||
/// </summary>
|
||||
public class BLEHandler
|
||||
public class BLEHandler : IHandler
|
||||
{
|
||||
List<IDataReceiver> dataReceivers;
|
||||
private BLE bleBike;
|
||||
@@ -25,11 +25,13 @@ namespace Hardware
|
||||
public BLEHandler(IDataReceiver dataReceiver)
|
||||
{
|
||||
this.dataReceivers = new List<IDataReceiver> { dataReceiver };
|
||||
|
||||
}
|
||||
|
||||
public BLEHandler(List<IDataReceiver> dataReceivers)
|
||||
{
|
||||
this.dataReceivers = dataReceivers;
|
||||
|
||||
}
|
||||
|
||||
public void addDataReceiver(IDataReceiver dataReceiver)
|
||||
@@ -43,6 +45,7 @@ namespace Hardware
|
||||
public void Connect()
|
||||
{
|
||||
BLE bleBike = new BLE();
|
||||
|
||||
Thread.Sleep(1000); // We need some time to list available devices
|
||||
|
||||
// List available devices
|
||||
@@ -170,6 +173,11 @@ namespace Hardware
|
||||
/// <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;
|
||||
|
||||
@@ -98,32 +98,7 @@ namespace Hardware.Simulators
|
||||
return hartByte;
|
||||
}
|
||||
|
||||
//Generate an ANT message for resistance
|
||||
public byte[] GenerateResistance(float percentage)
|
||||
{
|
||||
byte[] antMessage = new byte[13];
|
||||
antMessage[0] = 0x4A;
|
||||
antMessage[1] = 0x09;
|
||||
antMessage[2] = 0x4E;
|
||||
antMessage[3] = 0x05;
|
||||
antMessage[4] = 0x30;
|
||||
for (int i = 5; i < 11; i++)
|
||||
{
|
||||
antMessage[i] = 0xFF;
|
||||
}
|
||||
antMessage[11] = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0);
|
||||
//antMessage[11] = 50; //hardcoded for testing
|
||||
|
||||
byte checksum = 0;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
checksum ^= antMessage[i];
|
||||
}
|
||||
|
||||
antMessage[12] = checksum;//reminder that i am dumb :P
|
||||
|
||||
return antMessage;
|
||||
}
|
||||
|
||||
//Calculates the needed variables
|
||||
//Input perlin value
|
||||
@@ -143,20 +118,11 @@ namespace Hardware.Simulators
|
||||
}
|
||||
|
||||
//Set resistance in simulated bike
|
||||
public void setResistance(byte[] bytes)
|
||||
public void setResistance(float percentage)
|
||||
{
|
||||
//TODO check if message is correct
|
||||
if (bytes.Length == 13)
|
||||
{
|
||||
this.resistance = Convert.ToDouble(bytes[11]) / 2;
|
||||
}
|
||||
this.resistance = (byte)Math.Max(Math.Min(Math.Round(percentage / 0.5), 255), 0);
|
||||
}
|
||||
}
|
||||
|
||||
//Interface for receiving a message on the simulated bike
|
||||
interface IHandler
|
||||
{
|
||||
void setResistance(byte[] bytes);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace ProftaakRH
|
||||
IDataReceiver dataReceiver = new DataConverter();
|
||||
BLEHandler bLEHandler = new BLEHandler(dataReceiver);
|
||||
BikeSimulator bikeSimulator = new BikeSimulator(dataReceiver);
|
||||
bikeSimulator.setResistance(bikeSimulator.GenerateResistance(1f));
|
||||
bikeSimulator.setResistance(1);
|
||||
bikeSimulator.StartSimulation();
|
||||
|
||||
|
||||
|
||||
@@ -15,7 +15,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Message", "..\Message\Messa
|
||||
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
|
||||
Global
|
||||
GlobalSection(SharedMSBuildProjectFiles) = preSolution
|
||||
..\Hashing\Hashing.projitems*{5759dd20-7a4f-4d8d-b986-a70a7818c112}*SharedItemsImports = 5
|
||||
..\Hashing\Hashing.projitems*{70277749-d423-4871-b692-2efc5a6ed932}*SharedItemsImports = 13
|
||||
..\Hashing\Hashing.projitems*{b150f08b-13da-4d17-bd96-7e89f52727c6}*SharedItemsImports = 5
|
||||
..\Hashing\Hashing.projitems*{b1ab6f51-a20d-4162-9a7f-b3350b7510fd}*SharedItemsImports = 5
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
|
||||
@@ -4,7 +4,7 @@ using System;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
class Command
|
||||
public class Command
|
||||
{
|
||||
public const string STANDARD_HEAD = "Head";
|
||||
public const string STANDARD_GROUND = "GroundPlane";
|
||||
@@ -83,11 +83,12 @@ namespace RH_Engine
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string DeleteNode(string uuid)
|
||||
public string DeleteNode(string uuid, string serialCode)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/delete",
|
||||
serial = serialCode,
|
||||
data = new
|
||||
{
|
||||
id = uuid,
|
||||
@@ -105,14 +106,13 @@ namespace RH_Engine
|
||||
data = new
|
||||
{
|
||||
name = "dashboard",
|
||||
parent = uuidBike,
|
||||
components = new
|
||||
{
|
||||
panel = new
|
||||
{
|
||||
size = new int[] { 1, 1 },
|
||||
resolution = new int[] { 512, 512 },
|
||||
background = new int[] { 1, 0, 0, 0 },
|
||||
background = new int[] { 1, 1, 1, 1 },
|
||||
castShadow = false
|
||||
}
|
||||
}
|
||||
@@ -151,17 +151,18 @@ namespace RH_Engine
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string bikeSpeed(string uuidPanel, double speed)
|
||||
public string bikeSpeed(string uuidPanel, string serialCode, double speed)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/panel/drawtext",
|
||||
serial = serialCode,
|
||||
data = new
|
||||
{
|
||||
id = uuidPanel,
|
||||
text = "Bike speed placeholder",
|
||||
position = new int[] { 0, 0 },
|
||||
size = 32.0,
|
||||
text = "Speed: " + speed.ToString(),
|
||||
position = new int[] { 4, 24 },
|
||||
size = 36.0,
|
||||
color = new int[] { 0, 0, 0, 1 },
|
||||
font = "segoeui"
|
||||
}
|
||||
@@ -250,16 +251,17 @@ namespace RH_Engine
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
public string MoveTo(string uuid, float[] positionVector, float rotateValue, float speedValue, float timeValue)
|
||||
public string MoveTo(string uuid, string serial, float[] positionVector, string rotateValue, int speedValue, int timeValue)
|
||||
{
|
||||
return MoveTo(uuid, "idk", positionVector, rotateValue, "linear", false, speedValue, timeValue);
|
||||
return MoveTo(uuid, serial, "stop", positionVector, rotateValue, "linear", false, speedValue, timeValue);
|
||||
}
|
||||
|
||||
private string MoveTo(string uuid, string stopValue, float[] positionVector, float rotateValue, string interpolateValue, bool followHeightValue, float speedValue, float timeValue)
|
||||
private string MoveTo(string uuid, string serialCode, string stopValue, float[] positionVector, string rotateValue, string interpolateValue, bool followHeightValue, int speedValue, int timeValue)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
id = "scene/node/moveto",
|
||||
serial = serialCode,
|
||||
data = new
|
||||
{
|
||||
id = uuid,
|
||||
@@ -319,7 +321,7 @@ namespace RH_Engine
|
||||
}
|
||||
}
|
||||
};
|
||||
Console.WriteLine("route command: " + JsonConvert.SerializeObject(Payload(payload)));
|
||||
//Console.WriteLine("route command: " + JsonConvert.SerializeObject(Payload(payload)));
|
||||
return JsonConvert.SerializeObject(Payload(payload));
|
||||
}
|
||||
|
||||
@@ -350,7 +352,7 @@ namespace RH_Engine
|
||||
{
|
||||
return RouteFollow(routeID, nodeID, speedValue, 0, "XYZ", 1, true, new float[] { 0, 0, 0 }, positionOffsetVector);
|
||||
}
|
||||
private string RouteFollow(string routeID, string nodeID, float speedValue, float offsetValue, string rotateValue, float smoothingValue, bool followHeightValue, float[] rotateOffsetVector, float[] positionOffsetVector)
|
||||
public string RouteFollow(string routeID, string nodeID, float speedValue, float offsetValue, string rotateValue, float smoothingValue, bool followHeightValue, float[] rotateOffsetVector, float[] positionOffsetVector)
|
||||
{
|
||||
dynamic payload = new
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@ using System;
|
||||
|
||||
namespace RH_Engine
|
||||
{
|
||||
class JSONParser
|
||||
public class JSONParser
|
||||
{
|
||||
/// <summary>
|
||||
/// returns all the users from the given response
|
||||
@@ -25,6 +25,20 @@ namespace RH_Engine
|
||||
return res;
|
||||
}
|
||||
|
||||
public static string GetIdSceneInfoChild(string msg, string nodeName)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(msg);
|
||||
Newtonsoft.Json.Linq.JArray children = jsonData.data.data.data.children;
|
||||
foreach (dynamic d in children)
|
||||
{
|
||||
if (d.name == nodeName)
|
||||
{
|
||||
return d.uuid;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string GetSessionID(string msg, PC[] PCs)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(msg);
|
||||
@@ -36,7 +50,7 @@ namespace RH_Engine
|
||||
{
|
||||
if (d.clientinfo.host == pc.host && d.clientinfo.user == pc.user)
|
||||
{
|
||||
Console.WriteLine("connecting to {0}, on {1} with id {2}", pc.user, pc.host, d.id);
|
||||
Console.WriteLine("[JSONPARSER] connecting to {0}, on {1} with id {2}", pc.user, pc.host, d.id);
|
||||
return d.id;
|
||||
}
|
||||
}
|
||||
@@ -45,6 +59,12 @@ namespace RH_Engine
|
||||
return null;
|
||||
}
|
||||
|
||||
public static bool GetStatus(string json)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(json);
|
||||
return jsonData.data.data.status == "ok";
|
||||
}
|
||||
|
||||
public static string GetSerial(string json)
|
||||
{
|
||||
dynamic jsonData = JsonConvert.DeserializeObject(json);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using LibNoise.Primitive;
|
||||
using Microsoft.VisualBasic.FileIO;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
@@ -10,13 +11,13 @@ namespace RH_Engine
|
||||
{
|
||||
public delegate void HandleSerial(string message);
|
||||
|
||||
class Program
|
||||
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("HP-ZBOOK-SEM", "Sem"),
|
||||
//new PC("DESKTOP-TV73FKO", "Wouter"),
|
||||
new PC("DESKTOP-SINMKT1", "Ralf van Aert"),
|
||||
//new PC("NA", "Bart")
|
||||
@@ -25,9 +26,11 @@ namespace RH_Engine
|
||||
private static ServerResponseReader serverResponseReader;
|
||||
private static string sessionId = string.Empty;
|
||||
private static string tunnelId = string.Empty;
|
||||
private static string cameraId = string.Empty;
|
||||
private static string routeId = string.Empty;
|
||||
private static string panelId = string.Empty;
|
||||
private static string bikeId = string.Empty;
|
||||
private static string headId = string.Empty;
|
||||
|
||||
private static Dictionary<string, HandleSerial> serialResponses = new Dictionary<string, HandleSerial>();
|
||||
|
||||
@@ -55,6 +58,7 @@ namespace RH_Engine
|
||||
/// <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
|
||||
@@ -109,7 +113,7 @@ namespace RH_Engine
|
||||
|
||||
stream.Write(res);
|
||||
|
||||
Console.WriteLine("sent message " + message);
|
||||
//Console.WriteLine("sent message " + message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -144,40 +148,83 @@ namespace RH_Engine
|
||||
{
|
||||
Command mainCommand = new Command(tunnelID);
|
||||
|
||||
// Reset scene
|
||||
WriteTextMessage(stream, mainCommand.ResetScene());
|
||||
//headId = GetId("Root", stream, mainCommand);
|
||||
//while (headId == string.Empty) { }
|
||||
|
||||
//Get sceneinfo
|
||||
SendMessageAndOnResponse(stream, mainCommand.GetSceneInfoCommand("sceneinfo"), "sceneinfo",
|
||||
(message) =>
|
||||
{
|
||||
//Console.WriteLine("\r\n\r\n\r\nscene info" + message);
|
||||
cameraId = JSONParser.GetIdSceneInfoChild(message, "Camera");
|
||||
string headId = JSONParser.GetIdSceneInfoChild(message, "Head");
|
||||
string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand");
|
||||
string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand");
|
||||
|
||||
//Force(stream, mainCommand.DeleteNode(handLeftId, "deleteHandL"), "deleteHandL", (message) => Console.WriteLine("Left hand deleted"));
|
||||
//Force(stream, mainCommand.DeleteNode(handRightId, "deleteHandR"), "deleteHandR", (message) => Console.WriteLine("Right hand deleted"));
|
||||
});
|
||||
|
||||
//Add route, bike and put camera and bike to follow route at same speed.
|
||||
SendMessageAndOnResponse(stream, mainCommand.RouteCommand("routeID"), "routeID", (message) => routeId = JSONParser.GetResponseUuid(message));
|
||||
SendMessageAndOnResponse(stream, mainCommand.AddBikeModel("bikeID"), "bikeID",
|
||||
(message) =>
|
||||
{
|
||||
bikeId = JSONParser.GetResponseUuid(message);
|
||||
SendMessageAndOnResponse(stream, mainCommand.addPanel("panelAdd", bikeId), "panelAdd",
|
||||
(message) =>
|
||||
{
|
||||
bool speedReplied = false;
|
||||
bool moveReplied = true;
|
||||
panelId = JSONParser.getPanelID(message);
|
||||
WriteTextMessage(stream, mainCommand.ClearPanel(panelId));
|
||||
|
||||
|
||||
SendMessageAndOnResponse(stream, mainCommand.MoveTo(panelId, "panelMove", new float[] { 0f, 0f, 0f }, "Z", 1, 5), "panelMove",
|
||||
(message) =>
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
SendMessageAndOnResponse(stream, mainCommand.bikeSpeed(panelId, "bikeSpeed", 5.0), "bikeSpeed",
|
||||
(message) =>
|
||||
{
|
||||
WriteTextMessage(stream, mainCommand.SwapPanel(panelId));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
//while (!(speedReplied && moveReplied)) { }
|
||||
|
||||
while (cameraId == string.Empty) { }
|
||||
SetFollowSpeed(5.0f, stream, mainCommand);
|
||||
});
|
||||
});
|
||||
|
||||
//Force(stream, mainCommand.addPanel("panelID", bikeId), "panelID",
|
||||
// (message) =>
|
||||
// {
|
||||
// Console.WriteLine("panel response: " + message);
|
||||
// panelId = JSONParser.GetResponseUuid(message);
|
||||
// while(bikeId == string.Empty) { }
|
||||
// SetFollowSpeed(5.0f, stream, mainCommand);
|
||||
// });
|
||||
//SendMessageAndOnResponse(stream, maincommand.addpanel("panelid", bikeid), "panelid",
|
||||
// (message) =>
|
||||
// {
|
||||
// console.writeline("panelid: " + message);
|
||||
// //panelid = jsonparser.getpanelid(message);
|
||||
// panelid = jsonparser.getresponseuuid(message);
|
||||
// while (bikeid == string.empty) { }
|
||||
// setfollowspeed(5.0f, stream, maincommand);
|
||||
// });
|
||||
|
||||
|
||||
|
||||
//WriteTextMessage(stream, mainCommand.TerrainCommand(new int[] { 256, 256 }, null));
|
||||
//string command;
|
||||
|
||||
SendMessageAndOnResponse(stream, mainCommand.AddBikeModel("bikeID"), "bikeID", (message) => bikeId = JSONParser.GetResponseUuid(message));
|
||||
|
||||
SendMessageAndOnResponse(stream, mainCommand.addPanel("panelID", bikeId), "panelID",
|
||||
(message) =>
|
||||
{
|
||||
panelId = JSONParser.GetResponseUuid(message);
|
||||
while (bikeId == string.Empty) { }
|
||||
WriteTextMessage(stream, mainCommand.RouteFollow(routeId, bikeId, 5, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 }));
|
||||
});
|
||||
|
||||
Console.WriteLine("id of head " + GetId(Command.STANDARD_HEAD, stream, mainCommand));
|
||||
|
||||
//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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -255,6 +302,30 @@ namespace RH_Engine
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private static void SetFollowSpeed(float speed, NetworkStream stream, Command mainCommand)
|
||||
{
|
||||
WriteTextMessage(stream, mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 }));
|
||||
WriteTextMessage(stream, mainCommand.RouteFollow(routeId, cameraId, speed));
|
||||
WriteTextMessage(stream, mainCommand.RouteFollow(routeId, panelId, speed, 0, "XYZ", 1, false, new float[] { 0, 0, 0 }, new float[] { 0f, 0f, 150f }));
|
||||
}
|
||||
//string routeID, string nodeID, float speedValue, float offsetValue, string rotateValue, float smoothingValue, bool followHeightValue, float[] rotateOffsetVector, float[] positionOffsetVector)
|
||||
private static void Force(NetworkStream stream, string message, string serial, HandleSerial action)
|
||||
{
|
||||
SendMessageAndOnResponse(stream, message, serial,
|
||||
(message) =>
|
||||
{
|
||||
if (!JSONParser.GetStatus(message))
|
||||
{
|
||||
serialResponses.Remove(serial);
|
||||
Force(stream, message, serial,action);
|
||||
} else
|
||||
{
|
||||
action(message);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ namespace RH_Engine
|
||||
{
|
||||
public delegate void OnResponse(string response);
|
||||
|
||||
class ServerResponseReader
|
||||
public class ServerResponseReader
|
||||
{
|
||||
public OnResponse callback
|
||||
{
|
||||
@@ -31,7 +31,7 @@ namespace RH_Engine
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Starting loop for reading");
|
||||
Console.WriteLine("[SERVERRESPONSEREADER] Starting loop for reading");
|
||||
while (true)
|
||||
{
|
||||
string res = ReadPrefMessage(Stream);
|
||||
|
||||
101
Server/Client.cs
101
Server/Client.cs
@@ -5,6 +5,7 @@ using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Client;
|
||||
using Newtonsoft.Json;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
@@ -19,6 +20,7 @@ namespace Server
|
||||
private SaveData saveData;
|
||||
private string username = null;
|
||||
private DateTime sessionStart;
|
||||
private string fileName;
|
||||
|
||||
|
||||
|
||||
@@ -30,11 +32,13 @@ namespace Server
|
||||
this.communication = communication;
|
||||
this.tcpClient = tcpClient;
|
||||
this.stream = this.tcpClient.GetStream();
|
||||
this.fileName = Directory.GetCurrentDirectory() + "/userInfo.dat";
|
||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
|
||||
}
|
||||
|
||||
private void OnRead(IAsyncResult ar)
|
||||
{
|
||||
|
||||
int receivedBytes = this.stream.EndRead(ar);
|
||||
|
||||
if (totalBufferReceived + receivedBytes > 1024)
|
||||
@@ -103,45 +107,120 @@ namespace Server
|
||||
{
|
||||
Console.WriteLine("Log in");
|
||||
this.username = username;
|
||||
byte[] response = DataParser.getLoginResponse("OK");
|
||||
stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null);
|
||||
this.saveData = new SaveData(Directory.GetCurrentDirectory() + "/" + username, sessionStart.ToString("yyyy-MM-dd HH-mm-ss"));
|
||||
sendMessage(DataParser.getLoginResponse("OK"));
|
||||
sendMessage(DataParser.getStartSessionJson());
|
||||
}
|
||||
else
|
||||
{
|
||||
byte[] response = DataParser.getLoginResponse("wrong username or password");
|
||||
stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null);
|
||||
sendMessage(DataParser.getLoginResponse("wrong username or password"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
byte[] response = DataParser.getLoginResponse("invalid json");
|
||||
stream.BeginWrite(response, 0, response.Length, new AsyncCallback(OnWrite), null);
|
||||
sendMessage(DataParser.getLoginResponse("invalid json"));
|
||||
}
|
||||
break;
|
||||
case DataParser.START_SESSION:
|
||||
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));
|
||||
saveData.WriteDataJSON(Encoding.ASCII.GetString(payloadbytes));
|
||||
|
||||
}
|
||||
else if (DataParser.isRawData(message))
|
||||
{
|
||||
Console.WriteLine(BitConverter.ToString(message));
|
||||
saveData.WriteDataRAW(ByteArrayToString(message));
|
||||
Console.WriteLine(BitConverter.ToString(payloadbytes));
|
||||
if (payloadbytes.Length == 8)
|
||||
{
|
||||
saveData?.WriteDataRAWBike(payloadbytes);
|
||||
}
|
||||
else if (payloadbytes.Length == 2)
|
||||
{
|
||||
saveData?.WriteDataRAWBPM(payloadbytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("received raw data with weird lenght " + BitConverter.ToString(payloadbytes));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void sendMessage(byte[] message)
|
||||
{
|
||||
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
|
||||
}
|
||||
|
||||
private bool verifyLogin(string username, string password)
|
||||
{
|
||||
return username == password;
|
||||
Console.WriteLine("got hashes " + username + "\n" + password);
|
||||
|
||||
|
||||
if (!File.Exists(fileName))
|
||||
{
|
||||
File.Create(fileName);
|
||||
Console.WriteLine("file doesnt exist");
|
||||
newUsers(username, password);
|
||||
Console.WriteLine("true");
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("file exists, located at " + Path.GetFullPath(fileName));
|
||||
string[] usernamesPasswords = File.ReadAllLines(fileName);
|
||||
if (usernamesPasswords.Length == 0)
|
||||
{
|
||||
newUsers(username, password);
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (string s in usernamesPasswords)
|
||||
{
|
||||
string[] combo = s.Split(" ");
|
||||
if (combo[0] == username)
|
||||
{
|
||||
Console.WriteLine("correct info");
|
||||
return combo[1] == password;
|
||||
}
|
||||
|
||||
}
|
||||
Console.WriteLine("combo was not found in file");
|
||||
|
||||
}
|
||||
Console.WriteLine("false");
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
private void newUsers(string username, string password)
|
||||
{
|
||||
|
||||
Console.WriteLine("creating new entry in file");
|
||||
using (StreamWriter sw = File.AppendText(fileName))
|
||||
{
|
||||
sw.WriteLine(username + " " + password);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static string ByteArrayToString(byte[] ba)
|
||||
{
|
||||
StringBuilder hex = new StringBuilder(ba.Length * 2);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using Client;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
@@ -10,6 +12,7 @@ namespace Server
|
||||
{
|
||||
private TcpListener listener;
|
||||
private List<Client> clients;
|
||||
private Client doctor;
|
||||
|
||||
public Communication(TcpListener listener)
|
||||
{
|
||||
@@ -28,9 +31,19 @@ namespace Server
|
||||
|
||||
private void OnConnect(IAsyncResult ar)
|
||||
{
|
||||
|
||||
var tcpClient = listener.EndAcceptTcpClient(ar);
|
||||
Console.WriteLine($"Client connected from {tcpClient.Client.RemoteEndPoint}");
|
||||
clients.Add(new Client(this, tcpClient));
|
||||
if (doctor == null)
|
||||
{
|
||||
doctor = clients.ElementAt(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
doctor.sendMessage(DataParser.getLoginResponse("new client"));
|
||||
}
|
||||
listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
class SaveData
|
||||
{
|
||||
private string path;
|
||||
private string filename;
|
||||
public SaveData(string path, string filename)
|
||||
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;
|
||||
this.filename = filename;
|
||||
if (!Directory.Exists(path))
|
||||
{
|
||||
Directory.CreateDirectory(path);
|
||||
@@ -22,21 +24,103 @@ namespace Server
|
||||
/// <summary>
|
||||
/// Every line is a new data entry
|
||||
/// </summary>
|
||||
|
||||
|
||||
public void WriteDataJSON(string data)
|
||||
{
|
||||
using (StreamWriter sw = File.AppendText(this.path + "/json"+filename+".txt"))
|
||||
using (StreamWriter sw = File.AppendText(this.path + jsonFilename))
|
||||
{
|
||||
sw.WriteLine(data);
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteDataRAW(string data)
|
||||
public void WriteDataRAWBPM(byte[] data)
|
||||
{
|
||||
using (StreamWriter sw = File.AppendText(this.path + "/rawFiets" + filename + ".txt"))
|
||||
if (data.Length != 2)
|
||||
{
|
||||
sw.WriteLine(data);
|
||||
throw new ArgumentException("data should have length of 2");
|
||||
}
|
||||
WriteRawData(data, this.path + rawBPMFilename);
|
||||
}
|
||||
|
||||
public void WriteDataRAWBike(byte[] data)
|
||||
{
|
||||
if (data.Length != 8)
|
||||
{
|
||||
throw new ArgumentException("data should have length of 8");
|
||||
}
|
||||
WriteRawData(data, this.path + rawBikeFilename);
|
||||
}
|
||||
|
||||
private void WriteRawData(byte[] data, string fileLocation)
|
||||
{
|
||||
int length = 0;
|
||||
try
|
||||
{
|
||||
FileInfo fi = new FileInfo(fileLocation);
|
||||
length = (int)fi.Length;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
using (BinaryWriter sw = new BinaryWriter(File.Open(fileLocation, FileMode.Create)))
|
||||
{
|
||||
sw.Seek(length, SeekOrigin.End);
|
||||
sw.Write(data);
|
||||
sw.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// gets BPM graph data out of file.
|
||||
/// if you want 100 datapoints but here are onlny 50, de last 50 datapoint will be 0
|
||||
/// if you want 100 datapoints where it takes the average of 2, the last 75 will be 0
|
||||
/// if the file isn't created yet it will retun null
|
||||
/// </summary>
|
||||
/// <param name="outputSize">the amount of data points for the output</param>
|
||||
/// <param name="averageOver">the amount of data points form the file for one data point in the output</param>
|
||||
/// <returns>byte array with data points from file</returns>
|
||||
public byte[] getBPMgraphData(int outputSize, int averageOver)
|
||||
{
|
||||
if (File.Exists(this.path + rawBPMFilename))
|
||||
{
|
||||
FileInfo fi = new FileInfo(this.path + rawBPMFilename);
|
||||
int length = (int)fi.Length;
|
||||
|
||||
byte[] output = new byte[outputSize];
|
||||
|
||||
int messageSize = 2;
|
||||
int readSize = messageSize * averageOver;
|
||||
byte[] readBuffer = new byte[readSize];
|
||||
|
||||
using (FileStream fileStream = new FileStream(this.path + rawBPMFilename, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
for (int i = 1; i >= outputSize; i++)
|
||||
{
|
||||
if (length - (i * readSize) < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
fileStream.Read(readBuffer, length - (i * readSize), readSize);
|
||||
|
||||
//handling data
|
||||
int total = 0;
|
||||
for (int j = 0; j < averageOver; j++)
|
||||
{
|
||||
total += readBuffer[j * messageSize + 1];
|
||||
}
|
||||
output[i - 1] = (byte)(total / averageOver);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,4 +13,6 @@
|
||||
<ProjectReference Include="..\Client\Client.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\Hashing\Hashing.projitems" Label="Shared" />
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user