5 Commits

Author SHA1 Message Date
Sem van der Hoeven
1f163325cf [FIX] fixed the panel not showing, it was because of the animation. removed it for now and it works 2020-10-29 17:09:20 +01:00
Sem van der Hoeven
1c7f9cf70a [FIX] fixed doctor buffer overflow 2020-10-28 13:23:20 +01:00
Sem van der Hoeven
5f2e325cb1 [ADD] added chat to all method from docter, it works but there is sometimes an error in the doctor client app that the buffer in OnRead is full, so will try to fix that tomorrow 2020-10-27 21:35:07 +01:00
Sem van der Hoeven
cda8b47ca3 [
ADD] added message sending to all clients, doesn't work yet
2020-10-27 21:24:47 +01:00
Sem van der Hoeven
fab3ed7705 [EDIT] made seperate method for sending message 2020-10-27 20:59:46 +01:00
15 changed files with 105 additions and 219 deletions

View File

@@ -43,7 +43,7 @@ namespace ClientApp.Utils
/// </summary>
private void initEngine()
{
Debug.WriteLine("init engine");
Debug.WriteLine("[CLIENT] init engine");
engineConnection = EngineConnection.INSTANCE;
engineConnection.OnNoTunnelId = RetryEngineConnection;
engineConnection.OnSuccessFullConnection = engineConnected;
@@ -184,12 +184,15 @@ namespace ClientApp.Utils
else if (DataParser.isRawDataBikeServer(messageBytes))
{
Console.WriteLine($"Received data: {BitConverter.ToString(payloadbytes)}");
}
}
totalBufferReceived -= expectedMessageLength;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
}
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.client.Connected)
return;
ar.AsyncWaitHandle.WaitOne();
this.stream.BeginRead(this.buffer, 0, this.buffer.Length, new AsyncCallback(OnRead), null);
}

View File

