HeartRateKeeper.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Vinno.IUS.Common.Log;
  6. using Vinno.IUS.Common.Network.Leaf;
  7. using Vinno.IUS.Common.Network.Transfer;
  8. using Vinno.vCloud.Protocol.Messages.Client.Login;
  9. using Vinno.vCloud.Protocol.Messages.Common;
  10. namespace Vinno.vCloud.Common.FIS
  11. {
  12. internal class HeartRateKeeper
  13. {
  14. private readonly string _sessionId;
  15. private readonly ClientLeaf _leaf;
  16. private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
  17. private readonly int _heartRate;
  18. public HeartRateKeeper(string sessionId, ClientLeaf leaf, int heartRateCycle)
  19. {
  20. _sessionId = sessionId;
  21. _leaf = leaf;
  22. _heartRate = heartRateCycle;
  23. }
  24. /// <summary>
  25. /// Start the Heartrate to keep the session available.
  26. /// </summary>
  27. public void Start()
  28. {
  29. DoHeartRate();
  30. }
  31. /// <summary>
  32. /// Stop the Heartrate
  33. /// </summary>
  34. public void Stop()
  35. {
  36. _waitEvent.Set();
  37. }
  38. /// <summary>
  39. /// Do HartRate
  40. /// </summary>
  41. /// <returns></returns>
  42. private void DoHeartRate()
  43. {
  44. Task.Run(() =>
  45. {
  46. while (!_waitEvent.WaitOne(TimeSpan.FromMinutes(_heartRate)))
  47. {
  48. try
  49. {
  50. using (var request = MessagePool.GetMessage<HeartRateRequest>())
  51. {
  52. request.AccountSessionId = _sessionId;
  53. var result = ResultMessage.Convert(_leaf.Send(request));
  54. if (result == null || result.ResultCode != OKResult.Code)
  55. {
  56. throw new InvalidDataException();
  57. }
  58. }
  59. }
  60. catch (Exception ex)
  61. {
  62. Logger.WriteLineError($"HeartRateKeeper Do Heart Rate Error:{ex}");
  63. }
  64. }
  65. });
  66. }
  67. }
  68. }