Vastgelopen
This commit is contained in:
251
DoctorApp/Utils/Client.cs
Normal file
251
DoctorApp/Utils/Client.cs
Normal file
@@ -0,0 +1,251 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using DoctorApp.ViewModels;
|
||||
using ProftaakRH;
|
||||
|
||||
namespace DoctorApp.Utils
|
||||
{
|
||||
public delegate void EngineCallback();
|
||||
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 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>
|
||||
/// 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")
|
||||
{
|
||||
Debug.WriteLine("Username and password correct!");
|
||||
this.LoginViewModel.setLoginStatus(true);
|
||||
this.connected = true;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LoginViewModel.setLoginStatus(false);
|
||||
Debug.WriteLine($"login failed \"{responseStatus}\"");
|
||||
}
|
||||
break;
|
||||
case DataParser.START_SESSION:
|
||||
Console.WriteLine("Session started!");
|
||||
this.sessionRunning = true;
|
||||
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);
|
||||
|
||||
|
||||
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:
|
||||
|
||||
if (canSendToEngine) engineConnection.BikeSpeed = (bytes[4] | (bytes[5] << 8)) * 0.01f;
|
||||
break;
|
||||
case 0x19:
|
||||
if (canSendToEngine) engineConnection.BikePower = (bytes[5]) | (bytes[6] & 0b00001111) << 8;
|
||||
break;
|
||||
}*/
|
||||
|
||||
|
||||
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
DoctorApp/Utils/DataParser.cs
Normal file
206
DoctorApp/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 DoctorApp.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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
12
DoctorApp/Utils/ObservableObject.cs
Normal file
12
DoctorApp/Utils/ObservableObject.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
|
||||
namespace DoctorApp.Utils
|
||||
{
|
||||
public abstract class ObservableObject : INotifyPropertyChanged
|
||||
{
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user