Add MQTT runtime control and device data pipeline

This commit is contained in:
zhougf committed 2026-05-31 10:55:22 +08:00
1 parent 96d8309793
commit 8a0aa8f7cb
31 files changed
+30842 -20

No files matched your search

@@ -0,0 +1,285 @@
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))
{
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<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,15 @@
namespace HHWMS.Web.Services.DeviceData
{
public class ProcessingResult
{
public bool Handled { get; set; }
public bool Updated { 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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -18,23 +19,40 @@ namespace HHWMS.Web.Services
private readonly IServiceProvider _serviceProvider;
private readonly IConfiguration _configuration;
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;
public MqttService(IServiceProvider serviceProvider, IConfiguration configuration, MqttMessageChannel channel)
public MqttService(
IServiceProvider serviceProvider,
IConfiguration configuration,
MqttMessageChannel channel,
MqttRuntimeState runtimeState,
MqttRuntimeStateRefresher runtimeStateRefresher)
{
_serviceProvider = serviceProvider;
_configuration = configuration;
_channel = channel;
_runtimeState = runtimeState;
_runtimeStateRefresher = runtimeStateRefresher;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await _runtimeStateRefresher.RefreshFromSubscriptionsAsync("startup", stoppingToken);
var factory = new MqttFactory();
_mqttClient = factory.CreateManagedMqttClient();
// 1. Handle received messages
_mqttClient.ApplicationMessageReceivedAsync += async e =>
{
if (!_runtimeState.Enabled)
{
return;
}
var payload = e.ApplicationMessage.PayloadSegment.Array != null ?
System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment) : string.Empty;
@@ -72,15 +90,34 @@ namespace HHWMS.Web.Services
{
try
{
await _runtimeStateRefresher.RefreshFromSubscriptionsAsync("sync", stoppingToken);
using (var scope = _serviceProvider.CreateScope())
{
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();
foreach (var sub in subscriptions)
foreach (var sub in subscriptionsToAdd)
{
var qosLevel = sub.Qos switch
{
@@ -91,10 +128,14 @@ namespace HHWMS.Web.Services
subOptionsBuilder.WithTopicFilter(f => f.WithTopic(sub.Topic).WithQualityOfServiceLevel(qosLevel));
}
await _mqttClient.SubscribeAsync(subOptionsBuilder.Build().TopicFilters);
foreach (var sub in subscriptionsToAdd)
{
_subscribedTopics.Add(sub.Topic);
}
}
}
}
catch (Exception ex)
catch (Exception)
{
// Basic logging or handling
}