MqttClientService .cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using MQTTnet;
  2. using MQTTnet.Client;
  3. using Microsoft.Extensions.Options;
  4. using Microsoft.Extensions.Logging;
  5. using System.Text;
  6. using MQTTnet.Server;
  7. namespace Fuel.Application.MqttService
  8. {
  9. public class MqttClientService : IMqttClientService, IDisposable
  10. {
  11. private readonly IMqttClient _mqttClient;
  12. private readonly MqttOptions _options;
  13. private readonly ILogger<MqttClientService> _logger;
  14. public MqttClientService(
  15. IOptions<MqttOptions> options,
  16. ILogger<MqttClientService> logger)
  17. {
  18. _options = options.Value;
  19. _logger = logger;
  20. var factory = new MqttFactory();
  21. _mqttClient = factory.CreateMqttClient();
  22. // 配置事件处理
  23. _mqttClient.ConnectedAsync += HandleConnectedAsync;
  24. _mqttClient.DisconnectedAsync += HandleDisconnectedAsync;
  25. _mqttClient.ApplicationMessageReceivedAsync += HandleMessageReceivedAsync;
  26. }
  27. private async Task HandleConnectedAsync(MqttClientConnectedEventArgs e)
  28. {
  29. _logger.LogInformation("MQTT connected");
  30. await Task.CompletedTask;
  31. }
  32. private async Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs e)
  33. {
  34. _logger.LogWarning("MQTT disconnected. Attempting to reconnect...");
  35. await Task.Delay(TimeSpan.FromSeconds(5));
  36. await ConnectAsync(); // 自动重连
  37. }
  38. private async Task HandleMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
  39. {
  40. var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
  41. _logger.LogInformation($"Received message: {payload} [Topic: {e.ApplicationMessage.Topic}]");
  42. await Task.CompletedTask;
  43. }
  44. public async Task ConnectAsync()
  45. {
  46. var options = new MqttClientOptionsBuilder()
  47. .WithTcpServer(_options.Server, _options.Port)
  48. .WithClientId(_options.ClientId)
  49. .WithCredentials(_options.Username, _options.Password)
  50. .WithCleanSession()
  51. .Build();
  52. await _mqttClient.ConnectAsync(options);
  53. }
  54. public async Task PublishAsync(string topic, string payload)
  55. {
  56. if (!_mqttClient.IsConnected)
  57. {
  58. await ConnectAsync();
  59. }
  60. var message = new MqttApplicationMessageBuilder()
  61. .WithTopic(topic)
  62. .WithPayload(payload)
  63. .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
  64. .Build();
  65. await _mqttClient.PublishAsync(message);
  66. }
  67. public async Task SubscribeAsync(string topic)
  68. {
  69. if (!_mqttClient.IsConnected)
  70. {
  71. await ConnectAsync();
  72. }
  73. var topicFilter = new MqttTopicFilterBuilder()
  74. .WithTopic(topic)
  75. .Build();
  76. await _mqttClient.SubscribeAsync(topicFilter);
  77. }
  78. public async Task DisconnectAsync()
  79. {
  80. await _mqttClient.DisconnectAsync();
  81. }
  82. public void Dispose()
  83. {
  84. _mqttClient?.Dispose();
  85. }
  86. }
  87. }