Merge remote-tracking branch 'origin/develop' into dataOnTabs

This commit is contained in:
fabjuuuh
2020-10-19 14:05:55 +02:00
15 changed files with 206 additions and 61 deletions

View File

@@ -29,13 +29,13 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Images\Icons\CheckMark.png"> <Content Include="Images\Icons\CheckMark.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Images\Icons\CrossMark.png"> <Content Include="Images\Icons\CrossMark.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Images\Logo\icon1.ico"> <Content Include="Images\Logo\icon1.ico">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Images\re15.jpg"> <Content Include="Images\re15.jpg">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>

View File

@@ -43,6 +43,7 @@ namespace ClientApp.Utils
/// </summary> /// </summary>
private void initEngine() private void initEngine()
{ {
Debug.WriteLine("init engine");
engineConnection = EngineConnection.INSTANCE; engineConnection = EngineConnection.INSTANCE;
engineConnection.OnNoTunnelId = RetryEngineConnection; engineConnection.OnNoTunnelId = RetryEngineConnection;
engineConnection.OnSuccessFullConnection = engineConnected; engineConnection.OnSuccessFullConnection = engineConnected;
@@ -88,6 +89,7 @@ namespace ClientApp.Utils
/// <param name="ar">the result of the async read</param> /// <param name="ar">the result of the async read</param>
private void OnRead(IAsyncResult ar) private void OnRead(IAsyncResult ar)
{ {
Debug.WriteLine("got message in client app");
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead)) if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead))
return; return;
@@ -136,7 +138,7 @@ namespace ClientApp.Utils
} }
break; break;
case DataParser.START_SESSION: case DataParser.START_SESSION:
Console.WriteLine("Session started!"); Debug.WriteLine("Session started!");
this.sessionRunning = true; this.sessionRunning = true;
if (engineConnection.Connected && !engineConnection.FollowingRoute) engineConnection.StartRouteFollow(); if (engineConnection.Connected && !engineConnection.FollowingRoute) engineConnection.StartRouteFollow();
Debug.WriteLine("start"); Debug.WriteLine("start");
@@ -147,18 +149,33 @@ namespace ClientApp.Utils
Debug.WriteLine("stop"); Debug.WriteLine("stop");
break; break;
case DataParser.SET_RESISTANCE: case DataParser.SET_RESISTANCE:
Console.WriteLine("Set resistance identifier"); Debug.WriteLine("Set resistance identifier");
if (this.handler == null) if (this.handler == null)
{ {
Console.WriteLine("handler is null"); // send that the operation was not successful if the handler is null
Debug.WriteLine("handler is null");
sendMessage(DataParser.getSetResistanceResponseJson(false)); sendMessage(DataParser.getSetResistanceResponseJson(false));
} }
else else
{ {
this.handler.setResistance(DataParser.getResistanceFromJson(payloadbytes)); // set the resistance in the vr scene and send that it was successful
float resistance = DataParser.getResistanceFromJson(payloadbytes);
Debug.WriteLine("resistance set was " + resistance);
this.handler.setResistance(resistance);
engineConnection.BikeResistance = resistance;
sendMessage(DataParser.getSetResistanceResponseJson(true)); sendMessage(DataParser.getSetResistanceResponseJson(true));
} }
break; break;
case DataParser.MESSAGE:
Debug.WriteLine("client has received message from doctor");
engineConnection.DoctorMessage = DataParser.getChatMessageFromJson(payloadbytes);
break;
case DataParser.NEW_CONNECTION:
this.LoginViewModel.DoctorConnected(DataParser.getUsernameFromJson(payloadbytes));
break;
case DataParser.DISCONNECT:
this.LoginViewModel.DoctorDisconnected(DataParser.getUsernameFromJson(payloadbytes));
break;
default: default:
Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}");
break; break;

View File

