DeviceHeartRateManager.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using Newtonsoft.Json;
  3. using System.Globalization;
  4. using WingInterfaceLibrary.Enum;
  5. using System.Collections.Concurrent;
  6. using System.Threading.Tasks;
  7. using WingServerCommon.Log;
  8. using System.Threading;
  9. using WingServerCommon.Utilities.Executors;
  10. namespace WingDeviceService.Common
  11. {
  12. internal class DeviceHeartRateManager
  13. {
  14. private ConcurrentDictionary<string, DeviceHeartRateDTO> _devices = new ConcurrentDictionary<string, DeviceHeartRateDTO>();
  15. private Func<string, bool, bool> OnSetOnlineState;
  16. Func<bool> OnCheckDeviceRoomStatus;
  17. public DeviceHeartRateManager(Func<string, bool, bool> setOnlineState, Func<bool> checkDeviceRoomStatus)
  18. {
  19. OnSetOnlineState = setOnlineState;
  20. OnCheckDeviceRoomStatus = checkDeviceRoomStatus;
  21. StartCheckClients();
  22. }
  23. /// <summary>
  24. /// 加入检测集合
  25. /// </summary>
  26. /// <param name="token"></param>
  27. public void AddOrUpdate(string token)
  28. {
  29. _devices.AddOrUpdate(token, new DeviceHeartRateDTO(token), (k, v) =>
  30. {
  31. v.Activate();
  32. return v;
  33. });
  34. }
  35. /// <summary>
  36. /// 设备心跳有效期验证
  37. /// </summary>
  38. private void StartCheckClients()
  39. {
  40. Logger.WriteLineInfo($"DeviceHeartRateManager start check clients");
  41. Task.Run(async () =>
  42. {
  43. while (true)
  44. {
  45. await Task.Delay(1 * 60 * 1000);
  46. foreach (var token in _devices.Keys)
  47. {
  48. var heartRate = _devices[token];
  49. heartRate.DeActivate();
  50. try
  51. {
  52. if (heartRate.LeftTime < 0)
  53. {
  54. OnSetOnlineState?.Invoke(token, false);
  55. }
  56. }
  57. catch (Exception ex)
  58. {
  59. Logger.WriteLineWarn($"check device token {token} err, {ex}");
  60. }
  61. finally
  62. {
  63. if (heartRate.LeftTime < 0)
  64. {
  65. _devices.TryRemove(token, out _);
  66. }
  67. }
  68. }
  69. OnCheckDeviceRoomStatus?.Invoke();
  70. }
  71. });
  72. Logger.WriteLineInfo($"DeviceHeartRateManager finished");
  73. }
  74. }
  75. internal class DeviceHeartRateDTO
  76. {
  77. public DeviceHeartRateDTO(string token)
  78. {
  79. Token = token;
  80. }
  81. private volatile int _livingTime = 0;
  82. private readonly int _clientLifecycle = 10; //10 minutes
  83. public string Token { get; set; }
  84. public int LeftTime => _clientLifecycle - _livingTime;
  85. /// <summary>
  86. /// Reset the living time.
  87. /// </summary>
  88. public virtual void Activate()
  89. {
  90. _livingTime = 0;
  91. }
  92. /// <summary>
  93. /// Deactive the session.
  94. /// </summary>
  95. public virtual void DeActivate()
  96. {
  97. _livingTime++;
  98. }
  99. }
  100. }