mqtt 1
This commit is contained in:
1 parent
17b3236989
commit
55cce81912
8 files changed
+266
-8
No files matched your search
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using HHWMS.Web.Models;
|
||||
using Quartz;
|
||||
using WalkingTec.Mvvm.Core;
|
||||
using WalkingTec.Mvvm.Core.Support.Quartz;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using HHWMS.Web.Services;
|
||||
using System.Linq;
|
||||
using MQTTnet.Extensions.ManagedClient;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
//[QuartzRepeat(5,5, true, -1)]
|
||||
[PersistJobDataAfterExecution]
|
||||
[DisallowConcurrentExecution]
|
||||
public class MqttMessageJob : WtmJob
|
||||
{
|
||||
public override async Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
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
|
||||
while (_channel.Reader.TryRead(out var message))
|
||||
{
|
||||
try
|
||||
{
|
||||
// Parse your message.Payload here.
|
||||
// For example, based on specific business logic.
|
||||
|
||||
message.IsProcessed = true;
|
||||
message.ProcessTime = DateTime.Now;
|
||||
message.ProcessResult = "Success";
|
||||
|
||||
_unitwork.Add(message);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
message.IsProcessed = true;
|
||||
message.ProcessTime = DateTime.Now;
|
||||
message.ProcessResult = $"Error: {ex.Message}";
|
||||
_unitwork.Add(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Check MQTT connection and subscriptions
|
||||
await CheckMqttConnectionAndSubscriptionsAsync(_configuration, _channel, _unitwork);
|
||||
|
||||
await _unitwork.SaveChangesAsync();
|
||||
|
||||
#region 更新时间
|
||||
var job = _unitwork.FindSingle<SysJob>(x =>
|
||||
x.JobName == context.JobDetail.Key.Name
|
||||
);
|
||||
if (job != null)
|
||||
{
|
||||
job.LastFireTime = TimeZoneInfo.ConvertTimeFromUtc(
|
||||
context.FireTimeUtc.DateTime,
|
||||
TimeZoneInfo.Local
|
||||
);
|
||||
if (context.NextFireTimeUtc != null)
|
||||
{
|
||||
job.NextFireTime = TimeZoneInfo.ConvertTimeFromUtc(
|
||||
context.NextFireTimeUtc.Value.DateTime,
|
||||
TimeZoneInfo.Local
|
||||
);
|
||||
}
|
||||
_unitwork.Update<SysJob>(job);
|
||||
await _unitwork.SaveChangesAsync();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user