HeartRateKeeperV2.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Vinno.IUS.Common.Log;
  5. using Vinno.vCloud.Common.FIS.Helper;
  6. using WingInterfaceLibrary.Interface;
  7. using WingInterfaceLibrary.Request;
  8. namespace Vinno.vCloud.Common.FIS
  9. {
  10. internal class HeartRateKeeperV2
  11. {
  12. private readonly IDeviceService _deviceService;
  13. private readonly string _token;
  14. private readonly int _heartRate;
  15. private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
  16. public HeartRateKeeperV2(IDeviceService deviceService, string token, int heartRate = 300)
  17. {
  18. _deviceService = deviceService;
  19. if (heartRate <= 0)
  20. {
  21. heartRate = 300;
  22. }
  23. _heartRate = heartRate;
  24. _token = token;
  25. }
  26. /// <summary>
  27. /// Start the Heartrate to keep the session available.
  28. /// </summary>
  29. public void Start()
  30. {
  31. DoHeartRate();
  32. }
  33. /// <summary>
  34. /// Stop the Heartrate
  35. /// </summary>
  36. public void Stop()
  37. {
  38. _waitEvent.Set();
  39. }
  40. /// <summary>
  41. /// Do HartRate
  42. /// </summary>
  43. /// <returns></returns>
  44. private void DoHeartRate()
  45. {
  46. Task.Run(() =>
  47. {
  48. while (!_waitEvent.WaitOne(TimeSpan.FromSeconds(_heartRate)))
  49. {
  50. try
  51. {
  52. bool result = false;
  53. var tokenRequest = new TokenRequest()
  54. {
  55. Token = _token,
  56. };
  57. result = JsonRpcHelper.HeartRate(_deviceService, tokenRequest);
  58. if (!result)
  59. {
  60. Logger.WriteLineError($"HeartRateKeeperV2 HeartRate Fail,Result is false");
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. Logger.WriteLineError($"HeartRateKeeperV2 Do HeartRate Error:{ex}");
  66. }
  67. }
  68. });
  69. }
  70. }
  71. }