平安校园
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

67 satır
2.9 KiB

  1. using Masuit.Tools;
  2. using NewLife.MQTT;
  3. using SafeCampus.Core;
  4. using SafeCampus.Cache;
  5. namespace SafeCampus.Background;
  6. /// <summary>
  7. /// mqtt后台任务
  8. /// </summary>
  9. public class MqttWorker : BackgroundService
  10. {
  11. private readonly ILogger<MqttWorker> _logger;
  12. private readonly ISimpleCacheService _simpleCacheService;
  13. private readonly MqttClient _mqtt;
  14. public MqttWorker(ILogger<MqttWorker> logger, ISimpleCacheService simpleCacheService, IMqttClientManager mqttClientManager)
  15. {
  16. _logger = logger;
  17. this._simpleCacheService = simpleCacheService;
  18. this._mqtt = mqttClientManager.GetClient();
  19. }
  20. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  21. {
  22. //订阅设备上下线主题
  23. await _mqtt.SubscribeAsync("$SYS/brokers/+/clients/+/+", (e) =>
  24. {
  25. var topicList = e.Topic.Split("/");//根据/分割
  26. var clientId = topicList[topicList.Length - 2];//获取客户端ID
  27. if (clientId.Contains("_"))//判断客户端ID是否有下划线有下划线表示是web用户登录
  28. {
  29. var userId = clientId.Split("_")[0];
  30. //获取redis当前用户的token信息列表
  31. var tokenInfos = _simpleCacheService.HashGetOne<List<TokenInfo>>(CacheConst.Cache_UserToken, userId);
  32. if (tokenInfos != null)
  33. {
  34. var connectEvent = topicList.Last();//获取连接事件判断上线还是下线
  35. if (connectEvent == "connected")//如果是上线
  36. {
  37. _logger.LogInformation($"设备{clientId}上线了");
  38. var token = _simpleCacheService.Get<string>(CacheConst.Cache_MqttClientUser + clientId);//获取mqtt客户端ID对应的用户token
  39. if (token == null) return;//没有token就直接退出
  40. //获取redis中当前token
  41. var tokenInfo = tokenInfos.Where(it => it.Token == token).FirstOrDefault();
  42. if (tokenInfo != null)
  43. {
  44. tokenInfo.ClientIds.Add(clientId);//添加到客户端列表
  45. _simpleCacheService.HashAdd(CacheConst.Cache_UserToken, userId, tokenInfos);//更新Redis
  46. }
  47. }
  48. else //下线
  49. {
  50. _logger.LogInformation($"设备{clientId}下线了");
  51. //获取当前客户端ID所在的token信息
  52. var tokenInfo = tokenInfos.Where(it => it.ClientIds.Contains(clientId)).FirstOrDefault();
  53. if (tokenInfo != null)
  54. {
  55. tokenInfo.ClientIds.RemoveWhere(it => it == clientId);//从客户端列表删除
  56. _simpleCacheService.HashAdd(CacheConst.Cache_UserToken, userId, tokenInfos);//更新Redis
  57. }
  58. }
  59. }
  60. }
  61. });
  62. }
  63. }