@@ -27,7 +27,7 @@ namespace ClientApp.Utils
//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")
@@ -71,7 +71,7 @@ namespace ClientApp.Utils
updateTimer.AutoReset = true;
updateTimer.Enabled = false;
noVRResponseTimer = new System.Timers.Timer(15000);
noVRResponseTimer = new System.Timers.Timer(30000);
noVRResponseTimer.Elapsed += noVRResponseTimeout;
noVRResponseTimer.AutoReset = false;
noVRResponseTimer.Enabled = false;
@@ -236,14 +236,14 @@ namespace ClientApp.Utils
Write("Starting route follow...");
FollowingRoute = true;
SendMessageAndOnResponse(mainCommand.AddBikeModelAnim("bikeID", 0.01f), "bikeID",
SendMessageAndOnResponse(mainCommand.AddBikeModel("bikeID"), "bikeID",
(message) =>
{
bikeId = JSONParser.GetResponseUuid(message);
SendMessageAndOnResponse(mainCommand.addPanel("panelAdd", bikeId), "panelAdd",
(message) =>
{
Write("got panel id");
panelId = JSONParser.getPanelID(message);
WriteTextMessage(mainCommand.ColorPanel(panelId));
@@ -295,6 +295,7 @@ namespace ClientApp.Utils
public void UpdateInfoPanel()
{
Write("updating info panel");
ShowPanel(BikeSpeed, (int)BikeBPM, (int)BikePower, (int)BikeResistance);
WriteTextMessage(mainCommand.RouteSpeed(BikeSpeed, bikeId));
WriteTextMessage(mainCommand.RouteSpeed(BikeSpeed, cameraId));

View File

@@ -16,7 +16,7 @@ namespace ClientApp.ViewModels
public string Username { get; set; }
public ICommand LoginCommand { get; set; }
public bool LoginStatus { get; set; } = false;
public bool LoginStatus { get; set; }
public bool InvertedLoginStatus { get; set; }

View File

@@ -19,7 +19,9 @@
<Label Content="Password" HorizontalContentAlignment="Center"/>
<PasswordBox x:Name="Password" Width="120" Util:FocusAdvancement.AdvancesByEnterKey="True"/>
<Button x:Name="Login" Content="Login" Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=Password}" Margin="0,20,0,0" Width="120"/>
<Label Content="Login failed" Foreground="Red" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Background="Transparent" IsEnabled="{Binding InvertedLoginStatus}"/>
<Popup IsOpen="{Binding InvertedLoginStatus}" PopupAnimation = "Slide" HorizontalAlignment="Center">
<Label Content="Login failed" Foreground="Red" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Background="Transparent"/>
</Popup>
</StackPanel>
</DockPanel>
</Page>

View File

@@ -25,7 +25,6 @@
<PackageReference Include="AsyncAwaitBestPractices.MVVM" Version="4.3.0" />
<PackageReference Include="LiveCharts.Wpf" Version="0.9.7" />
<PackageReference Include="MvvmLightLibsStd10" Version="5.4.1.1" />
<PackageReference Include="Prism.Wpf" Version="8.0.0.1909" />
<PackageReference Include="PropertyChanged.Fody" Version="3.2.9" />
</ItemGroup>

View File

@@ -1,11 +1,9 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using DoctorApp.ViewModels;
using Microsoft.Win32;
using ProftaakRH;
using Util;
@@ -131,24 +129,7 @@ namespace DoctorApp.Utils
{
MainViewModel.TransferDataToClientBPM(payloadbytes);
}
else if (DataParser.IsHistoricBikeData(messageBytes))
{
// todo change to name of patient
string name = MainViewModel.Tabs[0].PatientInfo.Username;
string result = "PATIENT INFO FOR " + name + "\n\n";
for (int i = 0; i < payloadbytes.Length; i += 8)
{
byte[] res = new byte[8];
Array.Copy(payloadbytes, i, res, 0, 8);
result += handleBikeHistory(res);
}
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/" + name + ".txt";
File.WriteAllText(path,result);
}
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength)); //maybe unsafe idk
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength)); //maybe unsafe idk
totalBufferReceived -= expectedMessageLength;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
}
@@ -159,40 +140,11 @@ namespace DoctorApp.Utils
}
private string handleBikeHistory(byte[] bytes)
{
string res = string.Empty;
switch (bytes[0])
{
case 0x10:
res += "Time elapsed: " + bytes[2] / 4 + "s\n";
res += "Distance traveled: " + bytes[3] + "\n";
int input = bytes[4] | (bytes[5] << 8);
res += $"Speed {input * 0.01}m/s\n";
res += $"Heart rate: { Convert.ToString(bytes[6], 10)}";
break;
case 0x19:
res += $"RPM: {bytes[2]}\n";
int accumPower = bytes[3] | (bytes[4] << 8);
res += $"Accumulated power: {accumPower} watt\n";
int instantPower = (bytes[5]) | (bytes[6] & 0b00001111) << 8;
if (instantPower != 0xFFF)
{
res += $"Instant power: {instantPower} watt\n";
}
break;
}
return res + "\n";
}
/// <summary>
/// starts sending a message to the server
/// </summary>
/// <param name="message">the message to send</param>
public void sendMessage(byte[] message)
/// <summary>
/// starts sending a message to the server
/// </summary>
/// <param name="message">the message to send</param>
public void sendMessage(byte[] message)
{
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), null);
}

View File

