DeviceHeartRateManager.cs 3.1 KB

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