Compare commits

...
2 Commits
Author SHA1 Message Date
zhougf 0c4077f181 Add dashboard device data push pipeline 2026-06-01 21:48:29 +08:00
zhougf 8a0aa8f7cb Add MQTT runtime control and device data pipeline 2026-05-31 10:55:22 +08:00
34 changed files with 31640 additions and 19 deletions

No files matched your search

+2
View File
@@ -15,6 +15,8 @@ node_modules/
.cache-loader .cache-loader
Migrations/ Migrations/
!HHWMS.Web/Migrations/
!HHWMS.Web/Migrations/**
*.pubxml *.pubxml
# User-specific files # User-specific files
+141
View File
@@ -0,0 +1,141 @@
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using Microsoft.AspNetCore.SignalR;
namespace HHWMS.Web
{
public class DashboardHub : Hub
{
private readonly IUnitWork _unitWork;
public DashboardHub(IUnitWork unitWork)
{
_unitWork = unitWork;
}
public Task<object> GetSnapshot()
{
var productionDate = DateTime.Today;
var dailyProductions = _unitWork.Find<DeviceProductionDaily>(x => x.ProductionDate == productionDate).ToList();
var productionStartDate = productionDate.AddDays(-6);
var recentProductions = _unitWork.Find<DeviceProductionDaily>(x => x.ProductionDate >= productionStartDate && x.ProductionDate <= productionDate).ToList();
var states = _unitWork.Find<DeviceCurrentState>(x => true)
.OrderBy(x => x.DeviceType)
.ThenBy(x => x.DeviceId)
.ToList();
var devices = states
.Select(x => new
{
x.DeviceId,
x.DeviceName,
x.DeviceType,
x.Status,
x.LastPayloadTime,
x.LastUpdateTime,
x.AlarmSummary,
Realtime = ParseRealtimeJson(x, dailyProductions.FirstOrDefault(d => d.DeviceId == x.DeviceId)),
DailyProduction = BuildDailyProduction(x.DeviceId, productionDate, recentProductions),
TrendPoints = BuildRecentTrendPoints(x.DeviceId, x.DeviceType, _unitWork)
})
.ToList();
var alarms = _unitWork.Find<DeviceAlarmRecord>(x => x.IsActive)
.OrderByDescending(x => x.LastSeenTime ?? x.StartTime)
.Take(20)
.Select(x => new
{
x.DeviceId,
x.AlarmCode,
x.AlarmMessage,
x.StartTime,
x.LastSeenTime,
x.RepeatCount
})
.ToList();
return Task.FromResult<object>(new
{
generatedAt = DateTime.Now,
devices,
alarms
});
}
private static object ParseRealtimeJson(DeviceCurrentState state, DeviceProductionDaily daily)
{
if (string.IsNullOrWhiteSpace(state.RealtimeJson))
{
return null;
}
try
{
var node = JsonNode.Parse(state.RealtimeJson);
if (node is JsonObject obj && state.DeviceType == "cnc" && daily != null)
{
obj["todayProduce"] = daily.ProduceCount;
}
return node == null ? null : JsonSerializer.Deserialize<object>(node.ToJsonString());
}
catch
{
return state.RealtimeJson;
}
}
private static object BuildDailyProduction(string deviceId, DateTime endDate, System.Collections.Generic.IEnumerable<DeviceProductionDaily> productions)
{
var rows = productions.Where(x => x.DeviceId == deviceId).ToList();
var dates = Enumerable.Range(0, 7).Select(offset => endDate.AddDays(offset - 6).Date).ToList();
return new
{
dates = dates.Select(x => x.ToString("MM/dd")).ToArray(),
produce = dates.Select(date => rows.FirstOrDefault(x => x.ProductionDate.Date == date)?.ProduceCount ?? 0).ToArray(),
runtime = dates.Select(date =>
{
var minutes = rows.FirstOrDefault(x => x.ProductionDate.Date == date)?.RuntimeMinutes ?? 0;
return Math.Round(minutes / 60m, 2);
}).ToArray()
};
}
private static object BuildRecentTrendPoints(string deviceId, string deviceType, IUnitWork unitWork)
{
if (deviceType != "power")
{
return Array.Empty<object>();
}
var startTime = DateTime.Now.AddHours(-1);
var metrics = new[] { "currentA", "currentB", "currentC", "estimatedPower" };
var windowPoints = unitWork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == deviceId && x.BucketTime >= startTime && metrics.Contains(x.MetricName)).ToList();
var leadingPoints = metrics
.Select(metric => unitWork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == deviceId && x.MetricName == metric && x.BucketTime < startTime)
.OrderByDescending(x => x.BucketTime)
.FirstOrDefault())
.Where(x => x != null)
.ToList();
return leadingPoints.Concat(windowPoints)
.OrderBy(x => x.BucketTime)
.Select(x => new
{
x.DeviceId,
x.MetricName,
x.BucketTime,
x.AvgValue,
x.MaxValue,
x.MinValue,
x.SampleCount
})
.ToList();
}
}
}
@@ -0,0 +1,66 @@
using System.Linq;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using HHWMS.Web.Services;
using Microsoft.AspNetCore.Mvc;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
namespace HHWMS.Web.Areas.System.Controllers
{
[Area("System")]
[Route("api/mqtt")]
[ApiController]
public class MqttRuntimeController : BaseController
{
private readonly IUnitWork _unitwork;
private readonly MqttRuntimeState _runtimeState;
private readonly MqttRuntimeStateRefresher _runtimeStateRefresher;
public MqttRuntimeController(
IUnitWork unitwork,
MqttRuntimeState runtimeState,
MqttRuntimeStateRefresher runtimeStateRefresher)
{
_unitwork = unitwork;
_runtimeState = runtimeState;
_runtimeStateRefresher = runtimeStateRefresher;
}
[HttpGet("status")]
public IActionResult Status()
{
var enabledSubscriptionCount = _unitwork.GetCount<MqttSubscription>(x => x.IsEnabled);
return Ok(new
{
enabled = _runtimeState.Enabled,
enabledSubscriptionCount,
lastChangedAt = _runtimeState.LastChangedAt,
lastChangedBy = _runtimeState.LastChangedBy
});
}
[HttpPost("refresh")]
public async Task<IActionResult> Refresh()
{
await _runtimeStateRefresher.RefreshFromSubscriptionsAsync(Wtm?.LoginUserInfo?.ITCode, HttpContext.RequestAborted);
return Status();
}
[HttpPost("subscriptions/{id:int}/enabled")]
public async Task<IActionResult> SetSubscriptionEnabled(int id, [FromQuery] bool enabled)
{
var subscription = _unitwork.Find<MqttSubscription>(x => x.ID == id).FirstOrDefault();
if (subscription == null)
{
return NotFound();
}
subscription.IsEnabled = enabled;
_unitwork.Update(subscription);
await _runtimeStateRefresher.RefreshFromSubscriptionsAsync(Wtm?.LoginUserInfo?.ITCode, HttpContext.RequestAborted);
return Status();
}
}
}
@@ -6,6 +6,7 @@ using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Support.Quartz; using WalkingTec.Mvvm.Core.Support.Quartz;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using HHWMS.Web.Services; using HHWMS.Web.Services;
using HHWMS.Web.Services.DeviceData;
using System.Linq; using System.Linq;
namespace HHWMS.Web namespace HHWMS.Web
@@ -21,26 +22,41 @@ namespace HHWMS.Web
{ {
var _unitwork = new UnitWork(Wtm); var _unitwork = new UnitWork(Wtm);
var _channel = Wtm.ServiceProvider.GetRequiredService<MqttMessageChannel>(); var _channel = Wtm.ServiceProvider.GetRequiredService<MqttMessageChannel>();
var runtimeState = Wtm.ServiceProvider.GetRequiredService<MqttRuntimeState>();
var powerCabinetProcessor = Wtm.ServiceProvider.GetRequiredService<PowerCabinetMessageProcessor>();
var cncProcessor = Wtm.ServiceProvider.GetRequiredService<CncMessageProcessor>();
var dashboardPushService = Wtm.ServiceProvider.GetRequiredService<DashboardPushService>();
Wtm.DoLog("执行MQTT消息消费", ActionLogTypesEnum.Job, "MqttMessageJob"); Wtm.DoLog("执行MQTT消息消费", ActionLogTypesEnum.Job, "MqttMessageJob");
// Drain the channel and process messages if (runtimeState.Enabled)
while (_channel.Reader.TryRead(out var message))
{ {
try // Drain the channel and process messages
while (_channel.Reader.TryRead(out var message))
{ {
message.IsProcessed = true; try
message.ProcessTime = DateTime.Now; {
message.ProcessResult = "Success"; var processingResult = powerCabinetProcessor.Process(message, _unitwork);
if (!processingResult.Handled)
{
processingResult = cncProcessor.Process(message, _unitwork);
}
message.IsProcessed = true;
message.ProcessTime = DateTime.Now;
message.ProcessResult = processingResult.Handled ? processingResult.Message : "Success";
message.ParsedData = processingResult.ParsedData;
_unitwork.Add(message); _unitwork.Add(message);
} await _unitwork.SaveChangesAsync();
catch(Exception ex) await dashboardPushService.PushProcessingResultAsync(processingResult, _unitwork);
{ }
message.IsProcessed = true; catch(Exception ex)
message.ProcessTime = DateTime.Now; {
message.ProcessResult = $"Error: {ex.Message}"; message.IsProcessed = true;
_unitwork.Add(message); message.ProcessTime = DateTime.Now;
message.ProcessResult = $"Error: {ex.Message}";
_unitwork.Add(message);
}
} }
} }
+4
View File
@@ -56,6 +56,10 @@ namespace HHWMS.Web
public DbSet<PrintConfig> PrintConfigs { get; set; } public DbSet<PrintConfig> PrintConfigs { get; set; }
public DbSet<MqttSubscription> MqttSubscriptions { get; set; } public DbSet<MqttSubscription> MqttSubscriptions { get; set; }
public DbSet<MqttMessageRecord> MqttMessageRecords { get; set; } public DbSet<MqttMessageRecord> MqttMessageRecords { get; set; }
public DbSet<DeviceCurrentState> DeviceCurrentStates { get; set; }
public DbSet<DeviceMetricTrendPoint> DeviceMetricTrendPoints { get; set; }
public DbSet<DeviceAlarmRecord> DeviceAlarmRecords { get; set; }
public DbSet<DeviceProductionDaily> DeviceProductionDailies { 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);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,204 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace HHWMS.Web.Migrations
{
public partial class updatetaskmodel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ReceiptDetail_ReceiptHeader_HeaderId",
table: "ReceiptDetail");
migrationBuilder.DropForeignKey(
name: "FK_ShipmentDetail_ShipmentHeader_HeaderId",
table: "ShipmentDetail");
migrationBuilder.DropForeignKey(
name: "FK_TaskDetail_TaskHeader_HeaderId",
table: "TaskDetail");
migrationBuilder.DropIndex(
name: "IX_TaskDetail_HeaderId",
table: "TaskDetail");
migrationBuilder.DropIndex(
name: "IX_ShipmentDetail_HeaderId",
table: "ShipmentDetail");
migrationBuilder.DropIndex(
name: "IX_ReceiptDetail_HeaderId",
table: "ReceiptDetail");
migrationBuilder.AlterColumn<string>(
name: "MaterialSpec",
table: "TaskDetailHistory",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "物料规格",
oldClrType: typeof(string),
oldType: "longtext",
oldNullable: true,
oldComment: "物料规格")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "MaterialSpec",
table: "TaskDetail",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "物料规格",
oldClrType: typeof(string),
oldType: "longtext",
oldNullable: true,
oldComment: "物料规格")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<int>(
name: "ShipmentHeaderID",
table: "ShipmentDetail",
type: "int",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "ReceiptHeaderID",
table: "ReceiptDetail",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_TaskHeaderHistory_TaskNo",
table: "TaskHeaderHistory",
column: "TaskNo",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ShipmentDetail_ShipmentHeaderID",
table: "ShipmentDetail",
column: "ShipmentHeaderID");
migrationBuilder.CreateIndex(
name: "IX_ReceiptDetail_ReceiptHeaderID",
table: "ReceiptDetail",
column: "ReceiptHeaderID");
migrationBuilder.AddForeignKey(
name: "FK_ReceiptDetail_ReceiptHeader_ReceiptHeaderID",
table: "ReceiptDetail",
column: "ReceiptHeaderID",
principalTable: "ReceiptHeader",
principalColumn: "ID");
migrationBuilder.AddForeignKey(
name: "FK_ShipmentDetail_ShipmentHeader_ShipmentHeaderID",
table: "ShipmentDetail",
column: "ShipmentHeaderID",
principalTable: "ShipmentHeader",
principalColumn: "ID");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ReceiptDetail_ReceiptHeader_ReceiptHeaderID",
table: "ReceiptDetail");
migrationBuilder.DropForeignKey(
name: "FK_ShipmentDetail_ShipmentHeader_ShipmentHeaderID",
table: "ShipmentDetail");
migrationBuilder.DropIndex(
name: "IX_TaskHeaderHistory_TaskNo",
table: "TaskHeaderHistory");
migrationBuilder.DropIndex(
name: "IX_ShipmentDetail_ShipmentHeaderID",
table: "ShipmentDetail");
migrationBuilder.DropIndex(
name: "IX_ReceiptDetail_ReceiptHeaderID",
table: "ReceiptDetail");
migrationBuilder.DropColumn(
name: "ShipmentHeaderID",
table: "ShipmentDetail");
migrationBuilder.DropColumn(
name: "ReceiptHeaderID",
table: "ReceiptDetail");
migrationBuilder.AlterColumn<string>(
name: "MaterialSpec",
table: "TaskDetailHistory",
type: "longtext",
nullable: true,
comment: "物料规格",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "物料规格")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "MaterialSpec",
table: "TaskDetail",
type: "longtext",
nullable: true,
comment: "物料规格",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "物料规格")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_TaskDetail_HeaderId",
table: "TaskDetail",
column: "HeaderId");
migrationBuilder.CreateIndex(
name: "IX_ShipmentDetail_HeaderId",
table: "ShipmentDetail",
column: "HeaderId");
migrationBuilder.CreateIndex(
name: "IX_ReceiptDetail_HeaderId",
table: "ReceiptDetail",
column: "HeaderId");
migrationBuilder.AddForeignKey(
name: "FK_ReceiptDetail_ReceiptHeader_HeaderId",
table: "ReceiptDetail",
column: "HeaderId",
principalTable: "ReceiptHeader",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ShipmentDetail_ShipmentHeader_HeaderId",
table: "ShipmentDetail",
column: "HeaderId",
principalTable: "ShipmentHeader",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskDetail_TaskHeader_HeaderId",
table: "TaskDetail",
column: "HeaderId",
principalTable: "TaskHeader",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,75 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace HHWMS.Web.Migrations
{
public partial class updatebillmodel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ReceiptDetail_ReceiptHeader_ReceiptHeaderID",
table: "ReceiptDetail");
migrationBuilder.DropForeignKey(
name: "FK_ShipmentDetail_ShipmentHeader_ShipmentHeaderID",
table: "ShipmentDetail");
migrationBuilder.DropIndex(
name: "IX_ShipmentDetail_ShipmentHeaderID",
table: "ShipmentDetail");
migrationBuilder.DropIndex(
name: "IX_ReceiptDetail_ReceiptHeaderID",
table: "ReceiptDetail");
migrationBuilder.DropColumn(
name: "ShipmentHeaderID",
table: "ShipmentDetail");
migrationBuilder.DropColumn(
name: "ReceiptHeaderID",
table: "ReceiptDetail");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ShipmentHeaderID",
table: "ShipmentDetail",
type: "int",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "ReceiptHeaderID",
table: "ReceiptDetail",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_ShipmentDetail_ShipmentHeaderID",
table: "ShipmentDetail",
column: "ShipmentHeaderID");
migrationBuilder.CreateIndex(
name: "IX_ReceiptDetail_ReceiptHeaderID",
table: "ReceiptDetail",
column: "ReceiptHeaderID");
migrationBuilder.AddForeignKey(
name: "FK_ReceiptDetail_ReceiptHeader_ReceiptHeaderID",
table: "ReceiptDetail",
column: "ReceiptHeaderID",
principalTable: "ReceiptHeader",
principalColumn: "ID");
migrationBuilder.AddForeignKey(
name: "FK_ShipmentDetail_ShipmentHeader_ShipmentHeaderID",
table: "ShipmentDetail",
column: "ShipmentHeaderID",
principalTable: "ShipmentHeader",
principalColumn: "ID");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace HHWMS.Web.Migrations
{
public partial class addupdateversion : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "UpdateVersion",
table: "ShipmentHeader",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "UpdateVersion",
table: "ShipmentDetail",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "UpdateVersion",
table: "ReceiptHeader",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "UpdateVersion",
table: "ReceiptDetail",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "UpdateVersion",
table: "Inventory",
type: "int",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UpdateVersion",
table: "ShipmentHeader");
migrationBuilder.DropColumn(
name: "UpdateVersion",
table: "ShipmentDetail");
migrationBuilder.DropColumn(
name: "UpdateVersion",
table: "ReceiptHeader");
migrationBuilder.DropColumn(
name: "UpdateVersion",
table: "ReceiptDetail");
migrationBuilder.DropColumn(
name: "UpdateVersion",
table: "Inventory");
}
}
}
File diff suppressed because it is too large. Load diff
+691
View File
@@ -0,0 +1,691 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace HHWMS.Web.Migrations
{
public partial class wms3 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ZoneCode",
table: "TaskHeaderHistory");
migrationBuilder.DropColumn(
name: "ZoneCode",
table: "TaskHeader");
migrationBuilder.DropColumn(
name: "QRCode",
table: "Material");
migrationBuilder.DropColumn(
name: "SourceCode",
table: "Material");
migrationBuilder.DropColumn(
name: "UniqueCode",
table: "Material");
migrationBuilder.DropColumn(
name: "ZoneCode",
table: "Location");
migrationBuilder.DropColumn(
name: "ZoneCode",
table: "Inventory");
migrationBuilder.AddColumn<int>(
name: "ZoneId",
table: "TaskHeaderHistory",
type: "int",
nullable: false,
defaultValue: 0,
comment: "库区");
migrationBuilder.AddColumn<int>(
name: "ZoneId",
table: "TaskHeader",
type: "int",
nullable: false,
defaultValue: 0,
comment: "库区");
migrationBuilder.AlterColumn<string>(
name: "SupplierCode",
table: "Material",
type: "varchar(100)",
maxLength: 100,
nullable: true,
comment: "供应商",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "供应商")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<decimal>(
name: "Qty",
table: "Material",
type: "decimal(12,4)",
nullable: false,
defaultValue: 0m,
comment: "数量",
oldClrType: typeof(decimal),
oldType: "decimal(12,4)",
oldNullable: true,
oldComment: "数量");
migrationBuilder.UpdateData(
table: "Material",
keyColumn: "MaterialType",
keyValue: null,
column: "MaterialType",
value: "");
migrationBuilder.AlterColumn<string>(
name: "MaterialType",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: false,
comment: "物料类型",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "物料类型")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.UpdateData(
table: "Material",
keyColumn: "MaterialCode",
keyValue: null,
column: "MaterialCode",
value: "");
migrationBuilder.AlterColumn<string>(
name: "MaterialCode",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: false,
comment: "物料编码",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "物料编码")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<short>(
name: "Type",
table: "Location",
type: "smallint",
nullable: false,
comment: "库位类型",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldComment: "库位类型")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<short>(
name: "Status",
table: "Location",
type: "smallint",
nullable: false,
defaultValue: (short)0,
comment: "是否锁定",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "库位状态")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<short>(
name: "RowFlag",
table: "Location",
type: "smallint",
nullable: false,
defaultValue: (short)0,
comment: "内外标识,0:外仓位,1:里仓位",
oldClrType: typeof(short),
oldType: "smallint",
oldNullable: true,
oldComment: "内外标识,0:外仓位,1:里仓位");
migrationBuilder.AddColumn<string>(
name: "ContainerStatus",
table: "Location",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "库位状态")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<int>(
name: "ZoneId",
table: "Location",
type: "int",
nullable: false,
defaultValue: 0,
comment: "库位编码");
migrationBuilder.AlterColumn<string>(
name: "SupplierCode",
table: "InventoryTransaction",
type: "varchar(100)",
maxLength: 100,
nullable: true,
comment: "供应商",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "供应商")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<short>(
name: "TaskStatus",
table: "Inventory",
type: "smallint",
nullable: false,
defaultValue: (short)0,
comment: "任务状态",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "任务状态")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "SupplierCode",
table: "Inventory",
type: "varchar(100)",
maxLength: 100,
nullable: true,
comment: "供应商",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldNullable: true,
oldComment: "供应商")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<int>(
name: "ZoneId",
table: "Inventory",
type: "int",
nullable: false,
defaultValue: 0,
comment: "库区");
migrationBuilder.AddColumn<int>(
name: "ZoneId",
table: "Container",
type: "int",
nullable: false,
defaultValue: 0,
comment: "库区");
migrationBuilder.CreateTable(
name: "Customer",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Code = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "编码")
.Annotation("MySql:CharSet", "utf8mb4"),
Type = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "类型")
.Annotation("MySql:CharSet", "utf8mb4"),
Name = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "名称")
.Annotation("MySql:CharSet", "utf8mb4"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_Customer", x => x.ID);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "LocationZone",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
ZoneCode = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "库区")
.Annotation("MySql:CharSet", "utf8mb4"),
Name = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "名称")
.Annotation("MySql:CharSet", "utf8mb4"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_LocationZone", x => x.ID);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "MaterialProcess",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
MaterialCode = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "物料编码")
.Annotation("MySql:CharSet", "utf8mb4"),
ProcessCode = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "工序编码")
.Annotation("MySql:CharSet", "utf8mb4"),
ProcessName = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false, comment: "工序名称")
.Annotation("MySql:CharSet", "utf8mb4"),
ProcessOrder = table.Column<int>(type: "int", nullable: false, comment: "工序顺序"),
Weight = table.Column<int>(type: "int", nullable: false, comment: "毛重"),
Description = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true, comment: "工序描述")
.Annotation("MySql:CharSet", "utf8mb4"),
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false, comment: "是否启用"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_MaterialProcess", x => x.ID);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "ProcessConfig",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Code = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "工序编码")
.Annotation("MySql:CharSet", "utf8mb4"),
Name = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "工序名称")
.Annotation("MySql:CharSet", "utf8mb4"),
Zone = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "存放区域")
.Annotation("MySql:CharSet", "utf8mb4"),
Port = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false, comment: "出口")
.Annotation("MySql:CharSet", "utf8mb4"),
Spare1 = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "备用1")
.Annotation("MySql:CharSet", "utf8mb4"),
Spare2 = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "备用2")
.Annotation("MySql:CharSet", "utf8mb4"),
Spare3 = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "备用3")
.Annotation("MySql:CharSet", "utf8mb4"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_ProcessConfig", x => x.ID);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_TaskHeaderHistory_ZoneId",
table: "TaskHeaderHistory",
column: "ZoneId");
migrationBuilder.CreateIndex(
name: "IX_TaskHeader_ZoneId",
table: "TaskHeader",
column: "ZoneId");
migrationBuilder.CreateIndex(
name: "IX_Location_ZoneId",
table: "Location",
column: "ZoneId");
migrationBuilder.CreateIndex(
name: "IX_Inventory_ZoneId",
table: "Inventory",
column: "ZoneId");
migrationBuilder.CreateIndex(
name: "IX_Container_ZoneId",
table: "Container",
column: "ZoneId");
migrationBuilder.AddForeignKey(
name: "FK_Container_LocationZone_ZoneId",
table: "Container",
column: "ZoneId",
principalTable: "LocationZone",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Inventory_LocationZone_ZoneId",
table: "Inventory",
column: "ZoneId",
principalTable: "LocationZone",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Location_LocationZone_ZoneId",
table: "Location",
column: "ZoneId",
principalTable: "LocationZone",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskHeader_LocationZone_ZoneId",
table: "TaskHeader",
column: "ZoneId",
principalTable: "LocationZone",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskHeaderHistory_LocationZone_ZoneId",
table: "TaskHeaderHistory",
column: "ZoneId",
principalTable: "LocationZone",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Container_LocationZone_ZoneId",
table: "Container");
migrationBuilder.DropForeignKey(
name: "FK_Inventory_LocationZone_ZoneId",
table: "Inventory");
migrationBuilder.DropForeignKey(
name: "FK_Location_LocationZone_ZoneId",
table: "Location");
migrationBuilder.DropForeignKey(
name: "FK_TaskHeader_LocationZone_ZoneId",
table: "TaskHeader");
migrationBuilder.DropForeignKey(
name: "FK_TaskHeaderHistory_LocationZone_ZoneId",
table: "TaskHeaderHistory");
migrationBuilder.DropTable(
name: "Customer");
migrationBuilder.DropTable(
name: "LocationZone");
migrationBuilder.DropTable(
name: "MaterialProcess");
migrationBuilder.DropTable(
name: "ProcessConfig");
migrationBuilder.DropIndex(
name: "IX_TaskHeaderHistory_ZoneId",
table: "TaskHeaderHistory");
migrationBuilder.DropIndex(
name: "IX_TaskHeader_ZoneId",
table: "TaskHeader");
migrationBuilder.DropIndex(
name: "IX_Location_ZoneId",
table: "Location");
migrationBuilder.DropIndex(
name: "IX_Inventory_ZoneId",
table: "Inventory");
migrationBuilder.DropIndex(
name: "IX_Container_ZoneId",
table: "Container");
migrationBuilder.DropColumn(
name: "ZoneId",
table: "TaskHeaderHistory");
migrationBuilder.DropColumn(
name: "ZoneId",
table: "TaskHeader");
migrationBuilder.DropColumn(
name: "ContainerStatus",
table: "Location");
migrationBuilder.DropColumn(
name: "ZoneId",
table: "Location");
migrationBuilder.DropColumn(
name: "ZoneId",
table: "Inventory");
migrationBuilder.DropColumn(
name: "ZoneId",
table: "Container");
migrationBuilder.AddColumn<string>(
name: "ZoneCode",
table: "TaskHeaderHistory",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "库区")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "ZoneCode",
table: "TaskHeader",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "库区")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "SupplierCode",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "供应商",
oldClrType: typeof(string),
oldType: "varchar(100)",
oldMaxLength: 100,
oldNullable: true,
oldComment: "供应商")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<decimal>(
name: "Qty",
table: "Material",
type: "decimal(12,4)",
nullable: true,
comment: "数量",
oldClrType: typeof(decimal),
oldType: "decimal(12,4)",
oldComment: "数量");
migrationBuilder.AlterColumn<string>(
name: "MaterialType",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "物料类型",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldComment: "物料类型")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "MaterialCode",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "物料编码",
oldClrType: typeof(string),
oldType: "varchar(50)",
oldMaxLength: 50,
oldComment: "物料编码")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "QRCode",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "二维码")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "SourceCode",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "上游单号")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "UniqueCode",
table: "Material",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "唯一码")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "Type",
table: "Location",
type: "varchar(50)",
maxLength: 50,
nullable: false,
comment: "库位类型",
oldClrType: typeof(short),
oldType: "smallint",
oldComment: "库位类型")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "Status",
table: "Location",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "库位状态",
oldClrType: typeof(short),
oldType: "smallint",
oldComment: "是否锁定")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<short>(
name: "RowFlag",
table: "Location",
type: "smallint",
nullable: true,
comment: "内外标识,0:外仓位,1:里仓位",
oldClrType: typeof(short),
oldType: "smallint",
oldComment: "内外标识,0:外仓位,1:里仓位");
migrationBuilder.AddColumn<string>(
name: "ZoneCode",
table: "Location",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "库区")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "SupplierCode",
table: "InventoryTransaction",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "供应商",
oldClrType: typeof(string),
oldType: "varchar(100)",
oldMaxLength: 100,
oldNullable: true,
oldComment: "供应商")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "TaskStatus",
table: "Inventory",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "任务状态",
oldClrType: typeof(short),
oldType: "smallint",
oldComment: "任务状态")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AlterColumn<string>(
name: "SupplierCode",
table: "Inventory",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "供应商",
oldClrType: typeof(string),
oldType: "varchar(100)",
oldMaxLength: 100,
oldNullable: true,
oldComment: "供应商")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "ZoneCode",
table: "Inventory",
type: "varchar(50)",
maxLength: 50,
nullable: true,
comment: "库区")
.Annotation("MySql:CharSet", "utf8mb4");
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace HHWMS.Web.Migrations
{
public partial class mqtt4 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ParsedData",
table: "MqttMessageRecord",
type: "longtext",
nullable: true,
comment: "解析后数据")
.Annotation("MySql:CharSet", "utf8mb4");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ParsedData",
table: "MqttMessageRecord");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,153 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace HHWMS.Web.Migrations
{
public partial class device_data_tables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DeviceAlarmRecord",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
DeviceId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false, comment: "设备唯一标识")
.Annotation("MySql:CharSet", "utf8mb4"),
AlarmCode = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true, comment: "告警代码")
.Annotation("MySql:CharSet", "utf8mb4"),
AlarmMessage = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true, comment: "告警内容")
.Annotation("MySql:CharSet", "utf8mb4"),
StartTime = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "告警开始时间"),
EndTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "告警恢复时间"),
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false, comment: "是否仍在告警"),
LastSeenTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后出现时间"),
RepeatCount = table.Column<int>(type: "int", nullable: false, comment: "重复出现次数"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceAlarmRecord", x => x.ID);
},
comment: "设备告警记录")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "DeviceCurrentState",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
DeviceId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false, comment: "设备唯一标识")
.Annotation("MySql:CharSet", "utf8mb4"),
DeviceName = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true, comment: "设备显示名称")
.Annotation("MySql:CharSet", "utf8mb4"),
DeviceType = table.Column<string>(type: "varchar(30)", maxLength: 30, nullable: true, comment: "设备类型")
.Annotation("MySql:CharSet", "utf8mb4"),
Status = table.Column<string>(type: "varchar(30)", maxLength: 30, nullable: true, comment: "当前状态")
.Annotation("MySql:CharSet", "utf8mb4"),
LastPayloadTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后设备数据时间"),
LastUpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后状态更新时间"),
AlarmSummary = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true, comment: "当前告警摘要")
.Annotation("MySql:CharSet", "utf8mb4"),
RealtimeJson = table.Column<string>(type: "longtext", nullable: true, comment: "清洗后的实时数据")
.Annotation("MySql:CharSet", "utf8mb4"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceCurrentState", x => x.ID);
},
comment: "设备当前状态")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "DeviceMetricTrendPoint",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
DeviceId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false, comment: "设备唯一标识")
.Annotation("MySql:CharSet", "utf8mb4"),
MetricName = table.Column<string>(type: "varchar(60)", maxLength: 60, nullable: false, comment: "指标名称")
.Annotation("MySql:CharSet", "utf8mb4"),
BucketTime = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "聚合时间桶"),
AvgValue = table.Column<decimal>(type: "decimal(18,4)", nullable: false, comment: "平均值"),
MaxValue = table.Column<decimal>(type: "decimal(18,4)", nullable: false, comment: "最大值"),
MinValue = table.Column<decimal>(type: "decimal(18,4)", nullable: false, comment: "最小值"),
SampleCount = table.Column<int>(type: "int", nullable: false, comment: "样本数"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceMetricTrendPoint", x => x.ID);
},
comment: "设备指标趋势聚合点")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "DeviceProductionDaily",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
DeviceId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false, comment: "设备唯一标识")
.Annotation("MySql:CharSet", "utf8mb4"),
ProductionDate = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "生产日期"),
StartCounter = table.Column<int>(type: "int", nullable: false, comment: "当日开始累计值"),
EndCounter = table.Column<int>(type: "int", nullable: false, comment: "当日结束累计值"),
ProduceCount = table.Column<int>(type: "int", nullable: false, comment: "当日产量"),
RuntimeMinutes = table.Column<int>(type: "int", nullable: false, comment: "运行分钟数"),
CuttimeMinutes = table.Column<int>(type: "int", nullable: false, comment: "加工分钟数"),
AlarmMinutes = table.Column<int>(type: "int", nullable: false, comment: "报警分钟数"),
OfflineMinutes = table.Column<int>(type: "int", nullable: false, comment: "离线分钟数"),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
CreateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4"),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: ""),
UpdateBy = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true, comment: "")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceProductionDaily", x => x.ID);
},
comment: "设备日产能汇总")
.Annotation("MySql:CharSet", "utf8mb4");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DeviceAlarmRecord");
migrationBuilder.DropTable(
name: "DeviceCurrentState");
migrationBuilder.DropTable(
name: "DeviceMetricTrendPoint");
migrationBuilder.DropTable(
name: "DeviceProductionDaily");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web.Models
{
[Table("DeviceAlarmRecord")]
[Display(Name = "DeviceAlarmRecord", Description = "设备告警记录")]
public class DeviceAlarmRecord : BasePoco
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new int ID { get; set; }
[Display(Name = "DeviceAlarmRecord.DeviceId", Description = "设备唯一标识")]
[StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")]
[Required(ErrorMessage = "Validate.{0}required")]
public string DeviceId { get; set; }
[Display(Name = "DeviceAlarmRecord.AlarmCode", Description = "告警代码")]
[StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")]
public string AlarmCode { get; set; }
[Display(Name = "DeviceAlarmRecord.AlarmMessage", Description = "告警内容")]
[StringLength(500, ErrorMessage = "Validate.{0}stringmax{1}")]
public string AlarmMessage { get; set; }
[Display(Name = "DeviceAlarmRecord.StartTime", Description = "告警开始时间")]
public DateTime StartTime { get; set; }
[Display(Name = "DeviceAlarmRecord.EndTime", Description = "告警恢复时间")]
public DateTime? EndTime { get; set; }
[Display(Name = "DeviceAlarmRecord.IsActive", Description = "是否仍在告警")]
public bool IsActive { get; set; }
[Display(Name = "DeviceAlarmRecord.LastSeenTime", Description = "最后出现时间")]
public DateTime? LastSeenTime { get; set; }
[Display(Name = "DeviceAlarmRecord.RepeatCount", Description = "重复出现次数")]
public int RepeatCount { get; set; }
}
}
@@ -0,0 +1,46 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web.Models
{
[Table("DeviceCurrentState")]
[Display(Name = "DeviceCurrentState", Description = "设备当前状态")]
public class DeviceCurrentState : BasePoco
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new int ID { get; set; }
[Display(Name = "DeviceCurrentState.DeviceId", Description = "设备唯一标识")]
[StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")]
[Required(ErrorMessage = "Validate.{0}required")]
public string DeviceId { get; set; }
[Display(Name = "DeviceCurrentState.DeviceName", Description = "设备显示名称")]
[StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")]
public string DeviceName { get; set; }
[Display(Name = "DeviceCurrentState.DeviceType", Description = "设备类型")]
[StringLength(30, ErrorMessage = "Validate.{0}stringmax{1}")]
public string DeviceType { get; set; }
[Display(Name = "DeviceCurrentState.Status", Description = "当前状态")]
[StringLength(30, ErrorMessage = "Validate.{0}stringmax{1}")]
public string Status { get; set; }
[Display(Name = "DeviceCurrentState.LastPayloadTime", Description = "最后设备数据时间")]
public DateTime? LastPayloadTime { get; set; }
[Display(Name = "DeviceCurrentState.LastUpdateTime", Description = "最后状态更新时间")]
public DateTime? LastUpdateTime { get; set; }
[Display(Name = "DeviceCurrentState.AlarmSummary", Description = "当前告警摘要")]
[StringLength(500, ErrorMessage = "Validate.{0}stringmax{1}")]
public string AlarmSummary { get; set; }
[Display(Name = "DeviceCurrentState.RealtimeJson", Description = "清洗后的实时数据")]
public string RealtimeJson { get; set; }
}
}
@@ -0,0 +1,44 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web.Models
{
[Table("DeviceMetricTrendPoint")]
[Display(Name = "DeviceMetricTrendPoint", Description = "设备指标趋势聚合点")]
public class DeviceMetricTrendPoint : BasePoco
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new int ID { get; set; }
[Display(Name = "DeviceMetricTrendPoint.DeviceId", Description = "设备唯一标识")]
[StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")]
[Required(ErrorMessage = "Validate.{0}required")]
public string DeviceId { get; set; }
[Display(Name = "DeviceMetricTrendPoint.MetricName", Description = "指标名称")]
[StringLength(60, ErrorMessage = "Validate.{0}stringmax{1}")]
[Required(ErrorMessage = "Validate.{0}required")]
public string MetricName { get; set; }
[Display(Name = "DeviceMetricTrendPoint.BucketTime", Description = "聚合时间桶")]
public DateTime BucketTime { get; set; }
[Display(Name = "DeviceMetricTrendPoint.AvgValue", Description = "平均值")]
[Column(TypeName = "decimal(18,4)")]
public decimal AvgValue { get; set; }
[Display(Name = "DeviceMetricTrendPoint.MaxValue", Description = "最大值")]
[Column(TypeName = "decimal(18,4)")]
public decimal MaxValue { get; set; }
[Display(Name = "DeviceMetricTrendPoint.MinValue", Description = "最小值")]
[Column(TypeName = "decimal(18,4)")]
public decimal MinValue { get; set; }
[Display(Name = "DeviceMetricTrendPoint.SampleCount", Description = "样本数")]
public int SampleCount { get; set; }
}
}
@@ -0,0 +1,45 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web.Models
{
[Table("DeviceProductionDaily")]
[Display(Name = "DeviceProductionDaily", Description = "设备日产能汇总")]
public class DeviceProductionDaily : BasePoco
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new int ID { get; set; }
[Display(Name = "DeviceProductionDaily.DeviceId", Description = "设备唯一标识")]
[StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")]
[Required(ErrorMessage = "Validate.{0}required")]
public string DeviceId { get; set; }
[Display(Name = "DeviceProductionDaily.ProductionDate", Description = "生产日期")]
public DateTime ProductionDate { get; set; }
[Display(Name = "DeviceProductionDaily.StartCounter", Description = "当日开始累计值")]
public int StartCounter { get; set; }
[Display(Name = "DeviceProductionDaily.EndCounter", Description = "当日结束累计值")]
public int EndCounter { get; set; }
[Display(Name = "DeviceProductionDaily.ProduceCount", Description = "当日产量")]
public int ProduceCount { get; set; }
[Display(Name = "DeviceProductionDaily.RuntimeMinutes", Description = "运行分钟数")]
public int RuntimeMinutes { get; set; }
[Display(Name = "DeviceProductionDaily.CuttimeMinutes", Description = "加工分钟数")]
public int CuttimeMinutes { get; set; }
[Display(Name = "DeviceProductionDaily.AlarmMinutes", Description = "报警分钟数")]
public int AlarmMinutes { get; set; }
[Display(Name = "DeviceProductionDaily.OfflineMinutes", Description = "离线分钟数")]
public int OfflineMinutes { get; set; }
}
}
+18
View File
@@ -29,6 +29,17 @@ builder.Services.AddRazorPages();
builder.Services.AddDistributedMemoryCache(); builder.Services.AddDistributedMemoryCache();
builder.Services.AddWtmSession(3600, builder.Configuration); builder.Services.AddWtmSession(3600, builder.Configuration);
builder.Services.AddWtmCrossDomain(builder.Configuration); builder.Services.AddWtmCrossDomain(builder.Configuration);
builder.Services.AddCors(options =>
{
options.AddPolicy("DashboardCors", policy =>
{
policy
.WithOrigins("http://localhost:5173", "http://127.0.0.1:5173")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.AddWtmAuthentication(builder.Configuration); builder.Services.AddWtmAuthentication(builder.Configuration);
builder.Services.AddWtmHttpClient(builder.Configuration); builder.Services.AddWtmHttpClient(builder.Configuration);
builder.Services.AddWtmSwagger(); builder.Services.AddWtmSwagger();
@@ -64,7 +75,12 @@ builder.Services.AddSignalR()
builder.Services.AddSingleton<StockTicker>(); builder.Services.AddSingleton<StockTicker>();
builder.Services.AddSingleton<HHWMS.Web.Services.MqttRuntimeState>();
builder.Services.AddSingleton<HHWMS.Web.Services.MqttRuntimeStateRefresher>();
builder.Services.AddSingleton<HHWMS.Web.Services.MqttMessageChannel>(); builder.Services.AddSingleton<HHWMS.Web.Services.MqttMessageChannel>();
builder.Services.AddSingleton<HHWMS.Web.Services.DeviceData.PowerCabinetMessageProcessor>();
builder.Services.AddSingleton<HHWMS.Web.Services.DeviceData.CncMessageProcessor>();
builder.Services.AddSingleton<HHWMS.Web.Services.DeviceData.DashboardPushService>();
builder.Services.AddHostedService<HHWMS.Web.Services.MqttService>(); builder.Services.AddHostedService<HHWMS.Web.Services.MqttService>();
@@ -78,6 +94,7 @@ app.UseExceptionHandler(config.CurrentValue.ErrorHandler);
app.UseStaticFiles(); app.UseStaticFiles();
app.UseWtmStaticFiles(); app.UseWtmStaticFiles();
app.UseRouting(); app.UseRouting();
app.UseCors("DashboardCors");
app.UseWtmMultiLanguages(); app.UseWtmMultiLanguages();
app.UseWtmCrossDomain(); app.UseWtmCrossDomain();
app.UseAuthentication(); app.UseAuthentication();
@@ -101,6 +118,7 @@ app.UseEndpoints(endpoints =>
name: "default", name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"); pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapHub<StockTickerHub>("/stocks"); endpoints.MapHub<StockTickerHub>("/stocks");
endpoints.MapHub<DashboardHub>("/dashboardHub").RequireCors("DashboardCors");
}); });
app.UseWtmContext(); app.UseWtmContext();
@@ -0,0 +1,461 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using HHWMS.Web.Models;
namespace HHWMS.Web.Services.DeviceData
{
public class CncMessageProcessor
{
private const decimal SpindleSpeedDeadband = 50m;
private const decimal FeedRateDeadband = 20m;
private static readonly TimeSpan MaxDeadbandSilence = TimeSpan.FromMinutes(1);
public ProcessingResult Process(MqttMessageRecord message, IUnitWork unitwork)
{
if (string.IsNullOrWhiteSpace(message?.Payload))
{
return ProcessingResult.NotHandled();
}
using var document = JsonDocument.Parse(message.Payload);
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || !LooksLikeCncPayload(root))
{
return ProcessingResult.NotHandled();
}
var payloadTime = ReadTimestamp(root) ?? (message.ReceiveTime == default ? DateTime.Now : message.ReceiveTime);
var statusInfo = root.TryGetProperty("statusInfo", out var statusElement) && statusElement.ValueKind == JsonValueKind.Object
? statusElement
: default;
var speedFeed = root.TryGetProperty("spindleSpeedAndFeedRate", out var speedFeedElement) && speedFeedElement.ValueKind == JsonValueKind.Object
? speedFeedElement
: default;
var programCurrent = root.TryGetProperty("programCurrent", out var programElement) && programElement.ValueKind == JsonValueKind.Object
? programElement
: default;
var deviceId = ResolveDeviceId(root, message.Topic);
var alarmMessages = ReadAlarmMessages(root);
var alarmStatus = ReadInt(root, "alarmStatus") ?? 0;
var emergency = ReadInt(statusInfo, "Emergency") ?? 0;
var alarmFlag = ReadInt(statusInfo, "Alarm") ?? 0;
var status = ResolveStatus(statusInfo, alarmStatus, alarmFlag, emergency);
var programName = ReadString(programCurrent, "name");
var programNumber = ReadInt(programCurrent, "number");
var currentProduceCount = ReadInt(root, "currentProduceCount");
var spindleSpeed = ReadDecimal(speedFeed, "speed");
var feedRate = ReadDecimal(speedFeed, "feedRate");
var setSpindleSpeed = ReadDecimal(root, "setSpindleSpeed");
var setFeedRate = ReadDecimal(root, "setFeedRate");
var runtimeMinutes = ParseFanucTimeMinutes(ReadString(root, "runtime"));
var cuttimeMinutes = ParseFanucTimeMinutes(ReadString(root, "cuttime"));
var cycletimeMinutes = ParseFanucTimeMinutes(ReadString(root, "cycletime"));
var workMode = ReadString(statusInfo, "WorkMode");
var runStatus = ReadString(statusInfo, "RunStatus");
var todayProduce = GetTodayProduce(unitwork, deviceId, payloadTime, currentProduceCount);
var realtime = new
{
currentProduceCount,
todayProduce,
programName,
programNumber,
workMode,
runStatus,
status,
alarmMessages,
runtimeMinutes,
cuttimeMinutes,
cycletimeMinutes,
spindleSpeed,
feedRate,
setSpindleSpeed,
setFeedRate,
cncType = ReadNestedString(root, "sysInfo", "cncType"),
axes = ReadNestedInt(root, "sysInfo", "axes"),
payloadTime
};
var realtimeJson = JsonSerializer.Serialize(realtime);
var currentState = unitwork.Find<DeviceCurrentState>(x => x.DeviceId == deviceId).FirstOrDefault();
if (IsDeadbandHit(currentState, status, programName, currentProduceCount, alarmMessages, spindleSpeed, feedRate))
{
return new ProcessingResult
{
Handled = true,
Updated = false,
DeviceId = deviceId,
DeviceType = "cnc",
Status = status,
PayloadTime = payloadTime,
Message = "CNC ignored by deadband",
ParsedData = realtimeJson
};
}
UpsertCurrentState(unitwork, currentState, deviceId, status, payloadTime, alarmMessages, realtimeJson);
UpsertTrendPoint(unitwork, deviceId, "cncProduceCount", payloadTime, currentProduceCount);
UpsertTrendPoint(unitwork, deviceId, "spindleSpeed", payloadTime, spindleSpeed);
UpsertTrendPoint(unitwork, deviceId, "feedRate", payloadTime, feedRate);
UpsertTrendPoint(unitwork, deviceId, "runtimeMinutes", payloadTime, runtimeMinutes);
UpsertTrendPoint(unitwork, deviceId, "cuttimeMinutes", payloadTime, cuttimeMinutes);
UpsertProductionDaily(unitwork, deviceId, payloadTime, currentProduceCount, runtimeMinutes, cuttimeMinutes, status);
SyncCncAlarm(unitwork, deviceId, alarmMessages, payloadTime);
return new ProcessingResult
{
Handled = true,
Updated = true,
DeviceId = deviceId,
DeviceType = "cnc",
Status = status,
PayloadTime = payloadTime,
Message = "CNC state updated",
ParsedData = realtimeJson
};
}
private static bool LooksLikeCncPayload(JsonElement root)
{
return root.TryGetProperty("statusInfo", out _)
|| root.TryGetProperty("programCurrent", out _)
|| root.TryGetProperty("currentProduceCount", out _)
|| root.TryGetProperty("spindleSpeedAndFeedRate", out _);
}
private static string ResolveDeviceId(JsonElement root, string topic)
{
var explicitId = ReadString(root, "deviceId")
?? ReadString(root, "device_id")
?? ReadString(root, "client_id")
?? ReadString(root, "machineId")
?? ReadString(root, "machine_id");
if (!string.IsNullOrWhiteSpace(explicitId))
{
return explicitId.StartsWith("CNC-", StringComparison.OrdinalIgnoreCase) ? explicitId : $"CNC-{NormalizeDeviceCode(explicitId)}";
}
var topicCode = Regex.Match(topic ?? string.Empty, @"(?:CNC[-_/]?)?(\d{1,3})(?!\d)", RegexOptions.IgnoreCase);
if (topicCode.Success)
{
return $"CNC-{NormalizeDeviceCode(topicCode.Groups[1].Value)}";
}
return string.IsNullOrWhiteSpace(topic) ? "CNC-UNKNOWN" : $"cnc:{topic}";
}
private static string NormalizeDeviceCode(string raw)
{
var digits = Regex.Match(raw ?? string.Empty, @"\d{1,3}");
return digits.Success ? int.Parse(digits.Value, CultureInfo.InvariantCulture).ToString("D3", CultureInfo.InvariantCulture) : raw;
}
private static string ResolveStatus(JsonElement statusInfo, int alarmStatus, int alarmFlag, int emergency)
{
if (alarmStatus > 0 || alarmFlag > 0 || emergency > 0)
{
return "alarm";
}
var motion = ReadInt(statusInfo, "Motion") ?? 0;
var mstb = ReadInt(statusInfo, "MSTB") ?? 0;
var runStatus = ReadString(statusInfo, "RunStatus");
if ((runStatus == "3" && motion == 1) || runStatus == "2" || mstb == 1)
{
return "running";
}
return "idle";
}
private static string[] ReadAlarmMessages(JsonElement root)
{
if (!root.TryGetProperty("alarm", out var alarm) || alarm.ValueKind != JsonValueKind.Array)
{
return Array.Empty<string>();
}
return alarm.EnumerateArray()
.Select(x => x.ValueKind == JsonValueKind.String ? x.GetString() : x.ToString())
.Where(x => string.IsNullOrWhiteSpace(x) == false)
.ToArray();
}
private static void UpsertCurrentState(IUnitWork unitwork, DeviceCurrentState currentState, string deviceId, string status, DateTime payloadTime, string[] alarmMessages, string realtimeJson)
{
var alarmSummary = alarmMessages.Length > 0 ? string.Join(";", alarmMessages) : null;
if (currentState == null)
{
unitwork.Add(new DeviceCurrentState
{
DeviceId = deviceId,
DeviceName = deviceId,
DeviceType = "cnc",
Status = status,
LastPayloadTime = payloadTime,
LastUpdateTime = DateTime.Now,
AlarmSummary = alarmSummary,
RealtimeJson = realtimeJson
});
return;
}
currentState.DeviceName = string.IsNullOrWhiteSpace(currentState.DeviceName) ? deviceId : currentState.DeviceName;
currentState.DeviceType = "cnc";
currentState.Status = status;
currentState.LastPayloadTime = payloadTime;
currentState.LastUpdateTime = DateTime.Now;
currentState.AlarmSummary = alarmSummary;
currentState.RealtimeJson = realtimeJson;
unitwork.Update(currentState);
}
private static void UpsertTrendPoint(IUnitWork unitwork, string deviceId, string metricName, DateTime payloadTime, int? value)
{
if (value != null)
{
UpsertTrendPoint(unitwork, deviceId, metricName, payloadTime, (decimal)value.Value);
}
}
private static void UpsertTrendPoint(IUnitWork unitwork, string deviceId, string metricName, DateTime payloadTime, decimal? value)
{
if (value == null)
{
return;
}
var bucketTime = new DateTime(payloadTime.Year, payloadTime.Month, payloadTime.Day, payloadTime.Hour, payloadTime.Minute, 0);
var point = unitwork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == deviceId && x.MetricName == metricName && x.BucketTime == bucketTime).FirstOrDefault();
if (point == null)
{
unitwork.Add(new DeviceMetricTrendPoint
{
DeviceId = deviceId,
MetricName = metricName,
BucketTime = bucketTime,
AvgValue = value.Value,
MaxValue = value.Value,
MinValue = value.Value,
SampleCount = 1
});
return;
}
var count = Math.Max(point.SampleCount, 1);
point.AvgValue = ((point.AvgValue * count) + value.Value) / (count + 1);
point.MaxValue = Math.Max(point.MaxValue, value.Value);
point.MinValue = Math.Min(point.MinValue, value.Value);
point.SampleCount = count + 1;
unitwork.Update(point);
}
private static void UpsertProductionDaily(IUnitWork unitwork, string deviceId, DateTime payloadTime, int? currentProduceCount, decimal? runtimeMinutes, decimal? cuttimeMinutes, string status)
{
if (currentProduceCount == null)
{
return;
}
var productionDate = payloadTime.Date;
var daily = unitwork.Find<DeviceProductionDaily>(x => x.DeviceId == deviceId && x.ProductionDate == productionDate).FirstOrDefault();
if (daily == null)
{
unitwork.Add(new DeviceProductionDaily
{
DeviceId = deviceId,
ProductionDate = productionDate,
StartCounter = currentProduceCount.Value,
EndCounter = currentProduceCount.Value,
ProduceCount = 0,
RuntimeMinutes = ToIntMinutes(runtimeMinutes),
CuttimeMinutes = ToIntMinutes(cuttimeMinutes),
AlarmMinutes = status == "alarm" ? 1 : 0,
OfflineMinutes = 0
});
return;
}
daily.EndCounter = currentProduceCount.Value;
daily.ProduceCount = Math.Max(0, daily.EndCounter - daily.StartCounter);
daily.RuntimeMinutes = Math.Max(daily.RuntimeMinutes, ToIntMinutes(runtimeMinutes));
daily.CuttimeMinutes = Math.Max(daily.CuttimeMinutes, ToIntMinutes(cuttimeMinutes));
unitwork.Update(daily);
}
private static int? GetTodayProduce(IUnitWork unitwork, string deviceId, DateTime payloadTime, int? currentProduceCount)
{
if (currentProduceCount == null)
{
return null;
}
var productionDate = payloadTime.Date;
var daily = unitwork.Find<DeviceProductionDaily>(x => x.DeviceId == deviceId && x.ProductionDate == productionDate).FirstOrDefault();
return daily == null ? 0 : Math.Max(0, currentProduceCount.Value - daily.StartCounter);
}
private static void SyncCncAlarm(IUnitWork unitwork, string deviceId, string[] alarmMessages, DateTime payloadTime)
{
var activeAlarm = unitwork.Find<DeviceAlarmRecord>(x => x.DeviceId == deviceId && x.AlarmCode == "CNC_ALARM" && x.IsActive).FirstOrDefault();
if (alarmMessages.Length > 0)
{
var alarmText = string.Join(";", alarmMessages);
if (activeAlarm == null)
{
unitwork.Add(new DeviceAlarmRecord
{
DeviceId = deviceId,
AlarmCode = "CNC_ALARM",
AlarmMessage = alarmText,
StartTime = payloadTime,
LastSeenTime = payloadTime,
IsActive = true,
RepeatCount = 1
});
return;
}
activeAlarm.AlarmMessage = alarmText;
activeAlarm.LastSeenTime = payloadTime;
activeAlarm.RepeatCount += 1;
unitwork.Update(activeAlarm);
return;
}
if (activeAlarm != null)
{
activeAlarm.IsActive = false;
activeAlarm.EndTime = payloadTime;
activeAlarm.LastSeenTime = payloadTime;
unitwork.Update(activeAlarm);
}
}
private static bool IsDeadbandHit(DeviceCurrentState currentState, string nextStatus, string programName, int? produceCount, string[] alarmMessages, decimal? spindleSpeed, decimal? feedRate)
{
if (currentState == null || string.IsNullOrWhiteSpace(currentState.RealtimeJson) || currentState.Status != nextStatus)
{
return false;
}
if (currentState.LastUpdateTime != null && DateTime.Now - currentState.LastUpdateTime.Value > MaxDeadbandSilence)
{
return false;
}
using var document = JsonDocument.Parse(currentState.RealtimeJson);
var root = document.RootElement;
var oldAlarm = ReadStringArray(root, "alarmMessages");
return string.Equals(ReadString(root, "programName"), programName, StringComparison.OrdinalIgnoreCase)
&& ReadInt(root, "currentProduceCount") == produceCount
&& string.Join("|", oldAlarm) == string.Join("|", alarmMessages)
&& IsWithinDeadband(ReadDecimal(root, "spindleSpeed"), spindleSpeed, SpindleSpeedDeadband)
&& IsWithinDeadband(ReadDecimal(root, "feedRate"), feedRate, FeedRateDeadband);
}
private static bool IsWithinDeadband(decimal? oldValue, decimal? newValue, decimal threshold)
{
if (oldValue == null && newValue == null)
{
return true;
}
if (oldValue == null || newValue == null)
{
return false;
}
return Math.Abs(oldValue.Value - newValue.Value) < threshold;
}
private static DateTime? ReadTimestamp(JsonElement root)
{
var raw = ReadString(root, "timestamp");
if (DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var timestamp))
{
return timestamp;
}
return null;
}
private static decimal? ParseFanucTimeMinutes(string time)
{
if (string.IsNullOrWhiteSpace(time))
{
return null;
}
var match = Regex.Match(time, @"(\d+)\s*H\s*(\d+)\s*M\s*(\d+)\s*S", RegexOptions.IgnoreCase);
if (!match.Success)
{
return null;
}
var hours = decimal.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
var minutes = decimal.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
var seconds = decimal.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture);
return Math.Round(hours * 60 + minutes + seconds / 60, 2);
}
private static int ToIntMinutes(decimal? value)
{
return value == null ? 0 : (int)Math.Round(value.Value, MidpointRounding.AwayFromZero);
}
private static string ReadString(JsonElement element, string propertyName)
{
if (element.ValueKind == JsonValueKind.Undefined || element.ValueKind == JsonValueKind.Null)
{
return null;
}
return element.TryGetProperty(propertyName, out var property) && property.ValueKind != JsonValueKind.Null
? property.ToString()
: null;
}
private static int? ReadInt(JsonElement element, string propertyName)
{
var value = ReadDecimal(element, propertyName);
return value == null ? null : (int)value.Value;
}
private static decimal? ReadDecimal(JsonElement element, string propertyName)
{
if (element.ValueKind == JsonValueKind.Undefined || element.ValueKind == JsonValueKind.Null)
{
return null;
}
if (!element.TryGetProperty(propertyName, out var property) || property.ValueKind == JsonValueKind.Null)
{
return null;
}
if (property.ValueKind == JsonValueKind.Number && property.TryGetDecimal(out var number))
{
return number;
}
return decimal.TryParse(property.ToString(), NumberStyles.Number, CultureInfo.InvariantCulture, out var value) ? value : null;
}
private static string ReadNestedString(JsonElement root, string objectName, string propertyName)
{
return root.TryGetProperty(objectName, out var nested) && nested.ValueKind == JsonValueKind.Object ? ReadString(nested, propertyName) : null;
}
private static int? ReadNestedInt(JsonElement root, string objectName, string propertyName)
{
return root.TryGetProperty(objectName, out var nested) && nested.ValueKind == JsonValueKind.Object ? ReadInt(nested, propertyName) : null;
}
private static string[] ReadStringArray(JsonElement root, string propertyName)
{
if (!root.TryGetProperty(propertyName, out var property) || property.ValueKind != JsonValueKind.Array)
{
return Array.Empty<string>();
}
return property.EnumerateArray().Select(x => x.ToString()).ToArray();
}
}
}
@@ -0,0 +1,142 @@
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using Microsoft.AspNetCore.SignalR;
namespace HHWMS.Web.Services.DeviceData
{
public class DashboardPushService
{
private readonly IHubContext<DashboardHub> _hubContext;
public DashboardPushService(IHubContext<DashboardHub> hubContext)
{
_hubContext = hubContext;
}
public async Task PushProcessingResultAsync(ProcessingResult result, IUnitWork unitWork)
{
if (result?.Handled != true || result.Updated != true || string.IsNullOrWhiteSpace(result.DeviceId))
{
return;
}
await _hubContext.Clients.All.SendAsync("device.updated", new
{
DeviceId = result.DeviceId,
DeviceName = result.DeviceId,
DeviceType = result.DeviceType,
Status = result.Status,
LastPayloadTime = result.PayloadTime,
LastUpdateTime = DateTime.Now,
Realtime = ParseJson(result.ParsedData),
DailyProduction = BuildDailyProduction(result.DeviceId, DateTime.Today, unitWork)
});
var trendPoints = BuildTrendPoints(result, unitWork);
await _hubContext.Clients.All.SendAsync("trend.updated", new
{
deviceId = result.DeviceId,
points = trendPoints
});
var alarms = unitWork.Find<DeviceAlarmRecord>(x => x.DeviceId == result.DeviceId && x.IsActive)
.OrderByDescending(x => x.LastSeenTime ?? x.StartTime)
.Select(x => new
{
x.DeviceId,
x.AlarmCode,
x.AlarmMessage,
x.StartTime,
x.LastSeenTime,
x.RepeatCount
})
.ToList();
await _hubContext.Clients.All.SendAsync("alarm.updated", new
{
deviceId = result.DeviceId,
alarms
});
}
private static object ParseJson(string json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
return JsonSerializer.Deserialize<object>(json);
}
catch
{
return json;
}
}
private static object BuildDailyProduction(string deviceId, DateTime endDate, IUnitWork unitWork)
{
var startDate = endDate.Date.AddDays(-6);
var rows = unitWork.Find<DeviceProductionDaily>(x => x.DeviceId == deviceId && x.ProductionDate >= startDate && x.ProductionDate <= endDate.Date).ToList();
var dates = Enumerable.Range(0, 7).Select(offset => endDate.Date.AddDays(offset - 6)).ToList();
return new
{
dates = dates.Select(x => x.ToString("MM/dd")).ToArray(),
produce = dates.Select(date => rows.FirstOrDefault(x => x.ProductionDate.Date == date)?.ProduceCount ?? 0).ToArray(),
runtime = dates.Select(date =>
{
var minutes = rows.FirstOrDefault(x => x.ProductionDate.Date == date)?.RuntimeMinutes ?? 0;
return Math.Round(minutes / 60m, 2);
}).ToArray()
};
}
private static object BuildTrendPoints(ProcessingResult result, IUnitWork unitWork)
{
if (result.DeviceType == "power")
{
var startTime = DateTime.Now.AddHours(-1);
var metrics = new[] { "currentA", "currentB", "currentC", "estimatedPower" };
var windowPoints = unitWork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == result.DeviceId && x.BucketTime >= startTime && metrics.Contains(x.MetricName)).ToList();
var leadingPoints = metrics
.Select(metric => unitWork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == result.DeviceId && x.MetricName == metric && x.BucketTime < startTime)
.OrderByDescending(x => x.BucketTime)
.FirstOrDefault())
.Where(x => x != null)
.ToList();
return ToTrendPointDto(leadingPoints.Concat(windowPoints));
}
var points = unitWork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == result.DeviceId)
.OrderByDescending(x => x.BucketTime)
.Take(80)
.OrderBy(x => x.BucketTime)
.ToList();
return ToTrendPointDto(points);
}
private static object ToTrendPointDto(System.Collections.Generic.IEnumerable<DeviceMetricTrendPoint> points)
{
return points
.OrderBy(x => x.BucketTime)
.Select(x => new
{
x.DeviceId,
x.MetricName,
x.BucketTime,
x.AvgValue,
x.MaxValue,
x.MinValue,
x.SampleCount
})
.ToList();
}
}
}
@@ -0,0 +1,307 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using HHWMS.Web.Models;
namespace HHWMS.Web.Services.DeviceData
{
public class PowerCabinetMessageProcessor
{
private const decimal CurrentDeadbandAmp = 0.2m;
public ProcessingResult Process(MqttMessageRecord message, IUnitWork unitwork)
{
if (string.IsNullOrWhiteSpace(message?.Payload))
{
return ProcessingResult.NotHandled();
}
using var document = JsonDocument.Parse(message.Payload);
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("slave1", out var slave))
{
return ProcessingResult.NotHandled();
}
var deviceId = ReadString(root, "client_id");
if (string.IsNullOrWhiteSpace(deviceId))
{
deviceId = BuildDeviceIdFromTopic(message.Topic);
}
var currentA = ParseCurrent(ReadString(slave, "current1"));
var currentB = ParseCurrent(ReadString(slave, "current2"));
var currentC = ParseCurrent(ReadString(slave, "current3"));
var payloadTime = message.ReceiveTime == default ? DateTime.Now : message.ReceiveTime;
var hasInvalid = currentA == null || currentB == null || currentC == null;
var status = hasInvalid ? "alarm" : "normal";
var avgCurrent = Average(currentA, currentB, currentC);
var maxCurrent = Max(currentA, currentB, currentC);
var minCurrent = Min(currentA, currentB, currentC);
var imbalanceRate = avgCurrent > 0 && maxCurrent != null && minCurrent != null
? Math.Round(((maxCurrent.Value - minCurrent.Value) / avgCurrent.Value) * 100, 2)
: (decimal?)null;
var estimatedPower = avgCurrent != null
? Math.Round((decimal)Math.Sqrt(3) * 380m * avgCurrent.Value / 1000m, 2)
: (decimal?)null;
var realtime = new
{
currentA,
currentB,
currentC,
avgCurrent,
maxCurrent,
minCurrent,
imbalanceRate,
estimatedPower,
unit = "A",
payloadTime
};
var realtimeJson = JsonSerializer.Serialize(realtime);
var currentState = unitwork.Find<DeviceCurrentState>(x => x.DeviceId == deviceId).FirstOrDefault();
if (IsDeadbandHit(currentState, status, currentA, currentB, currentC))
{
TouchCurrentState(unitwork, currentState, payloadTime, realtimeJson);
return new ProcessingResult
{
Handled = true,
Updated = true,
DeviceId = deviceId,
DeviceType = "power",
Status = status,
PayloadTime = payloadTime,
Message = "Power cabinet ignored by deadband",
ParsedData = realtimeJson
};
}
UpsertCurrentState(unitwork, currentState, deviceId, status, payloadTime, hasInvalid, realtimeJson);
UpsertTrendPoint(unitwork, deviceId, "currentA", payloadTime, currentA);
UpsertTrendPoint(unitwork, deviceId, "currentB", payloadTime, currentB);
UpsertTrendPoint(unitwork, deviceId, "currentC", payloadTime, currentC);
UpsertTrendPoint(unitwork, deviceId, "currentAvg", payloadTime, avgCurrent);
UpsertTrendPoint(unitwork, deviceId, "estimatedPower", payloadTime, estimatedPower);
UpsertTrendPoint(unitwork, deviceId, "imbalanceRate", payloadTime, imbalanceRate);
SyncInvalidCurrentAlarm(unitwork, deviceId, hasInvalid, payloadTime);
return new ProcessingResult
{
Handled = true,
Updated = true,
DeviceId = deviceId,
DeviceType = "power",
Status = status,
PayloadTime = payloadTime,
Message = "Power cabinet state updated",
ParsedData = realtimeJson
};
}
private static void UpsertCurrentState(IUnitWork unitwork, DeviceCurrentState currentState, string deviceId, string status, DateTime payloadTime, bool hasInvalid, string realtimeJson)
{
if (currentState == null)
{
unitwork.Add(new DeviceCurrentState
{
DeviceId = deviceId,
DeviceName = BuildPowerCabinetName(deviceId),
DeviceType = "power",
Status = status,
LastPayloadTime = payloadTime,
LastUpdateTime = DateTime.Now,
AlarmSummary = hasInvalid ? "三相电流存在无效值" : null,
RealtimeJson = realtimeJson
});
return;
}
currentState.DeviceName = string.IsNullOrWhiteSpace(currentState.DeviceName) ? BuildPowerCabinetName(deviceId) : currentState.DeviceName;
currentState.DeviceType = "power";
currentState.Status = status;
currentState.LastPayloadTime = payloadTime;
currentState.LastUpdateTime = DateTime.Now;
currentState.AlarmSummary = hasInvalid ? "三相电流存在无效值" : null;
currentState.RealtimeJson = realtimeJson;
unitwork.Update(currentState);
}
private static void TouchCurrentState(IUnitWork unitwork, DeviceCurrentState currentState, DateTime payloadTime, string realtimeJson)
{
if (currentState == null)
{
return;
}
currentState.LastPayloadTime = payloadTime;
currentState.LastUpdateTime = DateTime.Now;
currentState.RealtimeJson = realtimeJson;
unitwork.Update(currentState);
}
private static void UpsertTrendPoint(IUnitWork unitwork, string deviceId, string metricName, DateTime payloadTime, decimal? value)
{
if (value == null)
{
return;
}
var bucketTime = new DateTime(payloadTime.Year, payloadTime.Month, payloadTime.Day, payloadTime.Hour, payloadTime.Minute, 0);
var point = unitwork.Find<DeviceMetricTrendPoint>(x => x.DeviceId == deviceId && x.MetricName == metricName && x.BucketTime == bucketTime).FirstOrDefault();
if (point == null)
{
unitwork.Add(new DeviceMetricTrendPoint
{
DeviceId = deviceId,
MetricName = metricName,
BucketTime = bucketTime,
AvgValue = value.Value,
MaxValue = value.Value,
MinValue = value.Value,
SampleCount = 1
});
return;
}
var count = Math.Max(point.SampleCount, 1);
point.AvgValue = ((point.AvgValue * count) + value.Value) / (count + 1);
point.MaxValue = Math.Max(point.MaxValue, value.Value);
point.MinValue = Math.Min(point.MinValue, value.Value);
point.SampleCount = count + 1;
unitwork.Update(point);
}
private static void SyncInvalidCurrentAlarm(IUnitWork unitwork, string deviceId, bool hasInvalid, DateTime payloadTime)
{
var activeAlarm = unitwork.Find<DeviceAlarmRecord>(x => x.DeviceId == deviceId && x.AlarmCode == "POWER_CURRENT_INVALID" && x.IsActive).FirstOrDefault();
if (hasInvalid)
{
if (activeAlarm == null)
{
unitwork.Add(new DeviceAlarmRecord
{
DeviceId = deviceId,
AlarmCode = "POWER_CURRENT_INVALID",
AlarmMessage = "三相电流存在无效值",
StartTime = payloadTime,
LastSeenTime = payloadTime,
IsActive = true,
RepeatCount = 1
});
return;
}
activeAlarm.LastSeenTime = payloadTime;
activeAlarm.RepeatCount += 1;
unitwork.Update(activeAlarm);
return;
}
if (activeAlarm != null)
{
activeAlarm.IsActive = false;
activeAlarm.EndTime = payloadTime;
activeAlarm.LastSeenTime = payloadTime;
unitwork.Update(activeAlarm);
}
}
private static bool IsDeadbandHit(DeviceCurrentState currentState, string nextStatus, decimal? currentA, decimal? currentB, decimal? currentC)
{
if (currentState == null || currentState.Status != nextStatus || string.IsNullOrWhiteSpace(currentState.RealtimeJson))
{
return false;
}
using var document = JsonDocument.Parse(currentState.RealtimeJson);
var root = document.RootElement;
var oldA = ReadDecimal(root, "currentA");
var oldB = ReadDecimal(root, "currentB");
var oldC = ReadDecimal(root, "currentC");
return IsWithinDeadband(oldA, currentA)
&& IsWithinDeadband(oldB, currentB)
&& IsWithinDeadband(oldC, currentC);
}
private static bool IsWithinDeadband(decimal? oldValue, decimal? newValue)
{
if (oldValue == null && newValue == null)
{
return true;
}
if (oldValue == null || newValue == null)
{
return false;
}
return Math.Abs(oldValue.Value - newValue.Value) < CurrentDeadbandAmp;
}
private static string ReadString(JsonElement element, string propertyName)
{
return element.TryGetProperty(propertyName, out var property) && property.ValueKind != JsonValueKind.Null
? property.ToString()
: null;
}
private static decimal? ReadDecimal(JsonElement element, string propertyName)
{
if (!element.TryGetProperty(propertyName, out var property) || property.ValueKind == JsonValueKind.Null)
{
return null;
}
return property.TryGetDecimal(out var value) ? value : null;
}
private static decimal? ParseCurrent(string raw)
{
if (string.IsNullOrWhiteSpace(raw) || raw.Equals("invalid", StringComparison.OrdinalIgnoreCase))
{
return null;
}
var normalized = raw.Trim().Replace("A", string.Empty, StringComparison.OrdinalIgnoreCase);
return decimal.TryParse(normalized, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)
? value
: null;
}
private static decimal? Average(params decimal?[] values)
{
var validValues = values.Where(x => x != null).Select(x => x.Value).ToList();
return validValues.Any() ? Math.Round(validValues.Average(), 2) : null;
}
private static decimal? Max(params decimal?[] values)
{
var validValues = values.Where(x => x != null).Select(x => x.Value).ToList();
return validValues.Any() ? validValues.Max() : null;
}
private static decimal? Min(params decimal?[] values)
{
var validValues = values.Where(x => x != null).Select(x => x.Value).ToList();
return validValues.Any() ? validValues.Min() : null;
}
private static string BuildDeviceIdFromTopic(string topic)
{
return string.IsNullOrWhiteSpace(topic) ? "power:unknown" : $"power:{topic}";
}
private static string BuildPowerCabinetName(string deviceId)
{
if (deviceId?.EndsWith("001", StringComparison.OrdinalIgnoreCase) == true)
{
return "配电柜 #1";
}
if (deviceId?.EndsWith("002", StringComparison.OrdinalIgnoreCase) == true)
{
return "配电柜 #2";
}
return deviceId;
}
}
}
@@ -0,0 +1,25 @@
using System;
namespace HHWMS.Web.Services.DeviceData
{
public class ProcessingResult
{
public bool Handled { get; set; }
public bool Updated { get; set; }
public string DeviceId { get; set; }
public string DeviceType { get; set; }
public string Status { get; set; }
public DateTime? PayloadTime { get; set; }
public string Message { get; set; }
public string ParsedData { get; set; }
public static ProcessingResult NotHandled() => new ProcessingResult { Handled = false };
}
}
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.Threading;
namespace HHWMS.Web.Services
{
public class MqttRuntimeState
{
private int _enabled;
public bool Enabled => Volatile.Read(ref _enabled) == 1;
public DateTime? LastChangedAt { get; private set; }
public string LastChangedBy { get; private set; }
public void Update(bool enabled, string changedBy = null)
{
var oldEnabled = Enabled;
Volatile.Write(ref _enabled, enabled ? 1 : 0);
if (oldEnabled != enabled || string.IsNullOrEmpty(LastChangedBy))
{
LastChangedAt = DateTime.Now;
LastChangedBy = changedBy;
}
}
}
}
@@ -0,0 +1,30 @@
using System.Threading;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using Microsoft.Extensions.DependencyInjection;
namespace HHWMS.Web.Services
{
public class MqttRuntimeStateRefresher
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly MqttRuntimeState _runtimeState;
public MqttRuntimeStateRefresher(IServiceScopeFactory scopeFactory, MqttRuntimeState runtimeState)
{
_scopeFactory = scopeFactory;
_runtimeState = runtimeState;
}
public Task<bool> RefreshFromSubscriptionsAsync(string changedBy = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using var scope = _scopeFactory.CreateScope();
var unitwork = scope.ServiceProvider.GetRequiredService<IUnitWork>();
var enabled = unitwork.GetCount<MqttSubscription>(x => x.IsEnabled) > 0;
_runtimeState.Update(enabled, changedBy);
return Task.FromResult(enabled);
}
}
}
+46 -5
View File
@@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -18,23 +19,40 @@ namespace HHWMS.Web.Services
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly MqttMessageChannel _channel; private readonly MqttMessageChannel _channel;
private readonly MqttRuntimeState _runtimeState;
private readonly MqttRuntimeStateRefresher _runtimeStateRefresher;
private readonly HashSet<string> _subscribedTopics = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private IManagedMqttClient _mqttClient; private IManagedMqttClient _mqttClient;
public MqttService(IServiceProvider serviceProvider, IConfiguration configuration, MqttMessageChannel channel) public MqttService(
IServiceProvider serviceProvider,
IConfiguration configuration,
MqttMessageChannel channel,
MqttRuntimeState runtimeState,
MqttRuntimeStateRefresher runtimeStateRefresher)
{ {
_serviceProvider = serviceProvider; _serviceProvider = serviceProvider;
_configuration = configuration; _configuration = configuration;
_channel = channel; _channel = channel;
_runtimeState = runtimeState;
_runtimeStateRefresher = runtimeStateRefresher;
} }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
await _runtimeStateRefresher.RefreshFromSubscriptionsAsync("startup", stoppingToken);
var factory = new MqttFactory(); var factory = new MqttFactory();
_mqttClient = factory.CreateManagedMqttClient(); _mqttClient = factory.CreateManagedMqttClient();
// 1. Handle received messages // 1. Handle received messages
_mqttClient.ApplicationMessageReceivedAsync += async e => _mqttClient.ApplicationMessageReceivedAsync += async e =>
{ {
if (!_runtimeState.Enabled)
{
return;
}
var payload = e.ApplicationMessage.PayloadSegment.Array != null ? var payload = e.ApplicationMessage.PayloadSegment.Array != null ?
System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment) : string.Empty; System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment) : string.Empty;
@@ -72,15 +90,34 @@ namespace HHWMS.Web.Services
{ {
try try
{ {
await _runtimeStateRefresher.RefreshFromSubscriptionsAsync("sync", stoppingToken);
using (var scope = _serviceProvider.CreateScope()) using (var scope = _serviceProvider.CreateScope())
{ {
var unitwork = scope.ServiceProvider.GetRequiredService<IUnitWork>(); var unitwork = scope.ServiceProvider.GetRequiredService<IUnitWork>();
var subscriptions = unitwork.Find<MqttSubscription>(x => x.IsEnabled).ToList(); var subscriptions = _runtimeState.Enabled
? unitwork.Find<MqttSubscription>(x => x.IsEnabled).ToList()
: new List<MqttSubscription>();
if (subscriptions.Any()) var enabledTopics = subscriptions.Select(x => x.Topic).Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var topicsToUnsubscribe = _subscribedTopics.Except(enabledTopics, StringComparer.OrdinalIgnoreCase).ToList();
if (topicsToUnsubscribe.Any())
{
await _mqttClient.UnsubscribeAsync(topicsToUnsubscribe);
foreach (var topic in topicsToUnsubscribe)
{
_subscribedTopics.Remove(topic);
}
}
var subscriptionsToAdd = subscriptions
.Where(x => string.IsNullOrWhiteSpace(x.Topic) == false && _subscribedTopics.Contains(x.Topic) == false)
.ToList();
if (subscriptionsToAdd.Any())
{ {
var subOptionsBuilder = factory.CreateSubscribeOptionsBuilder(); var subOptionsBuilder = factory.CreateSubscribeOptionsBuilder();
foreach (var sub in subscriptions) foreach (var sub in subscriptionsToAdd)
{ {
var qosLevel = sub.Qos switch var qosLevel = sub.Qos switch
{ {
@@ -91,10 +128,14 @@ namespace HHWMS.Web.Services
subOptionsBuilder.WithTopicFilter(f => f.WithTopic(sub.Topic).WithQualityOfServiceLevel(qosLevel)); subOptionsBuilder.WithTopicFilter(f => f.WithTopic(sub.Topic).WithQualityOfServiceLevel(qosLevel));
} }
await _mqttClient.SubscribeAsync(subOptionsBuilder.Build().TopicFilters); await _mqttClient.SubscribeAsync(subOptionsBuilder.Build().TopicFilters);
foreach (var sub in subscriptionsToAdd)
{
_subscribedTopics.Add(sub.Topic);
}
} }
} }
} }
catch (Exception ex) catch (Exception)
{ {
// Basic logging or handling // Basic logging or handling
} }