@@ -43,8 +43,8 @@ namespace ClientApp.Utils
private static string headId = string.Empty; private static string headId = string.Empty;
private static string groundPlaneId = string.Empty; private static string groundPlaneId = string.Empty;
private static string terrainId = string.Empty; private static string terrainId = string.Empty;
private static string lastMessage = "No message received yet";
public string DoctorMessage { get; set; }
public float BikeSpeed { get; set; } public float BikeSpeed { get; set; }
public float BikePower { get; set; } public float BikePower { get; set; }
public float BikeBPM { get; set; } public float BikeBPM { get; set; }
@@ -65,6 +65,7 @@ namespace ClientApp.Utils
BikePower = 0; BikePower = 0;
BikeBPM = 0; BikeBPM = 0;
BikeResistance = 50; BikeResistance = 50;
DoctorMessage = "No message received yet";
updateTimer = new System.Timers.Timer(1000); updateTimer = new System.Timers.Timer(1000);
updateTimer.Elapsed += UpdateTimer_Elapsed; updateTimer.Elapsed += UpdateTimer_Elapsed;
updateTimer.AutoReset = true; updateTimer.AutoReset = true;
@@ -224,7 +225,6 @@ namespace ClientApp.Utils
string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand"); string handLeftId = JSONParser.GetIdSceneInfoChild(message, "LeftHand");
string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand"); string handRightId = JSONParser.GetIdSceneInfoChild(message, "RightHand");
groundPlaneId = JSONParser.GetIdSceneInfoChild(message, "GroundPlane"); groundPlaneId = JSONParser.GetIdSceneInfoChild(message, "GroundPlane");
Write("--- Ground plane id is " + groundPlaneId);
}); });
// add the route and set the route id // add the route and set the route id
CreateTerrain(); CreateTerrain();
@@ -324,7 +324,7 @@ namespace ClientApp.Utils
{ {
// TODO check if is drawn // TODO check if is drawn
}); });
SendMessageAndOnResponse(mainCommand.showMessage(panelId, "message", lastMessage), "message", SendMessageAndOnResponse(mainCommand.showMessage(panelId, "message", DoctorMessage), "message",
(message) => (message) =>
{ {
// TODO check if is drawn // TODO check if is drawn
@@ -337,6 +337,7 @@ namespace ClientApp.Utils
private void SetFollowSpeed(float speed) private void SetFollowSpeed(float speed)
{ {
Write("starting route follow");
WriteTextMessage(mainCommand.RouteFollow(routeId, bikeId, speed, new float[] { 0, -(float)Math.PI / 2f, 0 }, new float[] { 0, 0, 0 })); 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)); WriteTextMessage(mainCommand.RouteFollow(routeId, cameraId, speed));
} }

View File

@@ -42,5 +42,15 @@ namespace ClientApp.ViewModels
this.MainWindowViewModel.SelectedViewModel = new MainViewModel(MainWindowViewModel); this.MainWindowViewModel.SelectedViewModel = new MainViewModel(MainWindowViewModel);
} }
} }
internal void DoctorConnected(string name)
{
this.MainWindowViewModel.InfoModel.DoctorConnected = true;
}
internal void DoctorDisconnected(string name)
{
this.MainWindowViewModel.InfoModel.DoctorConnected = false;
}
} }
} }

View File

@@ -9,11 +9,11 @@
<ResourceDictionary> <ResourceDictionary>
<DataTemplate DataType="{x:Type viewModels:MainViewModel}"> <DataTemplate DataType="{x:Type viewModels:MainViewModel}">
<views:MainView /> <views:MainView />
<!-- This is a UserControl --> <!-- This is a Page -->
</DataTemplate> </DataTemplate>
<DataTemplate DataType="{x:Type viewModels:LoginViewModel}"> <DataTemplate DataType="{x:Type viewModels:LoginViewModel}">
<views:LoginView /> <views:LoginView />
<!-- This is a UserControl --> <!-- This is a Page -->
</DataTemplate> </DataTemplate>
<DataTemplate DataType="{x:Type viewModels:ClientInfoViewModel}"> <DataTemplate DataType="{x:Type viewModels:ClientInfoViewModel}">
<views:ClientInfoView/> <views:ClientInfoView/>

View File

