From 55cce81912a4feb17f664290a67eb96fb61e502c Mon Sep 17 00:00:00 2001 From: zhougf Date: Sat, 7 Mar 2026 17:01:46 +0800 Subject: [PATCH] mqtt 1 --- .../System/Controllers/jobs/MqttMessageJob.cs | 160 ++++++++++++++++++ HHWMS.Web/DataContext.cs | 4 +- HHWMS.Web/HHWMS.Web.csproj | 5 +- HHWMS.Web/Models/Mqtt/MqttMessageRecord.cs | 34 ++++ HHWMS.Web/Models/Mqtt/MqttSubscription.cs | 30 ++++ HHWMS.Web/Program.cs | 2 + HHWMS.Web/Services/MqttMessageChannel.cs | 28 +++ HHWMS.Web/appsettings.json | 11 +- 8 files changed, 266 insertions(+), 8 deletions(-) create mode 100644 HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs create mode 100644 HHWMS.Web/Models/Mqtt/MqttMessageRecord.cs create mode 100644 HHWMS.Web/Models/Mqtt/MqttSubscription.cs create mode 100644 HHWMS.Web/Services/MqttMessageChannel.cs diff --git a/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs b/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs new file mode 100644 index 0000000..8eb9cf4 --- /dev/null +++ b/HHWMS.Web/Areas/System/Controllers/jobs/MqttMessageJob.cs @@ -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(); + var _configuration = Wtm.ServiceProvider.GetRequiredService(); + + 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(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(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(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/DataContext.cs b/HHWMS.Web/DataContext.cs index fb0faa2..aca96eb 100644 --- a/HHWMS.Web/DataContext.cs +++ b/HHWMS.Web/DataContext.cs @@ -54,6 +54,8 @@ namespace HHWMS.Web public DbSet ReportDesigns { get; set; } public DbSet Materials { get; set; } public DbSet PrintConfigs { get; set; } + public DbSet MqttSubscriptions { get; set; } + public DbSet MqttMessageRecords { get; set; } public override async Task DataInit(object allModules, bool IsSpa) { var state = await base.DataInit(allModules, IsSpa); @@ -138,7 +140,7 @@ namespace HHWMS.Web { public DataContext CreateDbContext(string[] args) { - return new DataContext("Server=(localdb)\\mssqllocaldb;Database=HHWMS;Trusted_Connection=True;MultipleActiveResultSets=true", DBTypeEnum.SqlServer); + return new DataContext("Server=127.0.0.1;Port=3306;Database=wms3;Uid=root;Password=abc123*;Character Set=utf8mb4;", DBTypeEnum.MySql); } } } diff --git a/HHWMS.Web/HHWMS.Web.csproj b/HHWMS.Web/HHWMS.Web.csproj index 5f08f3f..1d8ff19 100644 --- a/HHWMS.Web/HHWMS.Web.csproj +++ b/HHWMS.Web/HHWMS.Web.csproj @@ -17,13 +17,9 @@ - - - - @@ -63,6 +59,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/HHWMS.Web/Models/Mqtt/MqttMessageRecord.cs b/HHWMS.Web/Models/Mqtt/MqttMessageRecord.cs new file mode 100644 index 0000000..0fc73e4 --- /dev/null +++ b/HHWMS.Web/Models/Mqtt/MqttMessageRecord.cs @@ -0,0 +1,34 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using WalkingTec.Mvvm.Core; + +namespace HHWMS.Web.Models +{ + [Table("MqttMessageRecord")] + public class MqttMessageRecord : BasePoco + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public new int ID { get; set; } + + [Display(Name = "Mqtt.Topic", Description = "主题")] + [StringLength(200, ErrorMessage = "Validate.{0}stringmax{1}")] + public string Topic { get; set; } + + [Display(Name = "Mqtt.Payload", Description = "消息内容")] + public string Payload { get; set; } + + [Display(Name = "Mqtt.ReceiveTime", Description = "接收时间")] + public DateTime ReceiveTime { get; set; } + + [Display(Name = "Mqtt.IsProcessed", Description = "是否已处理")] + public bool IsProcessed { get; set; } + + [Display(Name = "Mqtt.ProcessTime", Description = "处理时间")] + public DateTime? ProcessTime { get; set; } + + [Display(Name = "Mqtt.ProcessResult", Description = "处理结果")] + public string ProcessResult { get; set; } + } +} diff --git a/HHWMS.Web/Models/Mqtt/MqttSubscription.cs b/HHWMS.Web/Models/Mqtt/MqttSubscription.cs new file mode 100644 index 0000000..7b02aff --- /dev/null +++ b/HHWMS.Web/Models/Mqtt/MqttSubscription.cs @@ -0,0 +1,30 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using WalkingTec.Mvvm.Core; + +namespace HHWMS.Web.Models +{ + [Table("MqttSubscription")] + public class MqttSubscription : BasePoco + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public new int ID { get; set; } + + [Display(Name = "Mqtt.Topic", Description = "订阅主题")] + [StringLength(200, ErrorMessage = "Validate.{0}stringmax{1}")] + [Required(ErrorMessage = "Validate.{0}required")] + public string Topic { get; set; } + + [Display(Name = "Mqtt.Qos", Description = "服务质量(0,1,2)")] + public int Qos { get; set; } + + [Display(Name = "Mqtt.IsEnabled", Description = "是否启用")] + public bool IsEnabled { get; set; } + + [Display(Name = "Mqtt.Remark", Description = "备注")] + [StringLength(500, ErrorMessage = "Validate.{0}stringmax{1}")] + public string Remark { get; set; } + } +} diff --git a/HHWMS.Web/Program.cs b/HHWMS.Web/Program.cs index 2b5c3aa..9b453a3 100644 --- a/HHWMS.Web/Program.cs +++ b/HHWMS.Web/Program.cs @@ -64,6 +64,8 @@ builder.Services.AddSignalR() builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + var app = builder.Build(); IOptionsMonitor config = app.Services.GetRequiredService>(); diff --git a/HHWMS.Web/Services/MqttMessageChannel.cs b/HHWMS.Web/Services/MqttMessageChannel.cs new file mode 100644 index 0000000..298eee9 --- /dev/null +++ b/HHWMS.Web/Services/MqttMessageChannel.cs @@ -0,0 +1,28 @@ +using System.Threading.Channels; +using System.Threading.Tasks; +using HHWMS.Web.Models; +using System.Threading; + +namespace HHWMS.Web.Services +{ + public class MqttMessageChannel + { + private readonly Channel _channel; + + public MqttMessageChannel() + { + _channel = Channel.CreateUnbounded(new UnboundedChannelOptions + { + SingleReader = true, + SingleWriter = false + }); + } + + public async ValueTask AddMessageAsync(MqttMessageRecord message, CancellationToken cancellationToken = default) + { + await _channel.Writer.WriteAsync(message, cancellationToken); + } + + public ChannelReader Reader => _channel.Reader; + } +} diff --git a/HHWMS.Web/appsettings.json b/HHWMS.Web/appsettings.json index f058e0c..d7fb883 100644 --- a/HHWMS.Web/appsettings.json +++ b/HHWMS.Web/appsettings.json @@ -20,11 +20,10 @@ } } }, - "Connections": [ { "Key": "default", - "Value": "Server=127.0.0.1;Port=3306;Database=lkwms;Uid=root;Password=abc123*;Character Set=utf8mb4;", + "Value": "Server=127.0.0.1;Port=3306;Database=wms3;Uid=root;Password=abc123*;Character Set=utf8mb4;", "DBType": "mysql" }, //{ @@ -124,5 +123,11 @@ "In": "123", "Charge": "123", "OutIn": "123", + }, + "Mqtt": { + "Server": "127.0.0.1", + "Port": 1883, + "Username": "", + "Password": "" } -} +} \ No newline at end of file