@@ -41,16 +41,16 @@ namespace DoctorApp.ViewModels
public ICommand SetResistance { get; set; }
public ICommand SaveHistoricData { get; set; }
public MainWindowViewModel MainWindowViewModel { get; set; }
private Client client;
private MainViewModel parent;
public Chart Chart { get; set; }
public ClientInfoViewModel(MainWindowViewModel mainWindowViewModel, string username)
public ClientInfoViewModel(MainViewModel parent,MainWindowViewModel mainWindowViewModel, string username)
{
MainWindowViewModel = mainWindowViewModel;
this.parent = parent;
this.PatientInfo = new PatientInfo() { Username = username, Status = "Waiting to start" };
this.Chart = new Chart(this.PatientInfo);
PatientInfo.ChatLog = new ObservableCollection<string>();
@@ -70,12 +70,17 @@ namespace DoctorApp.ViewModels
Chat = new RelayCommand<object>((parameter) =>
{
client.sendMessage(DataParser.getChatJson(PatientInfo.Username, ((TextBox)parameter).Text));
PatientInfo.ChatLog.Add(DateTime.Now + ": " + ((TextBox)parameter).Text);
SendMessageToClient(PatientInfo.Username, ((TextBox)parameter).Text);
});
//TODO RelayCommand ChatToAll
ChatToAll = new RelayCommand<object>((parameter) =>
{
Debug.WriteLine("[CLIENTINFOVIEWMODEL] sending message to all clients");
this.parent?.SendToAllClients(((TextBox)parameter).Text);
});
SetResistance = new RelayCommand<object>((parameter) =>
{
Debug.WriteLine("resistance");
@@ -83,23 +88,19 @@ namespace DoctorApp.ViewModels
PatientInfo.Resistance = float.Parse(((TextBox)parameter).Text);
});
// request the historic data from the server
this.SaveHistoricData = new RelayCommand<object>((parameter) =>
{
this.client.sendMessage(DataParser.GetGetFileMessage(PatientInfo.Username));
// data is stored on the server
// send request to server that we want to get the current historic data from the patient
// server sends this back
// we parse it
});
}
public void BPMData(byte[] bytes)
public void SendMessageToClient(string username, string text)
{
client.sendMessage(DataParser.getChatJson(username, text));
PatientInfo.ChatLog.Add(DateTime.Now + ": " + text);
}
public void BPMData(byte [] bytes)
{
//TODO
//Parsen van de data you fuck
if (bytes[0] == 0x00)
if(bytes[0] == 0x00)
{
}
@@ -107,13 +108,13 @@ namespace DoctorApp.ViewModels
{
PatientInfo.BPM = bytes[1];
if (MySelectedItem == "BPM")
{
{
Chart.NewValue(PatientInfo.BPM);
}
}
}
public void BikeData(byte[] bytes)

View File

@@ -30,7 +30,7 @@ namespace DoctorApp.ViewModels
Debug.WriteLine("new tab with name " + username);
App.Current.Dispatcher.Invoke((Action)delegate
{
Tabs.Add(new ClientInfoViewModel(MainWindowViewModel, username));
Tabs.Add(new ClientInfoViewModel(this,MainWindowViewModel, username));
});
}
@@ -72,6 +72,15 @@ namespace DoctorApp.ViewModels
}
}
}
internal void SendToAllClients(string text)
{
Debug.WriteLine("[MAINVIEWMODEL] Sending message to all clients: " + text);
foreach (ClientInfoViewModel item in Tabs)
{
item.SendMessageToClient(item.PatientInfo.Username, text);
}
}
}

View File