@@ -9,12 +9,16 @@
<ItemGroup> <ItemGroup>
<None Remove="img\doctor.ico" /> <None Remove="img\doctor.ico" />
<None Remove="img\patient.png" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="img\doctor.ico"> <Content Include="img\doctor.ico">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="img\patient.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -111,11 +111,10 @@ namespace DoctorApp.Utils
Console.WriteLine("Set resistance identifier"); Console.WriteLine("Set resistance identifier");
break; break;
case DataParser.NEW_CONNECTION: case DataParser.NEW_CONNECTION:
Debug.WriteLine("doctor client new connection"); this.MainViewModel.NewConnectedUser(DataParser.getUsernameFromJson(payloadbytes));
this.MainViewModel.NewConnectedUser(DataParser.getUsernameFromResponseJson(payloadbytes));
break; break;
case DataParser.DISCONNECT: case DataParser.DISCONNECT:
this.MainViewModel.DisconnectedUser(DataParser.getUsernameFromResponseJson(payloadbytes)); this.MainViewModel.DisconnectedUser(DataParser.getUsernameFromJson(payloadbytes));
break; break;
default: default:
Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}");
@@ -135,6 +134,8 @@ namespace DoctorApp.Utils
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
} }
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.client.Connected)
return;
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
} }
@@ -197,6 +198,7 @@ namespace DoctorApp.Utils
public void Dispose() public void Dispose()
{ {
Debug.WriteLine("client dispose called"); Debug.WriteLine("client dispose called");
sendMessage(DataParser.getDisconnectJson(LoginViewModel.Username));
this.stream.Dispose(); this.stream.Dispose();
this.client.Dispose(); this.client.Dispose();
} }

View File

