From 96d8309793752cf920ce9d2927ec561819b816d6 Mon Sep 17 00:00:00 2001 From: zhougf Date: Tue, 14 Apr 2026 23:34:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9mqtt=E8=AE=A2=E9=98=85?= =?UTF-8?q?=E4=BD=8D=E7=A8=8B=E5=BA=8F=E5=90=AF=E5=8A=A8=EF=BC=8C=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E5=99=A8=E5=8F=AA=E5=AE=9A=E6=97=B6=E6=B6=88=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../System/Controllers/jobs/MqttMessageJob.cs | 143 +----------------- HHWMS.Web/Program.cs | 2 + HHWMS.Web/Services/MqttService.cs | 116 ++++++++++++++ 3 files changed, 120 insertions(+), 141 deletions(-) create mode 100644 HHWMS.Web/Services/MqttService.cs diff --git a/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs b/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs index 9c9d0b4..d23f644 100644 --- a/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs +++ b/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs @@ -7,7 +7,6 @@ using WalkingTec.Mvvm.Core.Support.Quartz; using Microsoft.Extensions.DependencyInjection; using HHWMS.Web.Services; using System.Linq; -using MQTTnet.Extensions.ManagedClient; namespace HHWMS.Web { @@ -22,78 +21,17 @@ namespace HHWMS.Web { var _unitwork = new UnitWork(Wtm); var _channel = Wtm.ServiceProvider.GetRequiredService(); - var _configuration = Wtm.ServiceProvider.GetRequiredService(); Wtm.DoLog("执行MQTT消息消费", ActionLogTypesEnum.Job, "MqttMessageJob"); - // Read all available messages currently in the channel without blocking indefinitely + // Drain the channel and process messages while (_channel.Reader.TryRead(out var message)) { try { - // Parse your message.Payload here. - if (!string.IsNullOrEmpty(message.Payload)) - { - try - { - var jObj = System.Text.Json.Nodes.JsonNode.Parse(message.Payload) as System.Text.Json.Nodes.JsonObject; - if (jObj != null) - { - var parsedObj = new System.Text.Json.Nodes.JsonObject(); - - string[] fieldsToExtract = new[] { - "setSpindleSpeed", "setFeedRate", "spindleSpeedAndFeedRate", - "currentProduceCount", "expectProduceCount", "boottime", - "runtime", "cuttime", "statusInfo", "timestamp" - }; - - bool hasAnyField = false; - foreach (var field in fieldsToExtract) - { - if (jObj.ContainsKey(field)) - { - // Clone the node to avoid "node already has a parent" exception - var nodeValue = jObj[field]; - if (nodeValue != null) - { - var clonedNode = System.Text.Json.Nodes.JsonNode.Parse(nodeValue.ToJsonString()); - parsedObj.Add(field, clonedNode); - } - else - { - parsedObj.Add(field, null); - } - hasAnyField = true; - } - } - - if (hasAnyField) - { - message.ParsedData = parsedObj.ToJsonString(); - message.ProcessResult = "Success (Parsed)"; - } - else - { - message.ProcessResult = "Success (No matching fields)"; - } - } - else - { - message.ProcessResult = "Success (Not JSON Object)"; - } - } - catch (Exception parseEx) - { - message.ProcessResult = $"Parse JSON Error: {parseEx.Message}"; - } - } - else - { - message.ProcessResult = "Success (Empty payload)"; - } - message.IsProcessed = true; message.ProcessTime = DateTime.Now; + message.ProcessResult = "Success"; _unitwork.Add(message); } @@ -106,8 +44,6 @@ namespace HHWMS.Web } } - // Check MQTT connection and subscriptions - await CheckMqttConnectionAndSubscriptionsAsync(_configuration, _channel, _unitwork); await _unitwork.SaveChangesAsync(); @@ -138,80 +74,5 @@ namespace HHWMS.Web Wtm.DoLog("处理MQTT消息异常", ActionLogTypesEnum.Job, "MqttMessageJob", request:"error", result:ex.Message); } } - - private static MQTTnet.Extensions.ManagedClient.IManagedMqttClient _mqttClient; - - private async Task CheckMqttConnectionAndSubscriptionsAsync( - Microsoft.Extensions.Configuration.IConfiguration configuration, - MqttMessageChannel channel, - IUnitWork unitwork) - { - if (_mqttClient == null) - { - var factory = new MQTTnet.MqttFactory(); - _mqttClient = factory.CreateManagedMqttClient(); - - _mqttClient.ApplicationMessageReceivedAsync += async e => - { - var payload = e.ApplicationMessage.PayloadSegment.Array != null ? - System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment) : string.Empty; - - var topic = e.ApplicationMessage.Topic; - - var record = new MqttMessageRecord - { - Topic = topic, - Payload = payload, - ReceiveTime = DateTime.Now, - IsProcessed = false - }; - - await channel.AddMessageAsync(record); - }; - - var mqttOptions = new MQTTnet.Client.MqttClientOptionsBuilder() - .WithClientId($"HHWMS_Client_{Guid.NewGuid()}") - .WithTcpServer(configuration["Mqtt:Server"] ?? "127.0.0.1", int.Parse(configuration["Mqtt:Port"] ?? "1883")); - - var user = configuration["Mqtt:Username"]; - var pass = configuration["Mqtt:Password"]; - if (!string.IsNullOrEmpty(user)) - { - mqttOptions.WithCredentials(user, pass); - } - - var managedOptions = new MQTTnet.Extensions.ManagedClient.ManagedMqttClientOptionsBuilder() - .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) - .WithClientOptions(mqttOptions.Build()) - .Build(); - - await _mqttClient.StartAsync(managedOptions); - } - - // Sync subscriptions - var subscriptions = unitwork.Find(x => x.ID > 0) - .Where(s => s.IsEnabled) - .ToList(); - - if (subscriptions.Any()) - { - var factory = new MQTTnet.MqttFactory(); - var subscribeOptionsBuilder = 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 - }; - - subscribeOptionsBuilder.WithTopicFilter(f => f.WithTopic(sub.Topic).WithQualityOfServiceLevel(qosLevel)); - } - - await _mqttClient.SubscribeAsync(subscribeOptionsBuilder.Build().TopicFilters); - } - } } } diff --git a/HHWMS.Web/Program.cs b/HHWMS.Web/Program.cs index 9b453a3..080be75 100644 --- a/HHWMS.Web/Program.cs +++ b/HHWMS.Web/Program.cs @@ -65,6 +65,8 @@ builder.Services.AddSignalR() builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddHostedService(); + var app = builder.Build(); diff --git a/HHWMS.Web/Services/MqttService.cs b/HHWMS.Web/Services/MqttService.cs new file mode 100644 index 0000000..9ea6940 --- /dev/null +++ b/HHWMS.Web/Services/MqttService.cs @@ -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(); + var subscriptions = unitwork.Find(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); + } + } +}