Add dashboard device data push pipeline
This commit is contained in:
parent
8a0aa8f7cb
commit
0c4077f181
141
HHWMS.Web/Areas/Hub/DashboardHub.cs
Normal file
141
HHWMS.Web/Areas/Hub/DashboardHub.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -24,6 +24,8 @@ namespace HHWMS.Web
|
||||
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");
|
||||
|
||||
@ -35,12 +37,18 @@ namespace HHWMS.Web
|
||||
try
|
||||
{
|
||||
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);
|
||||
await _unitwork.SaveChangesAsync();
|
||||
await dashboardPushService.PushProcessingResultAsync(processingResult, _unitwork);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
|
||||
@ -29,6 +29,17 @@ builder.Services.AddRazorPages();
|
||||
builder.Services.AddDistributedMemoryCache();
|
||||
builder.Services.AddWtmSession(3600, 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.AddWtmHttpClient(builder.Configuration);
|
||||
builder.Services.AddWtmSwagger();
|
||||
@ -68,6 +79,8 @@ 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.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>();
|
||||
|
||||
|
||||
@ -81,6 +94,7 @@ app.UseExceptionHandler(config.CurrentValue.ErrorHandler);
|
||||
app.UseStaticFiles();
|
||||
app.UseWtmStaticFiles();
|
||||
app.UseRouting();
|
||||
app.UseCors("DashboardCors");
|
||||
app.UseWtmMultiLanguages();
|
||||
app.UseWtmCrossDomain();
|
||||
app.UseAuthentication();
|
||||
@ -104,6 +118,7 @@ app.UseEndpoints(endpoints =>
|
||||
name: "default",
|
||||
pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||
endpoints.MapHub<StockTickerHub>("/stocks");
|
||||
endpoints.MapHub<DashboardHub>("/dashboardHub").RequireCors("DashboardCors");
|
||||
});
|
||||
|
||||
app.UseWtmContext();
|
||||
|
||||
461
HHWMS.Web/Services/DeviceData/CncMessageProcessor.cs
Normal file
461
HHWMS.Web/Services/DeviceData/CncMessageProcessor.cs
Normal file
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
142
HHWMS.Web/Services/DeviceData/DashboardPushService.cs
Normal file
142
HHWMS.Web/Services/DeviceData/DashboardPushService.cs
Normal file
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -64,10 +64,15 @@ namespace HHWMS.Web.Services.DeviceData
|
||||
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 = false,
|
||||
Updated = true,
|
||||
DeviceId = deviceId,
|
||||
DeviceType = "power",
|
||||
Status = status,
|
||||
PayloadTime = payloadTime,
|
||||
Message = "Power cabinet ignored by deadband",
|
||||
ParsedData = realtimeJson
|
||||
};
|
||||
@ -86,6 +91,10 @@ namespace HHWMS.Web.Services.DeviceData
|
||||
{
|
||||
Handled = true,
|
||||
Updated = true,
|
||||
DeviceId = deviceId,
|
||||
DeviceType = "power",
|
||||
Status = status,
|
||||
PayloadTime = payloadTime,
|
||||
Message = "Power cabinet state updated",
|
||||
ParsedData = realtimeJson
|
||||
};
|
||||
@ -119,6 +128,19 @@ namespace HHWMS.Web.Services.DeviceData
|
||||
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)
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
using System;
|
||||
|
||||
namespace HHWMS.Web.Services.DeviceData
|
||||
{
|
||||
public class ProcessingResult
|
||||
@ -6,6 +8,14 @@ namespace HHWMS.Web.Services.DeviceData
|
||||
|
||||
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; }
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user