TcpConnection.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. using FietsLibrary.JSONObjecten;
  2. using FietsLibrary;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Security;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. using System.Security.Cryptography.X509Certificates;
  13. using System.Security.Authentication;
  14. using System.IO;
  15. namespace FietsClient
  16. {
  17. public class TcpConnection
  18. {
  19. public TcpClient client;
  20. public bool isConnectedFlag { private set; get; }
  21. private SslStream sslStream;
  22. public CurrentData currentData { private set; get; }
  23. public string userID { private set; get; }
  24. private Thread receiveThread;
  25. public delegate void ChatmassegeDelegate(string[] data);
  26. public event ChatmassegeDelegate IncomingChatmessageEvent;
  27. public List<User> users = new List<User>();
  28. public TcpConnection()
  29. {
  30. client = new TcpClient();
  31. connect();
  32. }
  33. private void onIncomingChatMessage(string[] data)
  34. {
  35. ChatmassegeDelegate cMD = IncomingChatmessageEvent;
  36. if (cMD != null)
  37. {
  38. cMD(data);
  39. }
  40. }
  41. public bool isConnected()
  42. {
  43. return isConnectedFlag;
  44. }
  45. public void connect()
  46. {
  47. try
  48. {
  49. client.Connect("127.0.0.1", 1288);
  50. // create streams
  51. sslStream = new SslStream(client.GetStream(), false,
  52. new RemoteCertificateValidationCallback(CertificateValidationCallback),
  53. new LocalCertificateSelectionCallback(CertificateSelectionCallback));
  54. bool authenticationPassed = true;
  55. try
  56. {
  57. string serverName = System.Environment.MachineName;
  58. X509Certificate cert = GetServerCert();
  59. X509CertificateCollection certs = new X509CertificateCollection();
  60. certs.Add(cert);
  61. sslStream.AuthenticateAsClient(
  62. serverName,
  63. certs,
  64. SslProtocols.Default,
  65. false); // check cert revokation
  66. }
  67. catch (AuthenticationException)
  68. {
  69. authenticationPassed = false;
  70. }
  71. if (authenticationPassed)
  72. {
  73. receiveThread = new Thread(receive);
  74. receiveThread.Start();
  75. isConnectedFlag = true;
  76. }
  77. }
  78. catch (Exception ex)
  79. {
  80. Console.WriteLine(ex);
  81. Thread.Sleep(1000);
  82. isConnectedFlag = false;
  83. }
  84. }
  85. static X509Certificate CertificateSelectionCallback(object sender,
  86. string targetHost,
  87. X509CertificateCollection localCertificates,
  88. X509Certificate remoteCertificate,
  89. string[] acceptableIssuers)
  90. {
  91. return localCertificates[0];
  92. }
  93. private X509Certificate GetServerCert()
  94. {
  95. X509Certificate cert = new X509Certificate2(
  96. @"testcert.pfx",
  97. "jancoow");
  98. return cert;
  99. }
  100. private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  101. {
  102. return true;
  103. }
  104. public void disconnect()
  105. {
  106. sslStream.Close();
  107. client.Close();
  108. receiveThread.Abort();
  109. isConnectedFlag = false;
  110. }
  111. public void receive()
  112. {
  113. while (client.Connected)
  114. {
  115. byte[] bytesFrom = new byte[(int)client.ReceiveBufferSize];
  116. try
  117. {
  118. sslStream.Read(bytesFrom, 0, client.ReceiveBufferSize);
  119. }
  120. catch (IOException e)
  121. {
  122. Console.WriteLine(e.StackTrace);
  123. break;
  124. }
  125. string response = Encoding.ASCII.GetString(bytesFrom);
  126. string[] response_parts = response.Split('|');
  127. if (response_parts.Length > 0)
  128. {
  129. switch (response_parts[0])
  130. {
  131. case "0": //login and display correct window after login
  132. if (response_parts.Length == 4)
  133. {
  134. if (response_parts[1] == "1" && response_parts[2] == "1")
  135. {
  136. currentData = new CurrentData(userID);
  137. currentData.isDoctor = true;
  138. SendGet(1);
  139. }
  140. else if (response_parts[2] == "0" && response_parts[1] == "1")
  141. {
  142. currentData = new CurrentData(userID);
  143. currentData.isDoctor = false;
  144. SendGet(1);
  145. }
  146. else
  147. new Login("Geen gebruiker gevonden");
  148. }
  149. break;
  150. case "1":
  151. response_parts[1] = response_parts[1].TrimEnd('\0');
  152. currentData.setSessionList(JsonConvert.DeserializeObject<List<Session>>(response_parts[1]));
  153. if (currentData.isDoctor == true)
  154. {
  155. Form activeForm = Form.ActiveForm;
  156. activeForm.Invoke((MethodInvoker)delegate ()
  157. {
  158. DoctorForm doctorForm = new DoctorForm(this);
  159. activeForm.Hide();
  160. doctorForm.Show();
  161. });
  162. }
  163. else
  164. {
  165. Form activeForm = Form.ActiveForm;
  166. if (activeForm != null)
  167. {
  168. activeForm.Invoke((MethodInvoker)delegate ()
  169. {
  170. PatientForm patientForm = new PatientForm(this);
  171. activeForm.Hide();
  172. patientForm.Show();
  173. });
  174. }
  175. }
  176. break;
  177. case "2":
  178. dynamic DynMeasurement = JsonConvert.DeserializeObject<dynamic>(response_parts[2].TrimEnd('\0'));
  179. Measurement outputMeasurement = new Measurement((int)DynMeasurement.pulse, (int)DynMeasurement.rpm, (int)DynMeasurement.speed, (int)DynMeasurement.distance, (int)DynMeasurement.requestedPower, (int)DynMeasurement.energy, (int)DynMeasurement.actualPower, (int)DynMeasurement.time);
  180. currentData.GetSessions().Last().AddMeasurement(outputMeasurement);
  181. Forms.DoctorSessionUC sessionUC = null;
  182. bool b = DoctorModel.doctorModel.doctorSessions.TryGetValue(response_parts[1], out sessionUC);
  183. if (b)
  184. {
  185. sessionUC.HandleSessionBikeData(outputMeasurement);
  186. }
  187. break;
  188. case "7":
  189. // sender receiver message
  190. onIncomingChatMessage(new string[] { response_parts[1], response_parts[2], response_parts[3].TrimEnd('\0') });
  191. break;
  192. case "8":
  193. if (response_parts[1].TrimEnd('\0') != "-1")
  194. {
  195. DoctorModel.doctorModel.onlinePatients = response_parts[1].TrimEnd('\0').Split('\t').ToList();
  196. }
  197. else if (response_parts[1].TrimEnd('\0') == "-1")
  198. {
  199. DoctorModel.doctorModel.onlinePatients = new List<String>();
  200. }
  201. break;
  202. case "9":
  203. dynamic results = JsonConvert.DeserializeObject<dynamic>(response_parts[1]);
  204. foreach (dynamic r in results)
  205. {
  206. User user = r as User;
  207. users.Add(new User(r.id.ToString(), r.password.ToString(), Int32.Parse(r.age.ToString()),
  208. Boolean.Parse(r.gender.ToString()), Int32.Parse(r.weight.ToString()),
  209. Boolean.Parse(r.isDoctor.ToString())));
  210. int i = 1;
  211. foreach (dynamic ses in r.sessions)
  212. {
  213. Session tempSession = new Session(i);
  214. i++;
  215. foreach (dynamic m in ses.measurements)
  216. {
  217. Measurement measurement = new Measurement((int)m.pulse, (int)m.rpm, (int)m.speed, (int)m.distance, (int)m.requestedPower, (int)m.energy, (int)m.actualPower, (int)m.time); ;
  218. tempSession.AddMeasurement(measurement);
  219. }
  220. users.Last().AddSession(tempSession);
  221. }
  222. Console.WriteLine(users);
  223. }
  224. break;
  225. case "10":
  226. if (!currentData.isDoctor)
  227. {
  228. PatientModel.patientModel.CurrentDoctorID = response_parts[3].TrimEnd('\0');
  229. if (response_parts[1] == "1")
  230. {
  231. PatientModel.patientModel.startSession();
  232. }
  233. else if (response_parts[1] == "0")
  234. {
  235. StopSessoin();
  236. }
  237. }
  238. else
  239. {
  240. if (response_parts[1] == "1")
  241. {
  242. StartNewSession(true, response_parts[2]);
  243. }
  244. }
  245. break;
  246. case "20":
  247. PatientModel.patientModel.setDistanceMode(response_parts[1].TrimEnd('\0'), false);
  248. break;
  249. case "21":
  250. PatientModel.patientModel.setTimeMode(response_parts[1].TrimEnd('\0') + response_parts[2].TrimEnd('\0'), false);
  251. break;
  252. case "22":
  253. //PatientModel.patientModel.setPower(response_parts[1].TrimEnd('\0'));
  254. PatientModel.patientModel.powerLog = response_parts[1].TrimEnd('\0');
  255. break;
  256. }
  257. }
  258. }
  259. }
  260. public void StartNewSession(bool isDoctor, string PatientID)
  261. {
  262. Session session = new Session(currentData.sessions.Count + 1);
  263. currentData.sessions.Add(session);
  264. if (!isDoctor)
  265. {
  266. SendNewSession();
  267. PatientModel.patientModel.startAskingData();
  268. }
  269. else if(isDoctor)
  270. {
  271. Forms.DoctorSessionUC sessionUC = null;
  272. bool b = DoctorModel.doctorModel.doctorSessions.TryGetValue(PatientID, out sessionUC);
  273. if (b)
  274. {
  275. sessionUC.ClearOldSession();
  276. }
  277. }
  278. }
  279. public void StopSessoin()
  280. {
  281. PatientModel.patientModel.stopAskingData();
  282. SendStopSessionPatient();
  283. }
  284. public void SendLogin(string username, string password)
  285. {
  286. // send command ( cmdID | username | password )
  287. this.userID = username;
  288. SendString("0|" + username + "|" + password + "|");
  289. }
  290. public void SendGet(int GetWhat)
  291. {
  292. // send command ( cmdID | username )
  293. SendString(GetWhat + "|" + userID + "|");
  294. }
  295. public void SendNewSession()
  296. {
  297. // send command ( cmdID | username )
  298. SendString("3|" + userID + "|" + FietsLibrary.JsonConverter.SerializeSession(currentData.GetSessions().Last()) + "|");
  299. }
  300. public void SendNewPatient(User user)
  301. {
  302. // send command ( cmdID | username )
  303. SendString("4|" + user.id + "|" + user.password + "|" + user.age + "|" + user.gender + "|" + user.weight + "|");
  304. }
  305. public void SendNewMeasurement()
  306. {
  307. // send command ( usernamePatient | usernameCurrentDoctor | data )
  308. string currentDoctor = PatientModel.patientModel.CurrentDoctorID;
  309. SendString("5|" + userID + "|" + currentDoctor + "|" + FietsLibrary.JsonConverter.SerializeLastMeasurement(currentData.GetSessions().Last().GetLastMeasurement()) + "|");
  310. }
  311. public void SendChatMessage(string[] data)
  312. {
  313. String receiverID = data[1];
  314. if (currentData != null)
  315. {
  316. String message = data[0];
  317. // send command ( cmdID | username sender | username receiverID | message )
  318. string protocol = "6|" + this.userID + "|" + receiverID + "|" + message;
  319. SendString(protocol);
  320. }
  321. }
  322. public void SendGetActivePatients()
  323. {
  324. SendString("8|" + userID + "|");
  325. }
  326. public void SendStopSessionPatient()
  327. {
  328. SendString("11|" + userID + "|");
  329. }
  330. public void requestUsers()
  331. {
  332. SendString("9|");
  333. }
  334. public void SendStartStopSession(bool startstop, string PatientUsername)
  335. {
  336. if (startstop)
  337. SendString("10|1|" + PatientUsername + "|" + currentData.GetUserID() + "|");
  338. else
  339. SendString("10|0|" + PatientUsername + "|" + currentData.GetUserID() + "|");
  340. }
  341. public void SendDistance(int distance, string user)
  342. {
  343. SendString("20|" + user + "|" + distance + "|");
  344. }
  345. public void SendTime(int Minutes, int seconds, string user)
  346. {
  347. SendString("21|" + user + "|" + Minutes + ":" + seconds + "|");
  348. }
  349. public void SendPower(int power, string user)
  350. {
  351. SendString("22|" + user + "|" + power + "|");
  352. }
  353. public void SendString(string s)
  354. {
  355. try
  356. {
  357. byte[] b = Encoding.ASCII.GetBytes(s);
  358. sslStream.Write(b, 0, b.Length);
  359. sslStream.Flush();
  360. }
  361. catch (Exception e)
  362. {
  363. Console.WriteLine(e);
  364. }
  365. }
  366. }
  367. }