修改mqtt订阅位程序启动,定时器只定时消费
This commit is contained in:
1 parent
09098c020a
commit
96d8309793
3 files changed
+120
-141
No files matched your search
@@ -7,7 +7,6 @@ using WalkingTec.Mvvm.Core.Support.Quartz;
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using HHWMS.Web.Services;
|
using HHWMS.Web.Services;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using MQTTnet.Extensions.ManagedClient;
|
|
||||||
|
|
||||||
namespace HHWMS.Web
|
namespace HHWMS.Web
|
||||||
{
|
{
|
||||||
@@ -22,78 +21,17 @@ namespace HHWMS.Web
|
|||||||
{
|
{
|
||||||
var _unitwork = new UnitWork(Wtm);
|
var _unitwork = new UnitWork(Wtm);
|
||||||
var _channel = Wtm.ServiceProvider.GetRequiredService<MqttMessageChannel>();
|
var _channel = Wtm.ServiceProvider.GetRequiredService<MqttMessageChannel>();
|
||||||
var _configuration = Wtm.ServiceProvider.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>();
|
|
||||||
|
|
||||||
Wtm.DoLog("执行MQTT消息消费", ActionLogTypesEnum.Job, "MqttMessageJob");
|
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))
|
while (_channel.Reader.TryRead(out var message))
|
||||||
{
|
{
|
||||||
try
|
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.IsProcessed = true;
|
||||||
message.ProcessTime = DateTime.Now;
|
message.ProcessTime = DateTime.Now;
|
||||||
|
message.ProcessResult = "Success";
|
||||||
|
|
||||||
_unitwork.Add(message);
|
_unitwork.Add(message);
|
||||||
}
|
}
|
||||||
@@ -106,8 +44,6 @@ namespace HHWMS.Web
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check MQTT connection and subscriptions
|
|
||||||
await CheckMqttConnectionAndSubscriptionsAsync(_configuration, _channel, _unitwork);
|
|
||||||
|
|
||||||
await _unitwork.SaveChangesAsync();
|
await _unitwork.SaveChangesAsync();
|
||||||
|
|
||||||
@@ -138,80 +74,5 @@ namespace HHWMS.Web
|
|||||||
Wtm.DoLog("处理MQTT消息异常", ActionLogTypesEnum.Job, "MqttMessageJob", request:"error", result:ex.Message);
|
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<MqttSubscription>(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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,6 +65,8 @@ builder.Services.AddSignalR()
|
|||||||
builder.Services.AddSingleton<StockTicker>();
|
builder.Services.AddSingleton<StockTicker>();
|
||||||
|
|
||||||
builder.Services.AddSingleton<HHWMS.Web.Services.MqttMessageChannel>();
|
builder.Services.AddSingleton<HHWMS.Web.Services.MqttMessageChannel>();
|
||||||
|
builder.Services.AddHostedService<HHWMS.Web.Services.MqttService>();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|||||||
@@ -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