修改mqtt订阅位程序启动,定时器只定时消费

This commit is contained in:
zhougf committed 2026-04-14 23:34:56 +08:00
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 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<MqttMessageChannel>();
var _configuration = Wtm.ServiceProvider.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>();
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<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);
}
}
}
}