@@ -6,6 +6,7 @@ using System.Windows.Input;
using DoctorApp.Models;
using DoctorApp.Utils;
using Util.MagicCode;
using System;
namespace DoctorApp.ViewModels
{

View File

@@ -18,20 +18,16 @@
<RowDefinition Height="180*"/>
<RowDefinition Height="180*"/>
</Grid.RowDefinitions>
<Grid Grid.RowSpan="2" Margin="0,0,0,22">
<StackPanel Orientation="Horizontal" >
<StackPanel.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Margin" Value="0,0,20,0"/>
</Style>
</StackPanel.Resources>
<Label Content="{Binding Path=PatientInfo.Username}"/>
<Label Content="{Binding Path=PatientInfo.Status}"/>
</StackPanel>
<Button Content="Save Historic Data" HorizontalAlignment="Right" VerticalAlignment="Center" Padding="5" Command="{Binding SaveHistoricData}"/>
</Grid>
<StackPanel Margin="0,10,0,0" Grid.Row="2">
<StackPanel Orientation="Horizontal" Grid.RowSpan="2" Margin="0,0,0,22">
<StackPanel.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Margin" Value="0,0,20,0"/>
</Style>
</StackPanel.Resources>
<Label Content="{Binding Path=PatientInfo.Username}"/>
<Label Content="{Binding Path=PatientInfo.Status}"/>
</StackPanel>
<StackPanel Margin="0,10,0,0" Grid.RowSpan="2" Grid.Row="1">
<StackPanel.Resources>
<Style TargetType="{x:Type DockPanel}">
<Setter Property="Margin" Value="0,20,0,0"/>
@@ -61,6 +57,7 @@
<ListBox Name="ChatBox" ItemsSource="{Binding PatientInfo.ChatLog}" Grid.Column="1" Margin="59,41,0,0" Grid.RowSpan="3"/>
<TextBox Name="textBox_Chat" Grid.Column="1" HorizontalAlignment="Left" Margin="59,10,0,0" Grid.Row="3" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="235"/>
<Button x:Name="Send" Content="Send" Grid.Column="1" HorizontalAlignment="Left" Margin="59,33,0,0" Grid.Row="3" VerticalAlignment="Top" Command="{Binding Chat}" CommandParameter="{Binding ElementName=textBox_Chat}"/>
<Button x:Name="SendToAll" Content="Send to all clients" Grid.Column="1" HorizontalAlignment="Left" Margin="107,33,0,0" Grid.Row="3" VerticalAlignment="Top" Command="{Binding ChatToAll}" CommandParameter="{Binding ElementName=textBox_Chat}"/>
<Button Content="Start Session" Grid.Column="1" HorizontalAlignment="Left" Margin="69,86,0,0" Grid.Row="3" VerticalAlignment="Top" Width="97" Command="{Binding StartSession}" CommandParameter=""/>
<Button Content="Stop Session" Grid.Column="1" HorizontalAlignment="Left" Margin="187,86,0,0" Grid.Row="3" VerticalAlignment="Top" Width="97" Command="{Binding StopSession}" CommandParameter=""/>
<TextBox x:Name="textBox_SetResistance" Grid.Column="1" HorizontalAlignment="Left" Margin="69,128,0,0" Grid.Row="3" TextWrapping="Wrap" VerticalAlignment="Top" Width="97"/>

View File

@@ -10,7 +10,7 @@
AllowsTransparency="True"
MinHeight="{Binding MinimumHeight}"
MinWidth="{Binding MinimumWidth}"
Title="MainWindow" Height="800" Width="1500">
Title="MainWindow" Height="500" Width="900">
<Window.Resources>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="Template">

View File

@@ -4,11 +4,9 @@ using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Printing.IndexedProperties;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Media.Animation;
namespace Util
{
@@ -23,7 +21,6 @@ namespace Util
public const string DISCONNECT = "DISCONNECT";
public const string LOGIN_DOCTOR = "LOGIN DOCTOR";
public const string MESSAGE = "MESSAGE";
public const string GET_FILE = "GET FILE";
/// <summary>
/// makes the json object with LOGIN identifier and username and password
/// </summary>
@@ -73,7 +70,7 @@ namespace Util
return getName(bytes, 2, bytes.Length - 2);
}
private static string getName(byte[] bytes, int offset, int lenght)
private static string getName(byte[] bytes , int offset, int lenght)
{
byte[] nameArray = new byte[lenght];
Array.Copy(bytes, offset, nameArray, 0, lenght);
@@ -243,12 +240,6 @@ namespace Util
return bytes[4] == 0x05;
}
public static bool IsHistoricBikeData(byte[] bytes)
{
if (bytes.Length <= 5) throw new ArgumentException("bytes too short");
return bytes[4] == 0x06;
}
/// <summary>
/// constructs a message with the payload, messageId and clientId
@@ -293,17 +284,13 @@ namespace Util
public static byte[] GetRawBPMDataDoctor(byte[] payload, string username)
{
return GetRawDataDoctor(payload, username, 0x05);
return GetRawDataDoctor(payload,username,0x05);
}
private static byte[] GetRawDataDoctor(byte[] payload, string username, byte messageID)
{
Debug.WriteLine(BitConverter.ToString(Encoding.ASCII.GetBytes(username)));
byte[] nameArray = Encoding.ASCII.GetBytes(username);
byte[] total = new byte[nameArray.Length + payload.Length];
Array.Copy(payload, 0, total, 0, payload.Length);
Array.Copy(nameArray, 0, total, payload.Length, nameArray.Length);
return getMessage(total, messageID);
return getMessage(payload.Concat(Encoding.ASCII.GetBytes(username)).ToArray(), messageID);
}
/// <summary>
@@ -344,14 +331,14 @@ namespace Util
};
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
{
@@ -443,7 +430,7 @@ namespace Util
/// <returns>the chat message in the json message</returns>
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>
@@ -479,32 +466,6 @@ namespace Util
return data;
}
public static byte[] GetGetFileMessage(string mUsername)
{
if (mUsername == null)
{
throw new ArgumentNullException("username null");
}
dynamic data = new
{
username = mUsername,
};
return getJsonMessage(GET_FILE, data);
}
public static string GetUsernameFromGetFileBytes(byte[] json)
{
return ((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.username;
}
public static string GetDateFromGetFileBytes(byte[] json)
{
return ((string)((dynamic)JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json))).data.dateTime);
}
public static byte[] GetFileMessage(byte[] file)
{
return getMessage(file, 0x06);
}
}
}

View File

@@ -124,11 +124,13 @@ namespace RH_Engine
position = new float[]
{
-1.5f, 1f, 0f
//0f,0f,0f
},
scale = 1,
rotation = new int[]
{
-30, 90,0
//0,0,0
}
},
panel = new

View File