@@ -17,7 +17,6 @@ namespace DoctorApp.ViewModels
class ClientInfoViewModel : ObservableObject class ClientInfoViewModel : ObservableObject
{ {
public PatientInfo PatientInfo { get; set; } public PatientInfo PatientInfo { get; set; }
public ObservableCollection<string> ChatLog { get; set; }
private string _mySelectedItem; private string _mySelectedItem;
public string MySelectedItem public string MySelectedItem
@@ -53,28 +52,24 @@ namespace DoctorApp.ViewModels
this.PatientInfo = new PatientInfo() { Username = username, Status = "Waiting to start" }; this.PatientInfo = new PatientInfo() { Username = username, Status = "Waiting to start" };
this.Chart = new Chart(this.PatientInfo); this.Chart = new Chart(this.PatientInfo);
PatientInfo.ChatLog = new ObservableCollection<string>(); PatientInfo.ChatLog = new ObservableCollection<string>();
ChatLog = new ObservableCollection<string>();
client = mainWindowViewModel.client; client = mainWindowViewModel.client;
StartSession = new RelayCommand(() => StartSession = new RelayCommand(() =>
{ {
client.sendMessage(DataParser.getStartSessionJson(PatientInfo.Username)); client.sendMessage(DataParser.getStartSessionJson(PatientInfo.Username));
PatientInfo.Status = "Session started"; PatientInfo.Status = "Session started";
System.Diagnostics.Debug.WriteLine("patient info status" + PatientInfo.Status);
}); });
StopSession = new RelayCommand(() => StopSession = new RelayCommand(() =>
{ {
client.sendMessage(DataParser.getStopSessionJson(PatientInfo.Username)); client.sendMessage(DataParser.getStopSessionJson(PatientInfo.Username));
PatientInfo.Status = "Session stopped, waiting to start again."; PatientInfo.Status = "Session stopped, waiting to start again.";
System.Diagnostics.Debug.WriteLine("patient info status" + PatientInfo.Status);
}); });
Chat = new RelayCommand<object>((parameter) => Chat = new RelayCommand<object>((parameter) =>
{ {
client.sendMessage(DataParser.getChatJson(PatientInfo.Username, ((TextBox)parameter).Text)); client.sendMessage(DataParser.getChatJson(PatientInfo.Username, ((TextBox)parameter).Text));
PatientInfo.ChatLog.Add(DateTime.Now + ": " + ((TextBox)parameter).Text); PatientInfo.ChatLog.Add(DateTime.Now + ": " + ((TextBox)parameter).Text);
ChatLog.Add(DateTime.Now + ":derp: " + ((TextBox)parameter).Text);
}); });
//TODO RelayCommand ChatToAll //TODO RelayCommand ChatToAll

View File

@@ -3,7 +3,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
using System.Security.Cryptography; using System.Diagnostics;
using System.Text; using System.Text;
using System.Windows.Controls; using System.Windows.Controls;
using Util; using Util;
@@ -27,6 +27,7 @@ namespace DoctorApp.ViewModels
public void NewConnectedUser(string username) public void NewConnectedUser(string username)
{ {
Debug.WriteLine("new tab with name " + username);
App.Current.Dispatcher.Invoke((Action)delegate App.Current.Dispatcher.Invoke((Action)delegate
{ {
Tabs.Add(new ClientInfoViewModel(MainWindowViewModel, username)); Tabs.Add(new ClientInfoViewModel(MainWindowViewModel, username));

View File

@@ -11,7 +11,10 @@
<TabControl TabStripPlacement="Left" ItemsSource="{Binding Tabs}" SelectedItem="{Binding Selected}"> <TabControl TabStripPlacement="Left" ItemsSource="{Binding Tabs}" SelectedItem="{Binding Selected}">
<TabControl.ItemTemplate> <TabControl.ItemTemplate>
<DataTemplate> <DataTemplate>
<TextBlock Text="{Binding PatientInfo.Username}"/> <StackPanel Orientation="Horizontal">
<Image Source="/img/patient.png" Width="25" Margin="0 0 5 0"/>
<TextBlock Text="{Binding PatientInfo.Username}" FontSize="20" MaxWidth="100" Width="100" TextTrimming="CharacterEllipsis"/>
</StackPanel>
</DataTemplate> </DataTemplate>
</TabControl.ItemTemplate> </TabControl.ItemTemplate>
<TabControl.ContentTemplate> <TabControl.ContentTemplate>

BIN
DoctorApp/img/patient.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -1,6 +1,7 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System; using System;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices.WindowsRuntime;
@@ -40,7 +41,11 @@ namespace Util
return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)); return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json));
} }
/// <summary>
/// converts the given string parameter into a message using our protocol.
/// </summary>
/// <param name="messageToSend">the message string to send</param>
/// <returns>a byte array using our protocol to send the message</returns>
public static byte[] GetMessageToSend(string messageToSend) public static byte[] GetMessageToSend(string messageToSend)
{ {
dynamic json = new dynamic json = new
@@ -54,8 +59,12 @@ namespace Util
return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)); return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json));
} }
/// <summary>
/// creates a message for when the doctor wants to log in.
/// </summary>
/// <param name="mUsername">the username of the doctor</param>
/// <param name="mPassword">the (hashed) password of the doctor</param>
/// <returns>a byte array using our protocol that contains the username and password of the doctor</returns>
public static byte[] LoginAsDoctor(string mUsername, string mPassword) public static byte[] LoginAsDoctor(string mUsername, string mPassword)
{ {
dynamic json = new dynamic json = new
@@ -71,23 +80,13 @@ namespace Util
return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)); return Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json));
} }
internal static string getNameFromBytesBike(byte[] bytes) /// <summary>
{ /// gets the username and password from a given message array.
return ASCIIBytesToString(bytes, 8, bytes.Length - 8); /// </summary>
} /// <param name="jsonbytes">the array of bytes containing the message</param>
/// <param name="username">the username variable that the username will be put into</param>
internal static string getNameFromBytesBPM(byte[] bytes) /// <param name="password">the password variable that the password will be put into</param>
{ /// <returns><c>true</c> if the username and password were received correctly, <c>false</c> otherwise</returns>
return ASCIIBytesToString(bytes, 2, bytes.Length - 2);
}
private static string ASCIIBytesToString(byte[] bytes, int offset, int length)
{
byte[] nameArray = new byte[length];
Array.Copy(bytes, offset, nameArray, 0, length);
return Encoding.UTF8.GetString(nameArray);
}
public static bool GetUsernamePassword(byte[] jsonbytes, out string username, out string password) public static bool GetUsernamePassword(byte[] jsonbytes, out string username, out string password)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(jsonbytes)); dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(jsonbytes));
@@ -105,6 +104,12 @@ namespace Util
} }
} }
/// <summary>
/// gets message using our protocol of the given identifier and data.
/// </summary>
/// <param name="mIdentifier">the identifier string of the message</param>
/// <param name="data">the payload data of the message</param>
/// <returns>a byte array containing the json message with the given parameters, using our protocol.</returns>
private static byte[] getJsonMessage(string mIdentifier, dynamic data) private static byte[] getJsonMessage(string mIdentifier, dynamic data)
{ {
dynamic json = new dynamic json = new
@@ -115,6 +120,11 @@ namespace Util
return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01); return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01);
} }
/// <summary>
/// gets a message using our protocol with only the given identifier string.
/// </summary>
/// <param name="mIdentifier">the identifier to put into the message</param>
/// <returns>a byte array containing the json with only the identifier, using our protocol.</returns>
private static byte[] getJsonMessage(string mIdentifier) private static byte[] getJsonMessage(string mIdentifier)
{ {
dynamic json = new dynamic json = new
@@ -124,11 +134,21 @@ namespace Util
return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01); return getMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(json)), 0x01);
} }
/// <summary>
/// gets the login response of the given status
/// </summary>
/// <param name="mStatus">the status of the response</param>
/// <returns>a byte array containing the response for the given status, using our protocol.</returns>
public static byte[] getLoginResponse(string mStatus) public static byte[] getLoginResponse(string mStatus)
{ {
return getJsonMessage(LOGIN_RESPONSE, new { status = mStatus }); return getJsonMessage(LOGIN_RESPONSE, new { status = mStatus });
} }
/// <summary>
/// gets the status of the given json message
/// </summary>
/// <param name="json">the byte array containing a json message using our protocol</param>
/// <returns>the response of the message</returns>
public static string getResponseStatus(byte[] json) public static string getResponseStatus(byte[] json)
{ {
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.status; return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.status;
@@ -266,6 +286,11 @@ namespace Util
return getMessage(payload, 0x01); return getMessage(payload, 0x01);
} }
/// <summary>
/// gets the message to start a session with the given user username
/// </summary>
/// <param name="user">the username of the user we want to start the session for</param>
/// <returns>a byte array containing the message to start the session of the given user, using our protocol.</returns>
public static byte[] getStartSessionJson(string user) public static byte[] getStartSessionJson(string user)
{ {
dynamic data = new dynamic data = new
@@ -275,6 +300,11 @@ namespace Util
return getJsonMessage(START_SESSION, data); return getJsonMessage(START_SESSION, data);
} }
/// <summary>
/// gets the message to stop a session with the given user username
/// </summary>
/// <param name="user">the username of the user we want to stop the session for</param>
/// <returns>a byte array containing the message to stop the session of the given user, using our protocol.</returns>
public static byte[] getStopSessionJson(string user) public static byte[] getStopSessionJson(string user)
{ {
dynamic data = new dynamic data = new
@@ -284,6 +314,12 @@ namespace Util
return getJsonMessage(STOP_SESSION, data); return getJsonMessage(STOP_SESSION, data);
} }
/// <summary>
/// gets the message to set the resistance of the given user with the given resistance.
/// </summary>
/// <param name="user">the username to set the resistance of.</param>
/// <param name="mResistance">the resistance value to set</param>
/// <returns>a byte array containing a json messsage to set the user's resistance, using our protocol.</returns>
public static byte[] getSetResistanceJson(string user,float mResistance) public static byte[] getSetResistanceJson(string user,float mResistance)
{ {
dynamic data = new dynamic data = new
@@ -294,6 +330,11 @@ namespace Util
return getJsonMessage(SET_RESISTANCE, data); return getJsonMessage(SET_RESISTANCE, data);
} }
/// <summary>
/// gets the response message with the given value.
/// </summary>
/// <param name="mWorked">the boolean value to indicate if the operation we want to send a response for was successful or not.</param>
/// <returns>a byte array containing a json message with the response and the given value.</returns>
public static byte[] getSetResistanceResponseJson(bool mWorked) public static byte[] getSetResistanceResponseJson(bool mWorked)
{ {
dynamic data = new dynamic data = new
@@ -303,6 +344,11 @@ namespace Util
return getJsonMessage(SET_RESISTANCE, data); return getJsonMessage(SET_RESISTANCE, data);
} }
/// <summary>
/// gets the message to indicate a new connection for the given user.
/// </summary>
/// <param name="user">the username of the user to start a connection for.</param>
/// <returns>a byte array containing a json message to indicate a new connection for the given user, using our protocol.</returns>
public static byte[] getNewConnectionJson(string user) public static byte[] getNewConnectionJson(string user)
{ {
if (user == null) if (user == null)
@@ -314,6 +360,11 @@ namespace Util
return getJsonMessage(NEW_CONNECTION, data); return getJsonMessage(NEW_CONNECTION, data);
} }
/// <summary>
/// gets the message for when a user has been disconnected.
/// </summary>
/// <param name="user">the username of the user that has been disconnected</param>
/// <returns>a byte array containing a json message to indicate that the given user has disconnected, using our protocol.</returns>
public static byte[] getDisconnectJson(string user) public static byte[] getDisconnectJson(string user)
{ {
dynamic data = new dynamic data = new
@@ -323,31 +374,63 @@ namespace Util
return getJsonMessage(DISCONNECT, data); return getJsonMessage(DISCONNECT, data);
} }
/// <summary>
/// gets the resistance from the given json message
/// </summary>
/// <param name="json">the json messag</param>
/// <returns>the resistance that was in the message</returns>
public static float getResistanceFromJson(byte[] json) public static float getResistanceFromJson(byte[] json)
{ {
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.resistance; return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.resistance;
} }
/// <summary>
/// gets the resistance response from the given json message
/// </summary>
/// <param name="json">the byte array containin the json message</param>
/// <returns>the response of the message, so wether it was successful or not.</returns>
public static bool getResistanceFromResponseJson(byte[] json) public static bool getResistanceFromResponseJson(byte[] json)
{ {
Debug.WriteLine("got message " + Encoding.ASCII.GetString(json));
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.worked; return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.worked;
} }
/// <summary>
/// gets the username from the given response message.
/// </summary>
/// <param name="json">the byte array containin the json message</param>
/// <returns>the username in the message.</returns>
public static string getUsernameFromResponseJson(byte[] json) public static string getUsernameFromResponseJson(byte[] json)
{ {
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.username; return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.username;
} }
/// <summary>
/// gets the chat message from the given json message.
/// </summary>
/// <param name="json">the byte array containin the json message</param>
/// <returns>the chat message in the json message</returns>
public static string getChatMessageFromJson(byte[] json) public static string getChatMessageFromJson(byte[] json)
{ {
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.chat; return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.chat;
} }
/// <summary>
/// gets the username from the given json message.
/// </summary>
/// <param name="json">the byte array containin the json message</param>
/// <returns>the username that is in the message</returns>
public static string getUsernameFromJson(byte[] json) public static string getUsernameFromJson(byte[] json)
{ {
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.username; return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.username;
} }
/// <summary>
/// gets the byte array with the json message to send a message with the given parameters.
/// </summary>
/// <param name="user">the username of the user that wants to send the message</param>
/// <param name="message">the message the user wants to send</param>
/// <returns>a byte array containing a json message with the username and corresponding message, using our protocol.</returns>
public static byte[] getChatJson(string user, string message) public static byte[] getChatJson(string user, string message)
{ {
dynamic data = new dynamic data = new

View File

@@ -93,19 +93,25 @@ namespace Hardware.Simulators
//Generate an ANT message for page 0x10 //Generate an ANT message for page 0x10
private byte[] GenerateBike0x10() private byte[] GenerateBike0x10()
{ {
//SOMEONE FIX THIS!!!!!!!!!
try try
{ {
byte[] bikeByte = { 0x10, Convert.ToByte(equipmentType), Convert.ToByte(elapsedTime * 4 % 64), Convert.ToByte(distanceTraveled), speedArray[0], speedArray[1], Convert.ToByte(BPM), 0xFF }; byte[] bikeByte = { 0x10, check(equipmentType), check(elapsedTime * 4 % 64), check((int)Math.Round(distanceTraveled)), speedArray[0], speedArray[1], check(BPM), 0xFF };
return bikeByte; return bikeByte;
} }
catch (OverflowException e) catch (OverflowException e)
{ {
Debug.WriteLine(e); Debug.WriteLine(e);
return GenerateBike0x10(); byte[] res = { 0x10,0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0xFF};
return res;
} }
} }
private byte check(int value)
{
return value > 255 ? Convert.ToByte(255) : Convert.ToByte(value);
}
//Generate an ANT message for BPM //Generate an ANT message for BPM
private byte[] GenerateHeart() private byte[] GenerateHeart()
{ {

View File

@@ -34,7 +34,7 @@ namespace Server
private void OnRead(IAsyncResult ar) private void OnRead(IAsyncResult ar)
{ {
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead)) if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return; return;
int receivedBytes = this.stream.EndRead(ar); int receivedBytes = this.stream.EndRead(ar);
@@ -65,6 +65,8 @@ namespace Server
} }
} }
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null); this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
} }
@@ -117,11 +119,16 @@ namespace Server
this.communication.StopSessionUser(DataParser.getUsernameFromJson(payloadbytes)); this.communication.StopSessionUser(DataParser.getUsernameFromJson(payloadbytes));
break; break;
case DataParser.SET_RESISTANCE: case DataParser.SET_RESISTANCE:
bool worked = DataParser.getResistanceFromResponseJson(payloadbytes); //bool worked = DataParser.getResistanceFromResponseJson(payloadbytes);
communication.SendMessageToClient(DataParser.getUsernameFromJson(payloadbytes), message);
//set resistance on doctor GUI //set resistance on doctor GUI
break; break;
case DataParser.DISCONNECT: case DataParser.DISCONNECT:
communication.Disconnect(this); communication.LogOff(this);
break;
case DataParser.MESSAGE:
communication.SendMessageToClient(DataParser.getUsernameFromJson(payloadbytes), message);
break; break;
default: default:
Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}"); Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}");

