修改mqtt订阅位程序启动,定时器只定时消费
This commit is contained in:
1 parent
09098c020a
commit
96d8309793
3 files changed
+120
-141
No files matched your search
@@ -0,0 +1,116 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HHWMS.Web.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Extensions.ManagedClient;
|
||||
using WalkingTec.Mvvm.Core;
|
||||
|
||||
namespace HHWMS.Web.Services
|
||||
{
|
||||
public class MqttService : BackgroundService
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly MqttMessageChannel _channel;
|
||||
private IManagedMqttClient _mqttClient;
|
||||
|
||||
public MqttService(IServiceProvider serviceProvider, IConfiguration configuration, MqttMessageChannel channel)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
_configuration = configuration;
|
||||
_channel = channel;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
var factory = new MqttFactory();
|
||||
_mqttClient = factory.CreateManagedMqttClient();
|
||||
|
||||
// 1. Handle received messages
|
||||
_mqttClient.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
var payload = e.ApplicationMessage.PayloadSegment.Array != null ?
|
||||
System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment) : string.Empty;
|
||||
|
||||
var record = new MqttMessageRecord
|
||||
{
|
||||
Topic = e.ApplicationMessage.Topic,
|
||||
Payload = payload,
|
||||
ReceiveTime = DateTime.Now,
|
||||
IsProcessed = false
|
||||
};
|
||||
await _channel.AddMessageAsync(record, stoppingToken);
|
||||
};
|
||||
|
||||
// 2. Setup MQTT options
|
||||
var mqttOptions = new MqttClientOptionsBuilder()
|
||||
.WithClientId($"HHWMS_Service_{Guid.NewGuid()}")
|
||||
.WithTcpServer(_configuration["Mqtt:Server"] ?? "127.0.0.1", int.Parse(_configuration["Mqtt:Port"] ?? "1883"));
|
||||
|
||||
var user = _configuration["Mqtt:Username"];
|
||||
if (!string.IsNullOrEmpty(user))
|
||||
{
|
||||
mqttOptions.WithCredentials(user, _configuration["Mqtt:Password"]);
|
||||
}
|
||||
|
||||
var managedOptions = new ManagedMqttClientOptionsBuilder()
|
||||
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
|
||||
.WithClientOptions(mqttOptions.Build())
|
||||
.Build();
|
||||
|
||||
// 3. Start the client
|
||||
await _mqttClient.StartAsync(managedOptions);
|
||||
|
||||
// 4. Periodically sync subscriptions from database
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var scope = _serviceProvider.CreateScope())
|
||||
{
|
||||
var unitwork = scope.ServiceProvider.GetRequiredService<IUnitWork>();
|
||||
var subscriptions = unitwork.Find<MqttSubscription>(x => x.IsEnabled).ToList();
|
||||
|
||||
if (subscriptions.Any())
|
||||
{
|
||||
var subOptionsBuilder = factory.CreateSubscribeOptionsBuilder();
|
||||
foreach (var sub in subscriptions)
|
||||
{
|
||||
var qosLevel = sub.Qos switch
|
||||
{
|
||||
1 => MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
2 => MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
_ => MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
||||
};
|
||||
subOptionsBuilder.WithTopicFilter(f => f.WithTopic(sub.Topic).WithQualityOfServiceLevel(qosLevel));
|
||||
}
|
||||
await _mqttClient.SubscribeAsync(subOptionsBuilder.Build().TopicFilters);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Basic logging or handling
|
||||
}
|
||||
|
||||
// Check for new subscriptions every 1 minute
|
||||
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_mqttClient != null)
|
||||
{
|
||||
await _mqttClient.StopAsync();
|
||||
}
|
||||
await base.StopAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user