Compare commits

..
4 Commits
Author SHA1 Message Date
zhougf 96d8309793 修改mqtt订阅位程序启动,定时器只定时消费 2026-04-14 23:34:56 +08:00
zhougf 09098c020a mqtt test 2026-03-22 14:31:52 +08:00
zhougf 55cce81912 mqtt 1 2026-03-07 17:01:46 +08:00
zhougf 17b3236989 添加库存查询条件
入库保存时,依据容器的code,并不是前端传递的code
2026-03-07 11:26:25 +08:00
13 changed files with 316 additions and 11 deletions

No files matched your search

@@ -110,6 +110,7 @@ namespace HHWMS.Web
var query = DC.Set<Inventory>() var query = DC.Set<Inventory>()
.CheckContain(Searcher.ZoneCode, x => x.ZoneCode) .CheckContain(Searcher.ZoneCode, x => x.ZoneCode)
.CheckContain(Searcher.LocationCode, x => x.LocationCode) .CheckContain(Searcher.LocationCode, x => x.LocationCode)
.CheckContain(Searcher.ContainerCode, x => x.ContainerCode)
.CheckContain(Searcher.MaterialCode, x => x.MaterialCode) .CheckContain(Searcher.MaterialCode, x => x.MaterialCode)
.CheckContain(Searcher.MaterialType, x => x.MaterialType) .CheckContain(Searcher.MaterialType, x => x.MaterialType)
.CheckContain(Searcher.MaterialName, x => x.MaterialName) .CheckContain(Searcher.MaterialName, x => x.MaterialName)
@@ -14,8 +14,12 @@ namespace HHWMS.Web
{ {
[Display(Name = "Task.ZoneCode")] [Display(Name = "Task.ZoneCode")]
public String ZoneCode { get; set; } public String ZoneCode { get; set; }
[Display(Name = "Inventory.LocationCode")] [Display(Name = "Container.LocationCode")]
public String LocationCode { get; set; } public String LocationCode { get; set; }
[Display(Name = "Task.ContainerCode")]
public String ContainerCode { get; set; }
[Display(Name = "Inventory.UniqueCode")] [Display(Name = "Inventory.UniqueCode")]
public String UniqueCode { get; set; } public String UniqueCode { get; set; }
[Display(Name = "Inventory.MaterialCode")] [Display(Name = "Inventory.MaterialCode")]
@@ -5,6 +5,9 @@
<wt:row items-per-row="ItemsPerRowEnum.Three"> <wt:row items-per-row="ItemsPerRowEnum.Three">
<wt:textbox field="Searcher.MaterialCode" /> <wt:textbox field="Searcher.MaterialCode" />
<wt:textbox field="Searcher.MaterialName" /> <wt:textbox field="Searcher.MaterialName" />
<wt:textbox field="Searcher.ContainerCode" />
<wt:textbox field="Searcher.LocationCode" />
@*<wt:textbox field="Searcher.MaterialType" /> @*<wt:textbox field="Searcher.MaterialType" />
<wt:textbox field="Searcher.MaterialSpec" /> <wt:textbox field="Searcher.MaterialSpec" />
<wt:textbox field="Searcher.MaterialUnit" /> <wt:textbox field="Searcher.MaterialUnit" />
@@ -89,7 +89,7 @@ namespace HHWMS.Web.Controllers
var inventory = new Inventory() var inventory = new Inventory()
{ {
ZoneCode = ZoneCodeEnum.立库, ZoneCode = ZoneCodeEnum.立库,
ContainerCode = containerCode, ContainerCode = container.Code,
MaterialCode = material.MaterialCode, MaterialCode = material.MaterialCode,
MaterialName = material.MaterialName, MaterialName = material.MaterialName,
MaterialType = material.MaterialType, MaterialType = material.MaterialType,
@@ -108,7 +108,7 @@ namespace HHWMS.Web.Controllers
MaterialCode = material.MaterialCode, MaterialCode = material.MaterialCode,
MaterialName = material.MaterialName, MaterialName = material.MaterialName,
MaterialUnit = material.MaterialUnit, MaterialUnit = material.MaterialUnit,
ContainerCode = containerCode, ContainerCode = container.Code,
Qty = qty, Qty = qty,
CreateTime = DateTime.Now, CreateTime = DateTime.Now,
CreateBy = "WMS", CreateBy = "WMS",
@@ -194,7 +194,7 @@ namespace HHWMS.Web.Controllers
ZoneCode = ZoneCodeEnum.立库, ZoneCode = ZoneCodeEnum.立库,
TaskNo = _unitWork.GetSerialNumber("In"), TaskNo = _unitWork.GetSerialNumber("In"),
TaskType = TaskTypeEnum.立库入库, TaskType = TaskTypeEnum.立库入库,
ContainerCode = containerCode, ContainerCode = container.Code,
FromLocation = "", FromLocation = "",
ToLocation = location.Code, ToLocation = location.Code,
Status = TaskStatusEnum.待下发, Status = TaskStatusEnum.待下发,
@@ -0,0 +1,78 @@
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;
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>();
Wtm.DoLog("执行MQTT消息消费", ActionLogTypesEnum.Job, "MqttMessageJob");
// Drain the channel and process messages
while (_channel.Reader.TryRead(out var message))
{
try
{
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);
}
}
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);
}
}
}
}
+3 -1
View File
@@ -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);
} }
} }
} }
+1 -4
View File
@@ -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,37 @@
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; }
[Display(Name = "Mqtt.ParsedData", Description = "解析后数据")]
public string ParsedData { get; set; }
}
}
+30
View File
@@ -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; }
}
}
+4
View File
@@ -64,6 +64,10 @@ builder.Services.AddSignalR()
builder.Services.AddSingleton<StockTicker>(); builder.Services.AddSingleton<StockTicker>();
builder.Services.AddSingleton<HHWMS.Web.Services.MqttMessageChannel>();
builder.Services.AddHostedService<HHWMS.Web.Services.MqttService>();
var app = builder.Build(); var app = builder.Build();
IOptionsMonitor<Configs> config = app.Services.GetRequiredService<IOptionsMonitor<Configs>>(); IOptionsMonitor<Configs> config = app.Services.GetRequiredService<IOptionsMonitor<Configs>>();
+28
View File
@@ -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;
}
}
+116
View File
@@ -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);
}
}
}
+7 -2
View File
@@ -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": ""
} }
} }