Compare commits

1 Commits
Author SHA1 Message Date
kennyboy55 465ff5ea8a Merge pull request #1 from KettlerX7AvansA5/develop
Merge develop into master
2015-10-02 11:06:00 +02:00
11 changed files with 115 additions and 641 deletions
-162
View File
@@ -1,162 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ErgometerLibrary
{
static class AESEncrypt
{
// Change these keys
private static byte[] Key = { 47, 20, 192, 222, 214, 221, 193, 151, 182, 182, 20, 246, 80, 235, 182, 216, 116, 141, 188, 191, 13, 159, 1, 137, 151, 150, 29, 171, 240, 21, 251, 252 };
private static byte[] Vector = { 147, 16, 78, 223, 97, 189, 43, 197, 244, 102, 242, 123, 184, 101, 75, 203 };
private static ICryptoTransform EncryptorTransform, DecryptorTransform;
private static System.Text.UTF8Encoding UTFEncoder;
static AESEncrypt()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(Key, Vector);
DecryptorTransform = rm.CreateDecryptor(Key, Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public static string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue));
}
/// Encrypt some text and return an encrypted byte array.
public static byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public static string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString));
}
/// Decryption when working with byte arrays.
public static string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return UTFEncoder.GetString(decryptedBytes);
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public static byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public static string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
}
-63
View File
@@ -1,63 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ErgometerLibrary.Chat
{
public class ChatItem : Panel
{
private Label messageLabel, timeLabel;
public ChatItem(ChatMessage chat) : base()
{
this.messageLabel = new Label();
this.timeLabel = new Label();
this.AutoSize = true;
this.setAppearance(chat.IsDoctor);
this.Controls.Add(this.messageLabel);
this.Controls.Add(this.timeLabel);
this.MinimumSize = new System.Drawing.Size(150, 60);
this.Name = "messageContainer";
this.Padding = new System.Windows.Forms.Padding(6);
//
// Message Label
//
this.messageLabel.AutoSize = true;
this.messageLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.messageLabel.Font = new System.Drawing.Font("Segoe UI Semibold", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.messageLabel.Location = new System.Drawing.Point(6, 6);
this.messageLabel.MaximumSize = new System.Drawing.Size(250, 0);
this.messageLabel.Size = new System.Drawing.Size(121, 20);
this.messageLabel.Text = chat.Message.Replace("\n", "");
//
// Time Label
//
this.timeLabel.AutoSize = true;
this.timeLabel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.timeLabel.Font = new System.Drawing.Font("Segoe UI Semilight", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.timeLabel.Location = new System.Drawing.Point(6, 26);
this.timeLabel.Margin = new System.Windows.Forms.Padding(6);
this.timeLabel.Size = new System.Drawing.Size(32, 13);
this.timeLabel.Text = Helper.MillisecondsToTime(chat.TimeStamp);
}
private void setAppearance(bool isDoctor)
{
if (isDoctor)
{
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.Dock = DockStyle.Right;
}
else
{
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.Dock = DockStyle.Left;
}
}
}
}
+1 -3
View File
@@ -5,14 +5,12 @@
public string Message { get; } public string Message { get; }
public string Name { get; } public string Name { get; }
public double TimeStamp { get; set;} public double TimeStamp { get; set;}
public bool IsDoctor { get; set; }
public ChatMessage(string name, string message, bool isDoctor) public ChatMessage(string name, string message)
{ {
Name = name; Name = name;
Message = message; Message = message;
TimeStamp = Helper.Now; TimeStamp = Helper.Now;
IsDoctor = isDoctor;
} }
public override string ToString() public override string ToString()
+1 -13
View File
@@ -24,14 +24,8 @@ namespace ErgometerLibrary
comPort.Parity = Parity.None; comPort.Parity = Parity.None;
comPort.StopBits = StopBits.One; comPort.StopBits = StopBits.One;
comPort.BaudRate = 9600; comPort.BaudRate = 9600;
comPort.ReadTimeout = 1500;
try {
comPort.Open(); comPort.Open();
}
catch(Exception e)
{
return false;
}
return comPort.IsOpen; return comPort.IsOpen;
} }
@@ -62,14 +56,8 @@ namespace ErgometerLibrary
{ {
if (IsOpen()) if (IsOpen())
{ {
try {
return comPort.ReadLine(); return comPort.ReadLine();
} }
catch(TimeoutException e)
{
return "err";
}
}
return ""; return "";
} }
+1 -6
View File
@@ -36,8 +36,6 @@
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
@@ -46,14 +44,11 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="AESEncrypt.cs" />
<Compile Include="ChatMessage.cs" /> <Compile Include="ChatMessage.cs" />
<Compile Include="Chat\ChatItem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Helper.cs" /> <Compile Include="Helper.cs" />
<Compile Include="NetCommand.cs" /> <Compile Include="NetCommand.cs" />
<Compile Include="ComPort.cs" /> <Compile Include="ComPort.cs" />
<Compile Include="FileHandler.cs" />
<Compile Include="Meting.cs" /> <Compile Include="Meting.cs" />
<Compile Include="NetHelper.cs" /> <Compile Include="NetHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
+82
View File
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ErgometerLibrary
{
public class FileHandler
{
public static string DataFolder { get; } = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "Ergometer");
public static void CheckDataFolder()
{
if(! Directory.Exists(DataFolder))
{
Directory.CreateDirectory(DataFolder);
}
}
public static int GenerateSession()
{
string[] existingSessions = Directory.GetDirectories(DataFolder);
Random rand = new Random();
int sessionID = rand.Next(int.MinValue, int.MaxValue);
while (existingSessions.Contains(sessionID.ToString()))
{
sessionID = rand.Next(int.MinValue, int.MaxValue);
}
return sessionID;
}
public static void CreateSession(int session, string naam)
{
Directory.CreateDirectory(GetSessionFolder(session));
File.Create(Path.Combine(GetSessionFolder(session), "session.prop"));
File.Create(Path.Combine(GetSessionFolder(session), "metingen.ergo"));
File.Create(Path.Combine(GetSessionFolder(session), "chat.log"));
File.WriteAllText(GetSessionFile(session), naam + "\n" + Helper.Now);
}
public static void WriteMetingen(int session, List<Meting> metingen)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(metingen);
File.WriteAllText(GetSessionMetingen(session), json);
Console.WriteLine("Writing metingen: " + GetSessionMetingen(session));
}
public static void WriteChat(int session, List<ChatMessage> chat)
{
string write = "";
foreach(ChatMessage c in chat)
{
write += c.ToString() + "\n";
}
File.WriteAllText(GetSessionChat(session), write);
Console.WriteLine("Writing chat: " + GetSessionChat(session));
}
private static string GetSessionFolder(int session)
{
return Path.Combine(DataFolder, session.ToString());
}
private static string GetSessionFile(int session)
{
return Path.Combine(DataFolder, session.ToString(), "session.prop");
}
private static string GetSessionMetingen(int session)
{
return Path.Combine(DataFolder, session.ToString(), "metingen.ergo");
}
private static string GetSessionChat(int session)
{
return Path.Combine(DataFolder, session.ToString(), "chat.log");
}
}
}
+2 -21
View File
@@ -6,27 +6,8 @@ using System.Threading.Tasks;
namespace ErgometerLibrary namespace ErgometerLibrary
{ {
public class Helper class Helper
{ {
public static double Now { get { return (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; } } public static double Now { get { return (DateTime.Now - DateTime.Parse("1/1/1870 0:0:0")).TotalMilliseconds; } }
public static string MillisecondsToTime(double millis)
{
DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
string timestr = time.AddMilliseconds(millis) + "";
return timestr;
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
} }
} }
+3 -10
View File
@@ -68,9 +68,10 @@ namespace ErgometerLibrary
public static Meting Parse(string input, char delimiter) public static Meting Parse(string input, char delimiter)
{ {
string[] status = input.Split(delimiter); string[] status = input.Split(delimiter);
Console.WriteLine(status.Length);
if (status.Length != 8 && status.Length != 9) if (status.Length != 8 && status.Length != 9)
{ {
throw new FormatException("Error in Meting: Arguments do not match"); return null;
} }
int heartbeat = int.Parse(status[0]); int heartbeat = int.Parse(status[0]);
int rpm = int.Parse(status[1]); int rpm = int.Parse(status[1]);
@@ -87,15 +88,7 @@ namespace ErgometerLibrary
timestamp = Helper.Now; timestamp = Helper.Now;
string[] temp = status[6].Split(':'); string[] temp = status[6].Split(':');
int seconds = 0; int seconds = (int.Parse(temp[0]) * 60) + (int.Parse(temp[1]));
if (temp.Length == 2)
{
seconds = (int.Parse(temp[0]) * 60) + (int.Parse(temp[1]));
}
else
{
seconds = int.Parse(status[6]);
}
return new Meting(heartbeat, rpm, speed, distance, power, energy, seconds, actualpower,timestamp); return new Meting(heartbeat, rpm, speed, distance, power, energy, seconds, actualpower,timestamp);
} }
+17 -256
View File
@@ -3,34 +3,23 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Win32;
namespace ErgometerLibrary namespace ErgometerLibrary
{ {
public class NetCommand public class NetCommand
{ {
public enum CommandType { LOGIN, DATA, CHAT, LOGOUT, SESSION, VALUESET, USER, RESPONSE, REQUEST, LENGTH, SESSIONDATA, ERROR, BROADCAST } public enum CommandType { LOGIN, DATA, CHAT, LOGOUT, SESSION };
public enum RequestType { USERS, ALLSESSIONS, OLDDATA, SESSIONDATA, CHAT }
public enum ResponseType { LOGINOK, LOGINWRONG, ERROR, NOTLOGGEDIN }
public enum ValueType { TIME, POWER, ENERGY, DISTANCE }
public enum LengthType { USERS, SESSIONS, SESSIONDATA, DATA }
public double Timestamp { get; set; } public double Timestamp { get; set; }
public int Session { get; set; } public int Session { get; set; }
public CommandType Type { get; set; } public CommandType Type { get; set; }
public ResponseType Response { get; set; }
public ValueType Value { get; set; }
public RequestType Request { get; set; }
public LengthType Length { get; set; }
public int SetValue { get; set; }
public string DisplayName { get; set; } public string DisplayName { get; set; }
public bool IsDoctor { get; set; } public bool IsDoctor { get; set; }
public string Password { get; set; } public string Password { get; set; }
public string ChatMessage { get; set; } public string ChatMessage { get; set; }
public Meting Meting { get; set; } public Meting Meting { get; set; }
public int LengthValue { get; set; }
//SESSION
public NetCommand(int session) public NetCommand(int session)
{ {
Type = CommandType.SESSION; Type = CommandType.SESSION;
@@ -38,44 +27,6 @@ namespace ErgometerLibrary
Timestamp = Helper.Now; Timestamp = Helper.Now;
} }
//SESSIONDATA
public NetCommand(string name, double timestamp, int session)
{
Type = CommandType.SESSIONDATA;
Session = session;
Timestamp = timestamp;
DisplayName = name;
}
//RESPONSE
public NetCommand(ResponseType response, int session)
{
Type = CommandType.RESPONSE;
Session = session;
Timestamp = Helper.Now;
Response = response;
}
//Length
public NetCommand(LengthType lengthtype, int length, int session)
{
Type = CommandType.LENGTH;
Length = lengthtype;
Session = session;
Timestamp = Helper.Now;
LengthValue = length;
}
//REQUEST
public NetCommand(RequestType request, int session)
{
Type = CommandType.REQUEST;
Session = session;
Timestamp = Helper.Now;
Request = request;
}
//STANDARD
public NetCommand(CommandType commandtype, int session) public NetCommand(CommandType commandtype, int session)
{ {
Type = commandtype; Type = commandtype;
@@ -83,7 +34,6 @@ namespace ErgometerLibrary
Timestamp = Helper.Now; Timestamp = Helper.Now;
} }
//METING
public NetCommand(Meting m, int session) public NetCommand(Meting m, int session)
{ {
Type = CommandType.DATA; Type = CommandType.DATA;
@@ -93,47 +43,16 @@ namespace ErgometerLibrary
Meting = m; Meting = m;
} }
//CHAT public NetCommand(string chat, int session)
public NetCommand(string chat, bool isDoctor, int session)
{ {
Type = CommandType.CHAT; Type = CommandType.CHAT;
Session = session; Session = session;
IsDoctor = isDoctor;
Timestamp = Helper.Now; Timestamp = Helper.Now;
ChatMessage = chat.Replace("\n", ""); ChatMessage = chat;
} }
//BROADCAST public NetCommand(string name, bool doctor, int session)
public NetCommand(string broadcast, int session)
{
Type = CommandType.BROADCAST;
Session = session;
Timestamp = Helper.Now;
ChatMessage = broadcast.Replace("\n", "");
}
//SETVALUE
public NetCommand(ValueType value, int val, int session)
{
Type = CommandType.VALUESET;
Session = session;
Value = value;
SetValue = val;
}
//USER
public NetCommand(string username, string password, int session)
{
Type = CommandType.USER;
Session = session;
DisplayName = username;
Password = password;
}
//LOGIN
public NetCommand(string name, bool doctor, string password, int session)
{ {
Type = CommandType.LOGIN; Type = CommandType.LOGIN;
Session = session; Session = session;
@@ -141,30 +60,20 @@ namespace ErgometerLibrary
DisplayName = name; DisplayName = name;
IsDoctor = doctor; IsDoctor = doctor;
Password = password;
} }
public static NetCommand Parse(string command) public static NetCommand Parse(string command)
{ {
string[] com = command.Split('»'); string[] com = command.Split('»');
int comType = 0; int comType = int.Parse(com[0]);
try
{
comType = int.Parse(com[0]);
}
catch(Exception e)
{
return new NetCommand(CommandType.ERROR, 0);
}
int session = 0; int session = 0;
if (com[1].StartsWith("ses")) if (com[1].StartsWith("ses"))
session = int.Parse(com[1].Substring(3)); session = int.Parse(com[1].Substring(3));
else else
throw new FormatException("Error in NetCommand: " + com[1] + " is not a valid session."); throw new FormatException("Error in NetCommend: " + com[1] + " is not a valid session.");
string[] args = new string[com.Length - 2]; string[] args = new string[9];
for (int i = 2; i < com.Length; i++) for (int i = 2; i < com.Length; i++)
{ {
args[i - 2] = com[i]; args[i - 2] = com[i];
@@ -182,137 +91,11 @@ namespace ErgometerLibrary
return ParseLogoutRequest(session, args); return ParseLogoutRequest(session, args);
case 5: case 5:
return ParseSession(session); return ParseSession(session);
case 6:
return ParseResponse(session, args);
case 7:
return ParseValue(session, args);
case 8:
return ParseUser(session, args);
case 9:
return ParseRequest(session, args);
case 10:
return ParseLength(session, args);
case 11:
return ParseSessionData(session, args);
case 12:
return ParseBroadcast(session, args);
default: default:
throw new FormatException("Error in NetCommand: " + comType + " is not a valid command type."); throw new FormatException("Error in NetCommand: " + comType + " is not a valid command type.");
} }
} }
private static NetCommand ParseBroadcast(int session, string[] args)
{
if (args.Length != 1)
throw new MissingFieldException("Error in NetCommand: Broadcast Message is missing arguments");
NetCommand temp = new NetCommand(args[0], session);
return temp;
}
private static NetCommand ParseSessionData(int session, string[] args)
{
if (args.Length != 2)
throw new MissingFieldException("Error in NetCommand: Session Data is missing arguments");
NetCommand temp = new NetCommand(args[0], double.Parse(args[1]), session);
return temp;
}
private static NetCommand ParseLength(int session, string[] args)
{
if (args.Length != 2)
throw new MissingFieldException("Error in NetCommand: Length is missing arguments");
switch (args[0])
{
case "users":
return new NetCommand(LengthType.USERS, int.Parse(args[1]), session);
case "sessiondata":
return new NetCommand(LengthType.SESSIONDATA, int.Parse(args[1]), session);
case "sessions":
return new NetCommand(LengthType.SESSIONS, int.Parse(args[1]), session);
case "data":
return new NetCommand(LengthType.DATA, int.Parse(args[1]), session);
default:
throw new FormatException("Error in NetCommand: Length type not recognised");
}
}
private static NetCommand ParseRequest(int session, string[] args)
{
if (args.Length != 1)
throw new MissingFieldException("Error in NetCommand: Request is missing arguments");
switch (args[0])
{
case "users":
return new NetCommand(RequestType.USERS, session);
case "allsessions":
return new NetCommand(RequestType.ALLSESSIONS, session);
case "olddata":
return new NetCommand(RequestType.OLDDATA, session);
case "sessiondata":
return new NetCommand(RequestType.SESSIONDATA, session);
case "chat":
return new NetCommand(RequestType.CHAT, session);
default:
throw new FormatException("Error in NetCommand: Request type not recognised");
}
}
private static NetCommand ParseUser(int session, string[] args)
{
if (args.Length != 2)
throw new MissingFieldException("Error in NetCommand: User is missing arguments");
NetCommand temp = new NetCommand(args[0], Helper.Base64Decode(args[1]), session);
return temp;
}
private static NetCommand ParseValue(int session, string[] args)
{
if (args.Length != 2)
throw new MissingFieldException("Error in NetCommand: SetValue is missing arguments");
switch (args[0])
{
case "time":
return new NetCommand(ValueType.TIME, int.Parse(args[1]), session);
case "power":
return new NetCommand(ValueType.POWER, int.Parse(args[1]), session);
case "energy":
return new NetCommand(ValueType.ENERGY, int.Parse(args[1]), session);
case "distance":
return new NetCommand(ValueType.DISTANCE, int.Parse(args[1]), session);
default:
throw new FormatException("Error in NetCommand: SetValue type not recognised");
}
}
private static NetCommand ParseResponse(int session, string[] args)
{
if (args.Length != 1)
throw new MissingFieldException("Error in NetCommand: Response is missing arguments");
switch (args[0])
{
case "loginok":
return new NetCommand(ResponseType.LOGINOK, session);
case "loginwrong":
return new NetCommand(ResponseType.LOGINWRONG, session);
case "notloggedin":
return new NetCommand(ResponseType.NOTLOGGEDIN, session);
case "error":
return new NetCommand(ResponseType.ERROR, session);
default:
throw new FormatException("Error in NetCommand: Response type not recognised");
}
}
private static NetCommand ParseSession(int session) private static NetCommand ParseSession(int session)
{ {
NetCommand temp = new NetCommand(CommandType.SESSION, session); NetCommand temp = new NetCommand(CommandType.SESSION, session);
@@ -333,12 +116,11 @@ namespace ErgometerLibrary
private static NetCommand ParseChatMessage(int session, string[] args) private static NetCommand ParseChatMessage(int session, string[] args)
{ {
if (args.Length != 2) if (args.Length != 1)
throw new MissingFieldException("Error in NetCommand: Chat Message is missing arguments"); throw new MissingFieldException("Error in NetCommand: Chat Message is missing arguments");
NetCommand temp = new NetCommand(CommandType.CHAT, session); NetCommand temp = new NetCommand(CommandType.CHAT, session);
temp.ChatMessage = args[0]; temp.ChatMessage = args[0];
temp.IsDoctor = bool.Parse(args[1]);
return temp; return temp;
} }
@@ -356,14 +138,17 @@ namespace ErgometerLibrary
private static NetCommand ParseLoginRequest(int session, string[] args) private static NetCommand ParseLoginRequest(int session, string[] args)
{ {
bool doctor = bool.Parse(args[2]); bool doctor = bool.Parse(args[1]);
if (args.Length != 3) if (doctor && args.Length != 3)
throw new MissingFieldException("Error in NetCommand: Doctor login is missing arguments"); throw new MissingFieldException("Error in NetCommand: Doctor login is missing arguments");
else if (args.Length != 2)
throw new MissingFieldException("Error in NetCommand: Client login is missing arguments");
NetCommand temp = new NetCommand(CommandType.LOGIN, session); NetCommand temp = new NetCommand(CommandType.LOGIN, session);
temp.IsDoctor = doctor; temp.IsDoctor = doctor;
temp.DisplayName = args[0]; temp.DisplayName = args[0];
temp.Password = Helper.Base64Decode(args[1]); if (doctor)
temp.Password = args[2];
return temp; return temp;
} }
@@ -375,13 +160,13 @@ namespace ErgometerLibrary
switch (Type) switch (Type)
{ {
case CommandType.LOGIN: case CommandType.LOGIN:
command += "1»ses" + Session + "»" + DisplayName + "»" + Helper.Base64Encode(Password) + "»" + IsDoctor; command += "1»ses" + Session + "»" + DisplayName + "»" + IsDoctor + (IsDoctor ? "»" + Password : "");
break; break;
case CommandType.DATA: case CommandType.DATA:
command += "2»ses" + Session + "»" + Meting.ToCommand(); command += "2»ses" + Session + "»" + Meting.ToCommand();
break; break;
case CommandType.CHAT: case CommandType.CHAT:
command += "3»ses" + Session + "»" + ChatMessage + "»" + IsDoctor; command += "3»ses" + Session + "»" + ChatMessage;
break; break;
case CommandType.LOGOUT: case CommandType.LOGOUT:
command += "4»ses" + Session + "»logout"; command += "4»ses" + Session + "»logout";
@@ -389,30 +174,6 @@ namespace ErgometerLibrary
case CommandType.SESSION: case CommandType.SESSION:
command += "5»ses" + Session; command += "5»ses" + Session;
break; break;
case CommandType.RESPONSE:
command += "6»ses" + Session + "»" + Response.ToString().ToLower();
break;
case CommandType.VALUESET:
command += "7»ses" + Session + "»" + Value.ToString().ToLower() + "»" + SetValue;
break;
case CommandType.USER:
command += "8»ses" + Session + "»" + DisplayName + "»" + Helper.Base64Encode(Password);
break;
case CommandType.REQUEST:
command += "9»ses" + Session + "»" + Request.ToString().ToLower();
break;
case CommandType.LENGTH:
command += "10»ses" + Session + "»" + Length.ToString().ToLower() + "»" + LengthValue;
break;
case CommandType.SESSIONDATA:
command += "11»ses" + Session + "»" + DisplayName + "»" + Timestamp;
break;
case CommandType.BROADCAST:
command += "12»ses" + Session + "»" + ChatMessage;
break;
case CommandType.ERROR:
command += "ERROR IN NETCOMMAND";
break;
default: default:
throw new FormatException("Error in NetCommand: Cannot find type of command"); throw new FormatException("Error in NetCommand: Cannot find type of command");
+4 -103
View File
@@ -1,110 +1,26 @@
using System; using System;
using System.IO;
using System.Net; using System.Net;
using System.Net.Security;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
namespace ErgometerLibrary namespace ErgometerLibrary
{ {
public class NetHelper class NetHelper
{ {
public static bool SendNetCommand(TcpClient client, NetCommand command) public static void SendNetCommand(TcpClient client, NetCommand command)
{ {
/* byte[] b = Encoding.ASCII.GetBytes(command.ToString());
byte[] b = Encoding.Unicode.GetBytes(command.ToString());
client.GetStream().Write(b, 0, b.Length); client.GetStream().Write(b, 0, b.Length);
client.GetStream().Flush(); client.GetStream().Flush();
*/
return SendString(client, command.ToString());
}
public static bool SendString(TcpClient client, string command)
{
/*
byte[] b = Encoding.Unicode.GetBytes(command);
client.GetStream().Write(b, 0, b.Length);
client.GetStream().Flush();
*/
if (client != null && client.Connected)
{
try
{
StreamWriter wr = new StreamWriter(client.GetStream(), Encoding.Unicode);
wr.WriteLine(AESEncrypt.EncryptToString(command));
wr.Flush();
return true;
}
catch (Exception e)
{
return false;
}
}
else
return false;
} }
public static NetCommand ReadNetCommand(TcpClient client) public static NetCommand ReadNetCommand(TcpClient client)
{ {
/*
byte[] bytesFrom = new byte[(int) client.ReceiveBufferSize]; byte[] bytesFrom = new byte[(int) client.ReceiveBufferSize];
client.GetStream().Read(bytesFrom, 0, (int)client.ReceiveBufferSize); client.GetStream().Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
string response = Encoding.Unicode.GetString(bytesFrom); String response = Encoding.ASCII.GetString(bytesFrom);
NetCommand net = NetCommand.Parse(response); NetCommand net = NetCommand.Parse(response);
return net; return net;
*/
string str;
NetCommand net;
str = ReadString(client);
if (str != "")
{
try
{
str = AESEncrypt.DecryptString(str);
}
catch (Exception e)
{
str = "";
net = new NetCommand(NetCommand.CommandType.ERROR, 0);
}
try {
net = NetCommand.Parse(str);
}
catch (Exception e)
{
net = new NetCommand(NetCommand.CommandType.ERROR, 0);
}
}
else
net = new NetCommand(NetCommand.CommandType.ERROR, 0);
return net;
}
public static string ReadString(TcpClient client)
{
/*
byte[] bytesFrom = new byte[(int)client.ReceiveBufferSize];
client.GetStream().Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
string response = Encoding.Unicode.GetString(bytesFrom);
return response;
*/
if (client != null && client.Connected)
{
try {
StreamReader rd = new StreamReader(client.GetStream(), Encoding.Unicode);
string str = rd.ReadLine();
return str;
}
catch(Exception e)
{
return "";
}
}
else
return "";
} }
public static IPAddress GetIP(string ipstring) public static IPAddress GetIP(string ipstring)
@@ -116,20 +32,5 @@ namespace ErgometerLibrary
return ip; return ip;
} }
public static IPAddress GetIP()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return GetIP(localIP);
}
} }
} }
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.3.7")] [assembly: AssemblyFileVersion("1.0.2.0")]