Compare commits

43 Commits

Author SHA1 Message Date
kennyboy55 96deb8b9bb Possible encrypt fix 2015-10-21 09:33:13 +02:00
kennyboy55 ac0057a079 Added encryption 2015-10-21 09:12:08 +02:00
kennyboy55 4e0812bb16 Better network error handling 2015-10-20 23:28:55 +02:00
kennyboy55 52911bf1cd Version Bump (final) 2015-10-20 22:49:08 +02:00
kennyboy55 a737994c70 Error handling on Comport Open 2015-10-20 22:48:59 +02:00
kennyboy55 3cc8b70009 Moved local ip to library 2015-10-20 22:48:40 +02:00
kennyboy55 b75083be83 Added broadcast 2015-10-20 19:40:45 +02:00
kennyboy55 232639e3e2 Bugfix for ergometer crash 2015-10-20 17:06:50 +02:00
kennyboy55 1c83e6b086 Changed error 2015-10-20 16:03:23 +02:00
Aareschluchtje 0e77de2318 Merge remote-tracking branch 'origin/develop' into develop 2015-10-20 13:46:10 +02:00
Aareschluchtje 6a1e058639 Changed sessiondata 2015-10-20 13:45:50 +02:00
kennyboy55 59aac89454 Added docter tag to chat message 2015-10-20 12:58:05 +02:00
Aareschluchtje f397b8a2db Changed Sessiondata 2015-10-20 12:08:26 +02:00
kennyboy55 a7f8039fba Added more error handling 2015-10-20 11:18:03 +02:00
kennyboy55 217035b528 Removed unused code. Added timeout to comport read. 2015-10-20 00:28:36 +02:00
kennyboy55 2319c86320 Moved Filehandler, better error handling 2015-10-19 22:26:32 +02:00
kennyboy55 d75419d92e Move ChatItem to library 2015-10-19 18:53:10 +02:00
kennyboy55 0ae99173d6 Fixed chat 2015-10-19 17:30:33 +02:00
kennyboy55 8748315a40 Removed profanity 2015-10-17 16:56:35 +02:00
Aareschluchtje b337bb84b0 gefaalde poging om de chat te fixen take 1 2015-10-17 10:42:24 +02:00
kennyboy55 41a1ce5814 Bugfixed new bugs added bugfix 2015-10-16 10:48:15 +02:00
kennyboy55 b420e22780 Bugfix 2015-10-16 10:47:21 +02:00
kennyboy55 2761e5e93e Removed SSL 2015-10-16 09:39:11 +02:00
kennyboy55 5bd0816ed9 Added SSL connection 2015-10-14 09:18:57 +02:00
kennyboy55 7b806ac847 Encode/decode password.
Added Length options to protocol.
2015-10-13 22:03:08 +02:00
Aareschluchtje a348917810 Added method to get all the sessions. 2015-10-11 15:24:00 +02:00
kennyboy55 6a6a5102cc Added Request Parse options 2015-10-10 22:43:48 +02:00
Aareschluchtje f1fcee9d0f Added method for reading metingen 2015-10-10 22:38:14 +02:00
kennyboy55 2334a52633 Changed doctor username. Added milliseconds to date 2015-10-09 20:48:53 +02:00
kennyboy55 5c5048f362 Added Request 2015-10-09 12:10:53 +02:00
Aareschluchtje 38f0d21f9d Added Request 2015-10-09 11:54:02 +02:00
Aareschluchtje 3653edd707 Changed username for security reasons 2015-10-09 11:36:59 +02:00
kennyboy55 3963aa8bb0 Bugfixes 2015-10-09 11:17:48 +02:00
kennyboy55 043fb6b6ef Added new protocol stuff 2015-10-09 10:06:36 +02:00
kennyboy55 43bf6a1e1b Added login and user management 2015-10-08 22:41:21 +02:00
kennyboy55 69ed0a7095 Added users, bugfixes 2015-10-08 18:29:52 +02:00
Aareschluchtje 74b3d6b77d Cleaned up Console output for Server. 2015-10-05 10:21:18 +02:00
Aareschluchtje 589cfce648 Fixed IOexception 2015-10-04 14:47:32 +02:00
kennyboy55 9c8c87efaa Bugfixes 2015-10-02 13:40:02 +02:00
kennyboy55 5049bd3a38 Changed login procedure 2015-10-02 12:47:22 +02:00
kennyboy55 063264b1e3 Added extra methods for string sending and receiving 2015-10-02 11:54:49 +02:00
kennyboy55 167d186076 Bugfixes (public) 2015-10-02 11:45:17 +02:00
Aareschluchtje a6152e4e58 More bugfixes 2015-10-02 11:30:27 +02:00
11 changed files with 641 additions and 115 deletions
+162
View File
@@ -0,0 +1,162 @@
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
@@ -0,0 +1,63 @@
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;
}
}
}
}
+3 -1
View File
@@ -5,12 +5,14 @@
public string Message { get; }
public string Name { get; }
public double TimeStamp { get; set;}
public bool IsDoctor { get; set; }
public ChatMessage(string name, string message)
public ChatMessage(string name, string message, bool isDoctor)
{
Name = name;
Message = message;
TimeStamp = Helper.Now;
IsDoctor = isDoctor;
}
public override string ToString()
+15 -3
View File
@@ -24,8 +24,14 @@ namespace ErgometerLibrary
comPort.Parity = Parity.None;
comPort.StopBits = StopBits.One;
comPort.BaudRate = 9600;
comPort.Open();
comPort.ReadTimeout = 1500;
try {
comPort.Open();
}
catch(Exception e)
{
return false;
}
return comPort.IsOpen;
}
@@ -56,7 +62,13 @@ namespace ErgometerLibrary
{
if (IsOpen())
{
return comPort.ReadLine();
try {
return comPort.ReadLine();
}
catch(TimeoutException e)
{
return "err";
}
}
return "";
+6 -1
View File
@@ -36,6 +36,8 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
@@ -44,11 +46,14 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AESEncrypt.cs" />
<Compile Include="ChatMessage.cs" />
<Compile Include="Chat\ChatItem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Helper.cs" />
<Compile Include="NetCommand.cs" />
<Compile Include="ComPort.cs" />
<Compile Include="FileHandler.cs" />
<Compile Include="Meting.cs" />
<Compile Include="NetHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
-82
View File
@@ -1,82 +0,0 @@
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");
}
}
}
+21 -2
View File
@@ -6,8 +6,27 @@ using System.Threading.Tasks;
namespace ErgometerLibrary
{
class Helper
public class Helper
{
public static double Now { get { return (DateTime.Now - DateTime.Parse("1/1/1870 0:0:0")).TotalMilliseconds; } }
public static double Now { get { return (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).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);
}
}
}
+10 -3
View File
@@ -68,10 +68,9 @@ namespace ErgometerLibrary
public static Meting Parse(string input, char delimiter)
{
string[] status = input.Split(delimiter);
Console.WriteLine(status.Length);
if (status.Length != 8 && status.Length != 9)
{
return null;
throw new FormatException("Error in Meting: Arguments do not match");
}
int heartbeat = int.Parse(status[0]);
int rpm = int.Parse(status[1]);
@@ -88,7 +87,15 @@ namespace ErgometerLibrary
timestamp = Helper.Now;
string[] temp = status[6].Split(':');
int seconds = (int.Parse(temp[0]) * 60) + (int.Parse(temp[1]));
int seconds = 0;
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);
}
+256 -17
View File
@@ -3,23 +3,34 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace ErgometerLibrary
{
public class NetCommand
{
public enum CommandType { LOGIN, DATA, CHAT, LOGOUT, SESSION };
public enum CommandType { LOGIN, DATA, CHAT, LOGOUT, SESSION, VALUESET, USER, RESPONSE, REQUEST, LENGTH, SESSIONDATA, ERROR, BROADCAST }
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 int Session { 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 bool IsDoctor { get; set; }
public string Password { get; set; }
public string ChatMessage { get; set; }
public Meting Meting { get; set; }
public int LengthValue { get; set; }
//SESSION
public NetCommand(int session)
{
Type = CommandType.SESSION;
@@ -27,6 +38,44 @@ namespace ErgometerLibrary
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)
{
Type = commandtype;
@@ -34,6 +83,7 @@ namespace ErgometerLibrary
Timestamp = Helper.Now;
}
//METING
public NetCommand(Meting m, int session)
{
Type = CommandType.DATA;
@@ -43,16 +93,47 @@ namespace ErgometerLibrary
Meting = m;
}
public NetCommand(string chat, int session)
//CHAT
public NetCommand(string chat, bool isDoctor, int session)
{
Type = CommandType.CHAT;
Session = session;
IsDoctor = isDoctor;
Timestamp = Helper.Now;
ChatMessage = chat;
ChatMessage = chat.Replace("\n", "");
}
public NetCommand(string name, bool doctor, int session)
//BROADCAST
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;
Session = session;
@@ -60,20 +141,30 @@ namespace ErgometerLibrary
DisplayName = name;
IsDoctor = doctor;
Password = password;
}
public static NetCommand Parse(string command)
{
string[] com = command.Split('»');
int comType = int.Parse(com[0]);
int comType = 0;
try
{
comType = int.Parse(com[0]);
}
catch(Exception e)
{
return new NetCommand(CommandType.ERROR, 0);
}
int session = 0;
if (com[1].StartsWith("ses"))
session = int.Parse(com[1].Substring(3));
else
throw new FormatException("Error in NetCommend: " + com[1] + " is not a valid session.");
throw new FormatException("Error in NetCommand: " + com[1] + " is not a valid session.");
string[] args = new string[9];
string[] args = new string[com.Length - 2];
for (int i = 2; i < com.Length; i++)
{
args[i - 2] = com[i];
@@ -91,11 +182,137 @@ namespace ErgometerLibrary
return ParseLogoutRequest(session, args);
case 5:
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:
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)
{
NetCommand temp = new NetCommand(CommandType.SESSION, session);
@@ -116,11 +333,12 @@ namespace ErgometerLibrary
private static NetCommand ParseChatMessage(int session, string[] args)
{
if (args.Length != 1)
if (args.Length != 2)
throw new MissingFieldException("Error in NetCommand: Chat Message is missing arguments");
NetCommand temp = new NetCommand(CommandType.CHAT, session);
temp.ChatMessage = args[0];
temp.IsDoctor = bool.Parse(args[1]);
return temp;
}
@@ -138,17 +356,14 @@ namespace ErgometerLibrary
private static NetCommand ParseLoginRequest(int session, string[] args)
{
bool doctor = bool.Parse(args[1]);
if (doctor && args.Length != 3)
bool doctor = bool.Parse(args[2]);
if (args.Length != 3)
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);
temp.IsDoctor = doctor;
temp.DisplayName = args[0];
if (doctor)
temp.Password = args[2];
temp.Password = Helper.Base64Decode(args[1]);
return temp;
}
@@ -160,13 +375,13 @@ namespace ErgometerLibrary
switch (Type)
{
case CommandType.LOGIN:
command += "1»ses" + Session + "»" + DisplayName + "»" + IsDoctor + (IsDoctor ? "»" + Password : "");
command += "1»ses" + Session + "»" + DisplayName + "»" + Helper.Base64Encode(Password) + "»" + IsDoctor;
break;
case CommandType.DATA:
command += "2»ses" + Session + "»" + Meting.ToCommand();
break;
case CommandType.CHAT:
command += "3»ses" + Session + "»" + ChatMessage;
command += "3»ses" + Session + "»" + ChatMessage + "»" + IsDoctor;
break;
case CommandType.LOGOUT:
command += "4»ses" + Session + "»logout";
@@ -174,6 +389,30 @@ namespace ErgometerLibrary
case CommandType.SESSION:
command += "5»ses" + Session;
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:
throw new FormatException("Error in NetCommand: Cannot find type of command");
+103 -4
View File
@@ -1,26 +1,110 @@
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
namespace ErgometerLibrary
{
class NetHelper
public class NetHelper
{
public static void SendNetCommand(TcpClient client, NetCommand command)
public static bool 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().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)
{
/*
byte[] bytesFrom = new byte[(int) client.ReceiveBufferSize];
client.GetStream().Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
String response = Encoding.ASCII.GetString(bytesFrom);
string response = Encoding.Unicode.GetString(bytesFrom);
NetCommand net = NetCommand.Parse(response);
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)
@@ -32,5 +116,20 @@ namespace ErgometerLibrary
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
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.0.3.7")]