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(x => x.DeviceId == deviceId).FirstOrDefault(); if (IsDeadbandHit(currentState, status, currentA, currentB, currentC)) { return new ProcessingResult { Handled = true, Updated = false, 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, 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 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(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(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; } } }