@@ -19,9 +19,9 @@ namespace RH_Engine
//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("DESKTOP-SINMKT1", "Ralf van Aert"),
//new PC("NA", "Bart")
};
@@ -94,7 +94,7 @@ namespace RH_Engine
if (serialResponses.ContainsKey(serial))
{
serialResponses[serial].Invoke(message);
serialResponses.Remove(serial);
//serialResponses.Remove(serial);
}
}
}
@@ -181,39 +181,41 @@ namespace RH_Engine
//Force(stream, mainCommand.DeleteNode(handRightId, "deleteHandR"), "deleteHandR", (message) => Console.WriteLine("Right hand deleted"));
});
CreateTerrain(stream, mainCommand);
//CreateTerrain(stream, mainCommand);
//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.AddBikeModelAnim("bikeID", 0.01f), "bikeID",
//SendMessageAndOnResponse(stream, mainCommand.RouteCommand("routeID"), "routeID", (message) => routeId = JSONParser.GetResponseUuid(message));
SendMessageAndOnResponse(stream, mainCommand.AddBikeModelAnim("bikeID",0.01f), "bikeID",
(message) =>
{
bikeId = JSONParser.GetResponseUuid(message);
Console.WriteLine("got bike id " + bikeId);
SendMessageAndOnResponse(stream, mainCommand.addPanel("panelAdd", bikeId), "panelAdd",
(message) =>
{
bool speedReplied = false;
bool moveReplied = true;
Console.WriteLine(message);
panelId = JSONParser.getPanelID(message);
Console.WriteLine("got panel id " + panelId);
showPanel(stream, mainCommand);
//while (!(speedReplied && moveReplied)) { }
while (cameraId == string.Empty) { }
SetFollowSpeed(5.0f, stream, mainCommand);
WriteTextMessage(stream, mainCommand.RoadCommand(routeId, "road"));
WriteTextMessage(stream, mainCommand.ShowRoute("showRouteFalse", false));
//while (cameraId == string.Empty) { }
//SetFollowSpeed(5.0f, stream, mainCommand);
//WriteTextMessage(stream, mainCommand.RoadCommand(routeId, "road"));
//WriteTextMessage(stream, mainCommand.ShowRoute("showRouteFalse", false));
});
});
string groundplaneId = GetId("GroundPlane", stream, mainCommand);
WriteTextMessage(stream, mainCommand.DeleteNode(groundplaneId, "none"));
//string groundplaneId = GetId("GroundPlane", stream, mainCommand);
//WriteTextMessage(stream, mainCommand.DeleteNode(groundplaneId, "none"));
PlaceHouses(stream, mainCommand);
//PlaceHouses(stream, mainCommand);
WriteTextMessage(stream, mainCommand.SkyboxCommand(DateTime.Now.Hour));
//WriteTextMessage(stream, mainCommand.SkyboxCommand(DateTime.Now.Hour));
}
@@ -343,31 +345,36 @@ namespace RH_Engine
private static void showPanel(NetworkStream stream, Command mainCommand)
{
WriteTextMessage(stream, mainCommand.ColorPanel(panelId));
//WriteTextMessage(stream, mainCommand.ColorPanel(panelId));
WriteTextMessage(stream, mainCommand.ClearPanel(panelId));
SendMessageAndOnResponse(stream, mainCommand.showBikespeed(panelId, "bikeSpeed", bikeSpeed), "bikeSpeed",
(message) =>
{
Console.WriteLine(message);
// TODO check if is drawn
});
SendMessageAndOnResponse(stream, mainCommand.showHeartrate(panelId, "bpm", bpm), "bpm",
(message) =>
{
Console.WriteLine(message);
// TODO check if is drawn
});
SendMessageAndOnResponse(stream, mainCommand.showPower(panelId, "power", power), "power",
(message) =>
{
Console.WriteLine(message);
// TODO check if is drawn
});
SendMessageAndOnResponse(stream, mainCommand.showResistance(panelId, "resistance", resistance), "resistance",
(message) =>
{
Console.WriteLine(message);
// TODO check if is drawn
});
SendMessageAndOnResponse(stream, mainCommand.showMessage(panelId, "message", lastMessage), "message",
(message) =>
{
Console.WriteLine(message);
// TODO check if is drawn
});

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
@@ -24,11 +23,8 @@ namespace Server
private DateTime sessionStart;
private string fileName;
private Timer timer;
private volatile byte[] BikeDataBuffer;
private volatile byte[] BPMDataBuffer;
private bool BPMdata = false;
private bool Bikedata = false;
private object token = new object { };
private byte[] BikeDataBuffer;
private byte[] BPMDataBuffer;
public Client(Communication communication, TcpClient tcpClient)
{
@@ -41,9 +37,8 @@ namespace Server
this.BikeDataBuffer = new byte[16];
this.BPMDataBuffer = new byte[2];
this.timer.Interval = 1000;
this.timer.AutoReset = false;
this.timer.AutoReset = true;
this.timer.Elapsed += SendDataToDoctor;
Console.WriteLine("token is " + token);
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
}
@@ -147,9 +142,6 @@ namespace Server
case DataParser.MESSAGE:
communication.SendMessageToClient(DataParser.getUsernameFromJson(payloadbytes), message);
break;
case DataParser.GET_FILE:
getClientBikeData(payloadbytes);
break;
default:
Console.WriteLine($"Received json with identifier {identifier}:\n{Encoding.ASCII.GetString(payloadbytes)}");
break;
@@ -162,53 +154,16 @@ namespace Server
}
else if (DataParser.isRawDataBikeServer(message))
{
//Bikedata = true;
saveData?.WriteDataRAWBike(payloadbytes);
lock (token)
{
Array.Copy(this.BikeDataBuffer, 0, this.BikeDataBuffer, 8, 8);
Array.Copy(payloadbytes, 0, this.BikeDataBuffer, 0, 8);
}
//this.communication.Doctor?.sendMessage(DataParser.GetRawBikeDataDoctor(payloadbytes, this.username));
Array.Copy(this.BikeDataBuffer, 0, this.BikeDataBuffer, 8, 8);
Array.Copy(payloadbytes, 0, this.BikeDataBuffer, 0, 8);
}
else if (DataParser.isRawDataBPMServer(message))
{
//BPMdata = true;
saveData?.WriteDataRAWBPM(payloadbytes);
lock (token)
{
Array.Copy(payloadbytes, 0, this.BPMDataBuffer, 0, 2);
}
//this.communication.Doctor?.sendMessage(DataParser.GetRawBPMDataDoctor(payloadbytes, this.username));
}
}
private void getClientBikeData(byte[] payloadbytes)
{
//ugly
//get the raw bike data of the user with the specified username
string username = DataParser.GetUsernameFromGetFileBytes(payloadbytes);
string path = Directory.GetCurrentDirectory() + "/" + username + "/";
string bytes = string.Empty;
StringBuilder sb = new StringBuilder(bytes);
try
{
DirectoryInfo dirInf = new DirectoryInfo(Directory.GetCurrentDirectory() + "/" + username + "/");
DirectoryInfo[] directoryInfos = dirInf.GetDirectories();
DirectoryInfo latest = directoryInfos[directoryInfos.Length - 1];
path = path + latest.Name + "/rawBike.bin";
FileInfo fi = new FileInfo(path);
if ((int)fi.Length >= 1024) return;
}
catch (Exception e)
{
Debug.WriteLine("[SERVER CLIENT] excetion while trying to get raw bike data: " + e.Message);
Array.Copy(payloadbytes, 0, this.BikeDataBuffer, 0, 2);
}
Debug.WriteLine("[SERVER CLIENT] about to send " +sb.ToString());
communication.Doctor.sendMessage(DataParser.GetFileMessage(File.ReadAllBytes(path)));
}
private bool handleLogin(byte[] payloadbytes)
@@ -309,13 +264,9 @@ namespace Server
private void SendDataToDoctor(object sender, ElapsedEventArgs e)
{
lock (token)
{
this.communication.Doctor?.sendMessage(DataParser.GetRawBikeDataDoctor(this.BikeDataBuffer.Take(8).ToArray(), this.username));
this.communication.Doctor?.sendMessage(DataParser.GetRawBikeDataDoctor(this.BikeDataBuffer.Skip(8).ToArray(), this.username));
this.communication.Doctor?.sendMessage(DataParser.GetRawBPMDataDoctor(this.BPMDataBuffer, this.username));
}
this.timer.Start();
this.communication.Doctor?.sendMessage(DataParser.GetRawBikeDataDoctor(this.BikeDataBuffer.Take(8).ToArray(), this.username));
this.communication.Doctor?.sendMessage(DataParser.GetRawBikeDataDoctor(this.BikeDataBuffer.Skip(8).ToArray(), this.username));
this.communication.Doctor?.sendMessage(DataParser.GetRawBikeDataDoctor(this.BikeDataBuffer, this.username));
}
}
}