Procházet zdrojové kódy

Mauro's server variant

Mauro de Lyon před 10 roky
rodič
revize
8e823e6762

+ 6 - 0
Proftaak Remote Healthcare/Proftaak Remote Healthcare.sln

@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csp
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FietsClient", "FietsClientV2\FietsClient.csproj", "{96E4194B-1E09-42EA-AF10-09FC7B4444F8}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerV2", "ServerV2\ServerV2.csproj", "{1C8D6858-FC95-4869-8E4A-6FE1BE36EAD6}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -29,6 +31,10 @@ Global
 		{96E4194B-1E09-42EA-AF10-09FC7B4444F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{96E4194B-1E09-42EA-AF10-09FC7B4444F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{96E4194B-1E09-42EA-AF10-09FC7B4444F8}.Release|Any CPU.Build.0 = Release|Any CPU
+		{1C8D6858-FC95-4869-8E4A-6FE1BE36EAD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{1C8D6858-FC95-4869-8E4A-6FE1BE36EAD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{1C8D6858-FC95-4869-8E4A-6FE1BE36EAD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{1C8D6858-FC95-4869-8E4A-6FE1BE36EAD6}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 6 - 0
Proftaak Remote Healthcare/ServerV2/App.config

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <startup> 
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
+    </startup>
+</configuration>

+ 181 - 0
Proftaak Remote Healthcare/ServerV2/AppGlobal.cs

@@ -0,0 +1,181 @@
+using Newtonsoft.Json;
+using ServerV2.FileIO;
+using ServerV2.JSONObjecten;
+using ServerV2.Libraries;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace ServerV2
+{
+    class AppGlobal
+    {
+        private TcpListener listener;
+        private List<Client> clients = new List<Client>();
+        private List<User> users = new List<User>();
+
+        public AppGlobal()
+        {
+            listener = new TcpListener(IPAddress.Any, 1288);
+            listener.Start();
+            while (true)
+            {
+                TestMethode();
+                Console.WriteLine(FileIO.JsonConverter.GetUserSessions(users.ElementAt(1)));
+                Console.WriteLine("waiting for clients...");
+                TcpClient client = listener.AcceptTcpClient();
+                Console.WriteLine("connection received");
+                new Thread(receive).Start(client);
+            }
+        }
+
+        private void TestMethode()
+        {
+            users.Add(new User("JK123", "jancoow", 5, true, 100));
+            users.Add(new User("patient", "patient", 0, false, 0));
+            users.Add(new User("doctor", "doctor", 0, false, 0, true));
+            users.Add(new User("admin", "admin", 80, false, 77, true));
+
+            Random r = new Random();
+            Session session = new Session(1, "100");
+            for (int i = 0; i < 20; i++)
+                session.AddMeasurement(new Measurement(r.Next(100, 200), r.Next(60, 100), r.Next(100, 150), r.Next(0, 100), i, r.Next(100), r.Next(100), r.Next(100), i, r.Next(100)));
+            users.ElementAt(1).tests.Add(session);
+
+            Session session2 = new Session(2, "100");
+            for (int i = 0; i < 50; i++)
+                session2.AddMeasurement(new Measurement(r.Next(100, 200), r.Next(60, 100), r.Next(100, 150), r.Next(0, 100), i, r.Next(100), r.Next(100), r.Next(100), i, r.Next(100)));
+            users.ElementAt(1).tests.Add(session2);
+        }
+
+        private void receive(object obj)
+        {
+            TcpClient client = obj as TcpClient;
+            User currentUser;
+            while (!(client.Client.Poll(0, SelectMode.SelectRead) && client.Client.Available == 0))
+            {
+                string[] response = Encoding.ASCII.GetString(new byte[(int)client.ReceiveBufferSize]).Split('|');
+                switch (response[0])
+                {
+                    case "0":
+                        if (response.Length == 4)
+                        {
+                            int admin, id = 0;
+                            //check username and password
+                            foreach (User u in users)
+                            {
+                                if (u.id == response[1] && u.password == response[2])
+                                {
+                                    admin = u.isDoctor ? 1 : 0;
+                                    id = users.IndexOf(u);
+                                }
+                            }
+
+                            if (id > -1)
+                            {
+                                if (users.First(item => item.id == response[1]).isDoctor)
+                                {
+                                    Console.WriteLine($"received login from docter username: {response[1]} ");
+                                    Communication.SendMessage(client, "0|1|1|");   // Doctor
+                                }
+                                else
+                                {
+                                    Console.WriteLine($"received login from patient username: {response[1]} ");
+                                    Communication.SendMessage(client, "0|1|0|");   //Patient
+                                }
+                                clients.Add(new Client(client, response[1]));
+                            }
+                            else
+                            {
+                                Console.WriteLine("received incorrect username or password");
+                                Communication.SendMessage(client, "0|0|0|"); // Does not exist
+                            }
+                        }
+                        break;
+                    case "1":   //meetsessies ophalen
+                        currentUser = users.First(item => item.id == response[1]);
+                        Communication.SendMessage(client, "1|" + FileIO.JsonConverter.GetUserSessions(currentUser));
+                        break;
+                    case "2":   //Livedata opvragen
+                        currentUser = users.First(item => item.id == response[1]);
+                        FileIO.JsonConverter.GetLastMeasurement(currentUser.tests.Last());
+                        break;
+                    case "3":   //Nieuwe meetsessie aanmaken
+                        if (response.Length == 6)
+                        {
+                            foreach (User u in users)
+                            {
+                                if (u.id == response[1])
+                                    u.AddSession(new Session(int.Parse(response[2]), response[3]));
+                            }
+                        }
+                        break;
+                    case "4":  // Nieuwe patient
+                        users.Add(new User(response[1], response[2], Int32.Parse(response[3]), Boolean.Parse(response[4]), Int32.Parse(response[5])));
+                        break;
+                    case "5":   //data pushen naar meetsessie
+                        currentUser = users.First(item => item.id == response[1]);
+                        currentUser.tests.Last().AddMeasurement(JsonConvert.DeserializeObject<Measurement>(response[2]));
+                        break;
+                    case "6": //chatberichten ontvangen van gebruikers
+                        //controleren of het bericht wel tekens bevat
+                        if (response[3] != null)
+                        {
+                            string message = response[3].TrimEnd('\0');
+                            string receiver = response[2];
+                            string sender = response[1];
+
+                            string case6str = "7|" + sender + "|" + receiver + "|" + message;
+                            Console.WriteLine(case6str);
+                            Communication.SendMessage(client, case6str);
+                            for (int i = 0; i < clients.Count; i++)
+                            {
+                                if (clients[i].username == receiver)
+                                    Communication.SendMessage(clients[i].tcpClient, "7|" + sender + "|" + receiver + "|" + message);
+                            }
+                        }
+                        break;
+                    case "8": //alle online Patients sturen naar Doctorclient
+                        if (response[1] != null)
+                        {
+                            if (response[1] == "doctor" || true) //TODO: doctor check
+                            {
+                                List<string> patients = new List<string>();
+                                foreach (Client c in clients)
+                                {
+                                    User user = users.FirstOrDefault(item => item.id == c.username);
+                                    if (user != null)
+                                        if (!user.isDoctor)
+                                            patients.Add(user.id);
+                                }
+
+                                string strToSend = "8|";
+                                if (!(patients.Count > 0))
+                                    strToSend += "-1";
+                                else
+                                    foreach (string patient in patients)
+                                    {
+                                        strToSend += (patient + '\t');
+                                    }
+                                Communication.SendMessage(client, strToSend.TrimEnd('\t'));
+                            }
+                        }
+                        break;
+                    case "9": //alles doorsturen voor de dokter
+                        //insert code to send list
+                        break;
+                    default:
+                        break;
+                }
+            }
+        }
+
+    }
+}
+
+

+ 24 - 0
Proftaak Remote Healthcare/ServerV2/Client.cs

@@ -0,0 +1,24 @@
+using ServerV2.JSONObjecten;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace ServerV2
+{
+    class Client
+    {
+        public TcpClient tcpClient;
+        public string username;
+
+        public Client(TcpClient tcpClient, string username)
+        {
+            this.tcpClient = tcpClient;
+            this.username = username;
+        }
+
+    }
+}

+ 44 - 0
Proftaak Remote Healthcare/ServerV2/JSONObjecten/Measurement.cs

@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ServerV2.JSONObjecten
+
+{
+    [Serializable]
+    public class Measurement
+    {
+        public int pulse { get; private set; }
+        public int rpm { get; private set; }
+        public int speed { get; private set; }
+        public int wattage { get; private set; }
+        public int distance { get; private set; }
+        public int requestedPower { get; private set; }
+        public int energy { get; private set; }
+        public int actualPower { get; private set; }
+        public int time { get; private set; }
+        public int bpm { get; private set; }
+
+        public Measurement(int pulse, int rpm, int speed, int wattage, int distance, int requestedPower, int energy, int actualPower, int time, int bpm)
+        {
+            this.pulse = pulse;
+            this.rpm = rpm;
+            this.speed = speed;
+            this.wattage = wattage;
+            this.distance = distance;
+            this.requestedPower = requestedPower;
+            this.energy = energy;
+            this.actualPower = actualPower;
+            this.time = time;
+            this.bpm = bpm;
+        }
+
+
+        public override string ToString()
+        {
+            return "pulse: " + pulse + " - RPM: " + rpm + " speed: " + speed + " - distance: " + distance + " - requested power: " + requestedPower + " - energy: " + energy + " - time: " + time + " - actual power: " + actualPower;
+        }
+    }
+}

+ 56 - 0
Proftaak Remote Healthcare/ServerV2/JSONObjecten/Session.cs

@@ -0,0 +1,56 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+
+
+namespace ServerV2.JSONObjecten
+{
+    [Serializable]
+    public class Session
+    {
+        public int id { get; private set; }
+        public List<Measurement> session { get; private set; }
+        public bool isActive { get; private set; }
+        public int bikeMode { get; private set; }
+        public DateTime date { get; private set; }
+        public string note { get; private set; }
+        public string modevalue { get; private set; }
+
+        public Session(int bikeMode, string modevalue)
+        {
+            if (!(Directory.Exists(@"JSON Files"))) 
+            {
+                Directory.CreateDirectory(@"JSON Files");
+            }
+            string[] fileEntries = Directory.GetFiles(@"JSON Files\");
+
+            if (fileEntries.Length > 0)
+                this.id = int.Parse(fileEntries[fileEntries.Length]);
+            else
+                this.id = 1;
+
+            this.session = new List<Measurement>();
+            this.isActive = true;
+            this.bikeMode = bikeMode;
+            this.modevalue = modevalue;
+            this.date = DateTime.Now;
+            this.note = "";
+        }
+
+        public void AddMeasurement(Measurement m)
+        {
+            session.Add(m);
+        }
+
+        public Measurement GetMeasurement()
+        {
+            return session.Last();
+        }
+
+    }
+}

+ 62 - 0
Proftaak Remote Healthcare/ServerV2/JSONObjecten/User.cs

@@ -0,0 +1,62 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+
+namespace ServerV2.JSONObjecten
+{
+    [Serializable]
+    public class User
+    {
+
+        public string id { get; private set; }
+        public string password { get; private set; }
+        public List<Session> tests { get; private set; }
+        public int age { get; private set; }
+        public bool gender { get; private set; }
+        public int weight { get; private set; }
+
+        public bool isDoctor { get; private set; }
+
+        public User()
+        {
+
+        }
+
+        //Create Patient
+        public User(string id, string password, int age, bool gender, int weight)
+        {
+            this.id = id;
+            this.password = password;
+            this.tests = new List<Session>();
+            this.age = age;
+            this.gender = gender;
+            this.weight = weight;
+            this.isDoctor = false;
+        }
+
+        //Create Patient or Doctor
+        public User(string id, string password, int age, bool gender, int weight, bool isDoctor)
+        {
+            this.id = id;
+            this.password = password;
+            this.tests = new List<Session>();
+            this.age = age;
+            this.gender = gender;
+            this.weight = weight;
+            this.isDoctor = isDoctor;
+        }
+
+        public void AddSession(Session session)
+        {
+            tests.Add(session);
+        }
+
+        public List<Session> GetSessions()
+        {
+            return tests;
+        }
+    }
+}

+ 4 - 0
Proftaak Remote Healthcare/ServerV2/JSONObjecten/packages.config

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net452" />
+</packages>

+ 44 - 0
Proftaak Remote Healthcare/ServerV2/Libraries/Communication.cs

@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ServerV2.Libraries
+{
+    class Communication
+    {
+        //simple writeline and readline
+        public static void WriteTextMessage(TcpClient client, string message)
+        {
+            var stream = new StreamWriter(client.GetStream(), Encoding.Unicode);
+            string joined = string.Join("|", message);
+            stream.WriteLine(joined);
+            stream.Flush();
+        }
+
+        public static string ReadTextMessage(TcpClient client)
+        {
+            StreamReader stream = new StreamReader(client.GetStream(), Encoding.Unicode);
+            return stream.ReadLine();
+        }
+
+        //byte streaming
+        public static void SendMessage(TcpClient client, string message)
+        {
+            client.GetStream().Write(Encoding.Unicode.GetBytes(message), 0, Encoding.Unicode.GetBytes(message).Length);
+        }
+
+        //read incoming message
+        public static string ReadMessage(TcpClient client)
+        {
+            byte[] buffer = new byte[256];
+            int totalRead = 0;
+            do { totalRead += client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead); }
+            while (client.GetStream().DataAvailable);
+            return Encoding.Unicode.GetString(buffer, 0, totalRead);
+        }
+    }
+}

+ 40 - 0
Proftaak Remote Healthcare/ServerV2/Libraries/JsonConverter.cs

@@ -0,0 +1,40 @@
+using System;
+using System.IO;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+using ServerV2.JSONObjecten;
+
+namespace ServerV2.FileIO
+{
+    class JsonConverter
+    {
+        public static void SaveUser(User u)
+        {
+            File.WriteAllText(@"JSON Files\" + u.id + ".json", GetUser(u));
+        }
+
+        public static string GetUser(User u)
+        {
+            return JsonConvert.SerializeObject(u);
+        }
+
+        public static string GetUserSessions(User patient)
+        {
+            return JsonConvert.SerializeObject(patient.GetSessions());
+        }
+
+        public static string GetSessions(Session session)
+        {
+            return JsonConvert.SerializeObject(session);
+        }
+
+        public static string GetLastMeasurement(Session currentSession)
+        {
+            return JsonConvert.SerializeObject(currentSession.GetMeasurement());
+        }
+
+    }
+}

+ 17 - 0
Proftaak Remote Healthcare/ServerV2/Program.cs

@@ -0,0 +1,17 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ServerV2
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            Console.WriteLine("Server wordt gestart");
+            new AppGlobal();
+        }
+    }
+}

+ 36 - 0
Proftaak Remote Healthcare/ServerV2/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ServerV2")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("ServerV2")]
+[assembly: AssemblyCopyright("Copyright ©  2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("1c8d6858-fc95-4869-8e4a-6fe1be36ead6")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// 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.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 75 - 0
Proftaak Remote Healthcare/ServerV2/ServerV2.csproj

@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{1C8D6858-FC95-4869-8E4A-6FE1BE36EAD6}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>ServerV2</RootNamespace>
+    <AssemblyName>ServerV2</AssemblyName>
+    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+      <HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="AppGlobal.cs" />
+    <Compile Include="Client.cs" />
+    <Compile Include="JSONObjecten\Measurement.cs" />
+    <Compile Include="JSONObjecten\Session.cs" />
+    <Compile Include="JSONObjecten\User.cs" />
+    <Compile Include="Libraries\Communication.cs" />
+    <Compile Include="Libraries\JsonConverter.cs" />
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+    <None Include="JSONObjecten\packages.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <Folder Include="JSONObjecten\JSON Files\" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>