Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

128 lignes
4.9 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Core.Adapter;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using System.Linq;
  9. namespace MQTTnet.Core.Server
  10. {
  11. public class MqttServer : IMqttServer
  12. {
  13. private readonly ILogger<MqttServer> _logger;
  14. private readonly MqttClientSessionsManager _clientSessionsManager;
  15. private readonly ICollection<IMqttServerAdapter> _adapters;
  16. private readonly MqttServerOptions _options;
  17. private CancellationTokenSource _cancellationTokenSource;
  18. public MqttServer(IOptions<MqttServerOptions> options, IEnumerable<IMqttServerAdapter> adapters, ILogger<MqttServer> logger, MqttClientSessionsManager clientSessionsManager)
  19. {
  20. _options = options.Value ?? throw new ArgumentNullException(nameof(options));
  21. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  22. _clientSessionsManager = clientSessionsManager ?? throw new ArgumentNullException(nameof(clientSessionsManager));
  23. if (adapters == null)
  24. {
  25. throw new ArgumentNullException(nameof(adapters));
  26. }
  27. _adapters = adapters.ToList();
  28. _clientSessionsManager.ApplicationMessageReceived += (s, e) => ApplicationMessageReceived?.Invoke(s, e);
  29. _clientSessionsManager.ClientConnected += OnClientConnected;
  30. _clientSessionsManager.ClientDisconnected += OnClientDisconnected;
  31. }
  32. public IList<ConnectedMqttClient> GetConnectedClients()
  33. {
  34. return _clientSessionsManager.GetConnectedClients();
  35. }
  36. public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
  37. public event EventHandler<MqttClientDisconnectedEventArgs> ClientDisconnected;
  38. public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
  39. public void Publish(IEnumerable<MqttApplicationMessage> applicationMessages)
  40. {
  41. if (applicationMessages == null) throw new ArgumentNullException(nameof(applicationMessages));
  42. if (_cancellationTokenSource == null)
  43. {
  44. throw new InvalidOperationException("The server is not started.");
  45. }
  46. foreach (var applicationMessage in applicationMessages)
  47. {
  48. var interceptorContext = new MqttApplicationMessageInterceptorContext
  49. {
  50. ApplicationMessage = applicationMessage
  51. };
  52. _options.ApplicationMessageInterceptor?.Invoke(interceptorContext);
  53. _clientSessionsManager.DispatchApplicationMessage(null, interceptorContext.ApplicationMessage);
  54. }
  55. }
  56. public Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
  57. {
  58. Publish(applicationMessages);
  59. return Task.FromResult(0);
  60. }
  61. public async Task StartAsync()
  62. {
  63. if (_cancellationTokenSource != null) throw new InvalidOperationException("The MQTT server is already started.");
  64. _cancellationTokenSource = new CancellationTokenSource();
  65. await _clientSessionsManager.RetainedMessagesManager.LoadMessagesAsync();
  66. foreach (var adapter in _adapters)
  67. {
  68. adapter.ClientAccepted += OnClientAccepted;
  69. await adapter.StartAsync(_options);
  70. }
  71. _logger.LogInformation("Started.");
  72. }
  73. public async Task StopAsync()
  74. {
  75. _cancellationTokenSource?.Cancel(false);
  76. _cancellationTokenSource?.Dispose();
  77. _cancellationTokenSource = null;
  78. foreach (var adapter in _adapters)
  79. {
  80. adapter.ClientAccepted -= OnClientAccepted;
  81. await adapter.StopAsync();
  82. }
  83. _clientSessionsManager.Clear();
  84. _logger.LogInformation("Stopped.");
  85. }
  86. private void OnClientAccepted(object sender, MqttServerAdapterClientAcceptedEventArgs eventArgs)
  87. {
  88. eventArgs.SessionTask = Task.Run(async () => await _clientSessionsManager.RunClientSessionAsync(eventArgs.Client, _cancellationTokenSource.Token), _cancellationTokenSource.Token);
  89. }
  90. private void OnClientConnected(object sender, MqttClientConnectedEventArgs eventArgs)
  91. {
  92. _logger.LogInformation("Client '{0}': Connected.", eventArgs.Client.ClientId);
  93. ClientConnected?.Invoke(this, eventArgs);
  94. }
  95. private void OnClientDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs)
  96. {
  97. _logger.LogInformation("Client '{0}': Disconnected.", eventArgs.Client.ClientId);
  98. ClientDisconnected?.Invoke(this, eventArgs);
  99. }
  100. }
  101. }