View File

@@ -19,10 +19,12 @@ namespace Server
set set
{ {
this.mDoctor = value; this.mDoctor = value;
this.clients.ForEach((client) => if (this.mDoctor != null)
{ this.clients.ForEach((client) =>
this.mDoctor.sendMessage(DataParser.getNewConnectionJson(client.username)); {
}); this.mDoctor.sendMessage(DataParser.getNewConnectionJson(client.username));
client.sendMessage(DataParser.getNewConnectionJson(this.mDoctor.username));
});
} }
} }
public Communication(TcpListener listener) public Communication(TcpListener listener)
@@ -49,24 +51,27 @@ namespace Server
listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null); listener.BeginAcceptTcpClient(new AsyncCallback(OnConnect), null);
} }
internal void Disconnect(Client client)
{
clients.Remove(client);
Doctor.sendMessage(DataParser.getDisconnectJson(client.username));
}
public void NewLogin(Client client) public void NewLogin(Client client)
{ {
this.clients.Add(client); this.clients.Add(client);
Doctor?.sendMessage(DataParser.getNewConnectionJson(client.username)); if (this.Doctor != null)
{
Doctor.sendMessage(DataParser.getNewConnectionJson(client.username));
client.sendMessage(DataParser.getNewConnectionJson(Doctor.username));
}
} }
public void LogOff(Client client) public void LogOff(Client client)
{ {
if (this.Doctor == client) if (this.Doctor == client)
{ {
this.clients.ForEach((client) =>
{
client.sendMessage(DataParser.getDisconnectJson(this.mDoctor.username));
});
this.Doctor = null; this.Doctor = null;
} }
Doctor?.sendMessage(DataParser.getDisconnectJson(client.username));
this.clients.Remove(client); this.clients.Remove(client);
} }
@@ -94,5 +99,16 @@ namespace Server
} }
} }
public void SendMessageToClient(string user, byte[] message)
{
foreach (Client c in clients)
{
if (c.username == user)
{
c.sendMessage(message);
}
}
}
} }
} }