mqtt 1
This commit is contained in:
1 parent
17b3236989
commit
55cce81912
8 files changed
+265
-7
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -54,6 +54,8 @@ namespace HHWMS.Web
|
|||||||
public DbSet<ReportDesign> ReportDesigns { get; set; }
|
public DbSet<ReportDesign> ReportDesigns { get; set; }
|
||||||
public DbSet<Material> Materials { get; set; }
|
public DbSet<Material> Materials { get; set; }
|
||||||
public DbSet<PrintConfig> PrintConfigs { get; set; }
|
public DbSet<PrintConfig> PrintConfigs { get; set; }
|
||||||
|
public DbSet<MqttSubscription> MqttSubscriptions { get; set; }
|
||||||
|
public DbSet<MqttMessageRecord> MqttMessageRecords { get; set; }
|
||||||
public override async Task<bool> DataInit(object allModules, bool IsSpa)
|
public override async Task<bool> DataInit(object allModules, bool IsSpa)
|
||||||
{
|
{
|
||||||
var state = await base.DataInit(allModules, IsSpa);
|
var state = await base.DataInit(allModules, IsSpa);
|
||||||
@@ -138,7 +140,7 @@ namespace HHWMS.Web
|
|||||||
{
|
{
|
||||||
public DataContext CreateDbContext(string[] args)
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,13 +17,9 @@
|
|||||||
<Import Project="..\common.props" />
|
<Import Project="..\common.props" />
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Remove="Migrations\**" />
|
|
||||||
<Compile Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
<Compile Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
||||||
<Content Remove="Migrations\**" />
|
|
||||||
<Content Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
<Content Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
||||||
<EmbeddedResource Remove="Migrations\**" />
|
|
||||||
<EmbeddedResource Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
<EmbeddedResource Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
||||||
<None Remove="Migrations\**" />
|
|
||||||
<None Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
<None Remove="wwwroot\hiprint\vue-plugin-hiprint\**" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
@@ -63,6 +59,7 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="MQTTnet.Extensions.ManagedClient" Version="4.3.7.1207" />
|
||||||
<PackageReference Include="SoapCore" Version="1.1.0.38" />
|
<PackageReference Include="SoapCore" Version="1.1.0.38" />
|
||||||
<PackageReference Include="SqlSugarCore" Version="5.1.4.143" />
|
<PackageReference Include="SqlSugarCore" Version="5.1.4.143" />
|
||||||
<PackageReference Include="System.Reactive.Linq" Version="6.0.0" />
|
<PackageReference Include="System.Reactive.Linq" Version="6.0.0" />
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -64,6 +64,8 @@ builder.Services.AddSignalR()
|
|||||||
|
|
||||||
builder.Services.AddSingleton<StockTicker>();
|
builder.Services.AddSingleton<StockTicker>();
|
||||||
|
|
||||||
|
builder.Services.AddSingleton<HHWMS.Web.Services.MqttMessageChannel>();
|
||||||
|
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
IOptionsMonitor<Configs> config = app.Services.GetRequiredService<IOptionsMonitor<Configs>>();
|
IOptionsMonitor<Configs> config = app.Services.GetRequiredService<IOptionsMonitor<Configs>>();
|
||||||
|
|||||||
@@ -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<MqttMessageRecord> _channel;
|
||||||
|
|
||||||
|
public MqttMessageChannel()
|
||||||
|
{
|
||||||
|
_channel = Channel.CreateUnbounded<MqttMessageRecord>(new UnboundedChannelOptions
|
||||||
|
{
|
||||||
|
SingleReader = true,
|
||||||
|
SingleWriter = false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask AddMessageAsync(MqttMessageRecord message, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await _channel.Writer.WriteAsync(message, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChannelReader<MqttMessageRecord> Reader => _channel.Reader;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,11 +20,10 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
"Connections": [
|
"Connections": [
|
||||||
{
|
{
|
||||||
"Key": "default",
|
"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"
|
"DBType": "mysql"
|
||||||
},
|
},
|
||||||
//{
|
//{
|
||||||
@@ -124,5 +123,11 @@
|
|||||||
"In": "123",
|
"In": "123",
|
||||||
"Charge": "123",
|
"Charge": "123",
|
||||||
"OutIn": "123",
|
"OutIn": "123",
|
||||||
|
},
|
||||||
|
"Mqtt": {
|
||||||
|
"Server": "127.0.0.1",
|
||||||
|
"Port": 1883,
|
||||||
|
"Username": "",
|
||||||
|
"Password": ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user