first commit
This commit is contained in:
commit
b31e9a7261
38 files changed
+3822
No files matched your search
@@ -0,0 +1,360 @@
|
||||
using System.Buffers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// One outbound MQTT client for the appliance. It intentionally does not host an MQTT broker.
|
||||
/// Mappings are exact topics only; wildcard subscriptions are deliberately not created.
|
||||
/// </summary>
|
||||
public sealed class MqttClientService : BackgroundService
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly MqttClientFactory _factory = new();
|
||||
private readonly SemaphoreSlim _publishGate = new(1, 1);
|
||||
private readonly object _clientLock = new();
|
||||
private IMqttClient? _client;
|
||||
private MqttClientStatus _status = new(false, false, null, null, null, null, null);
|
||||
private int _reconfigureRequested = 1;
|
||||
private CancellationToken _stoppingToken;
|
||||
|
||||
public MqttClientService(GatewayStore store)
|
||||
{
|
||||
_store = store;
|
||||
_store.PointValueUpdated += OnPointValueUpdated;
|
||||
}
|
||||
|
||||
public MqttClientStatus GetStatus() => Volatile.Read(ref _status);
|
||||
|
||||
/// <summary>Applies changed broker or subscription configuration without a process restart.</summary>
|
||||
public void RequestReconfigure() => Interlocked.Exchange(ref _reconfigureRequested, 1);
|
||||
|
||||
public async Task<int> PublishPointValueAsync(PointValue pointValue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var client = GetConnectedClient();
|
||||
if (client is null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var mappings = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)
|
||||
.ToArray();
|
||||
var published = 0;
|
||||
await _publishGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
foreach (var mapping in mappings)
|
||||
{
|
||||
var payload = CreateOutboundPayload(mapping, pointValue);
|
||||
var message = _factory.CreateApplicationMessageBuilder()
|
||||
.WithTopic(GatewayStore.GetMqttTopic(mapping))
|
||||
.WithPayload(payload)
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService))
|
||||
.WithRetainFlag(mapping.Retain)
|
||||
.Build();
|
||||
await client.PublishAsync(message, cancellationToken);
|
||||
published++;
|
||||
UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null });
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
UpdateStatus(status => status with { LastError = $"Publish: {exception.Message}" });
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_publishGate.Release();
|
||||
}
|
||||
|
||||
return published;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_stoppingToken = stoppingToken;
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (configuration, password) = _store.GetMqttConnectionConfiguration();
|
||||
if (!configuration.Enabled)
|
||||
{
|
||||
await DisconnectCurrentAsync(stoppingToken);
|
||||
SetStatus(new MqttClientStatus(false, false, null, null, null, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
|
||||
}
|
||||
else if (Interlocked.Exchange(ref _reconfigureRequested, 0) == 1 || GetConnectedClient() is null)
|
||||
{
|
||||
await DisconnectCurrentAsync(stoppingToken);
|
||||
await ConnectAsync(configuration, password, stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false, LastError = exception.Message });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await DisconnectCurrentAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_store.PointValueUpdated -= OnPointValueUpdated;
|
||||
_publishGate.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken)
|
||||
{
|
||||
var builder = _factory.CreateClientOptionsBuilder()
|
||||
.WithClientId(configuration.ClientId)
|
||||
.WithTcpServer(configuration.Host, configuration.Port)
|
||||
// MQTT 3.1.1 gives the widest compatibility with existing field brokers.
|
||||
.WithProtocolVersion(MqttProtocolVersion.V311);
|
||||
if (!string.IsNullOrWhiteSpace(configuration.Username))
|
||||
{
|
||||
builder.WithCredentials(configuration.Username, password ?? string.Empty);
|
||||
}
|
||||
|
||||
if (configuration.UseTls)
|
||||
{
|
||||
builder.WithTlsOptions(tls =>
|
||||
{
|
||||
tls.UseTls();
|
||||
if (configuration.IgnoreCertificateErrors)
|
||||
{
|
||||
// This is opt-in and deliberately visible in the UI; normal operation validates certificates.
|
||||
tls.WithCertificateValidationHandler(_ => true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var client = _factory.CreateMqttClient();
|
||||
client.ApplicationMessageReceivedAsync += HandleReceivedMessageAsync;
|
||||
client.DisconnectedAsync += HandleDisconnectedAsync;
|
||||
await client.ConnectAsync(builder.Build(), cancellationToken);
|
||||
lock (_clientLock)
|
||||
{
|
||||
_client = client;
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
SetStatus(new MqttClientStatus(true, true, $"{configuration.Host}:{configuration.Port}", null, now, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
|
||||
await SubscribeMappedTopicsAsync(client, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task SubscribeMappedTopicsAsync(IMqttClient client, CancellationToken cancellationToken)
|
||||
{
|
||||
var subscriptions = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional)
|
||||
.GroupBy(GatewayStore.GetMqttTopic, StringComparer.Ordinal)
|
||||
.Select(group => new
|
||||
{
|
||||
Topic = group.Key,
|
||||
QualityOfService = group.Max(mapping => mapping.QualityOfService)
|
||||
})
|
||||
.ToArray();
|
||||
if (subscriptions.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var builder = _factory.CreateSubscribeOptionsBuilder();
|
||||
foreach (var subscription in subscriptions)
|
||||
{
|
||||
builder.WithTopicFilter(filter => filter
|
||||
.WithTopic(subscription.Topic)
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService)));
|
||||
}
|
||||
|
||||
await client.SubscribeAsync(builder.Build(), cancellationToken);
|
||||
}
|
||||
|
||||
private async Task HandleReceivedMessageAsync(MqttApplicationMessageReceivedEventArgs arguments)
|
||||
{
|
||||
try
|
||||
{
|
||||
var topic = arguments.ApplicationMessage.Topic;
|
||||
var mappings = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional)
|
||||
.Where(mapping => string.Equals(GatewayStore.GetMqttTopic(mapping), topic, StringComparison.Ordinal))
|
||||
.ToArray();
|
||||
if (mappings.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = arguments.ApplicationMessage.Payload;
|
||||
var payloadBytes = new byte[checked((int)payload.Length)];
|
||||
payload.CopyTo(payloadBytes);
|
||||
var rawPayload = Encoding.UTF8.GetString(payloadBytes);
|
||||
using var document = ParsePayload(rawPayload);
|
||||
foreach (var mapping in mappings)
|
||||
{
|
||||
var value = ExtractInboundValue(document.RootElement, mapping);
|
||||
_store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
UpdateStatus(status => status with { LastReceivedAtUtc = DateTimeOffset.UtcNow, LastError = null });
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
UpdateStatus(status => status with { LastError = $"Empfang: {exception.Message}" });
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs arguments)
|
||||
{
|
||||
lock (_clientLock)
|
||||
{
|
||||
_client = null;
|
||||
}
|
||||
|
||||
if (arguments.Exception is not null)
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false, LastError = arguments.Exception.Message });
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false });
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task DisconnectCurrentAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
IMqttClient? client;
|
||||
lock (_clientLock)
|
||||
{
|
||||
client = _client;
|
||||
_client = null;
|
||||
}
|
||||
|
||||
if (client is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.IsConnected)
|
||||
{
|
||||
await client.DisconnectAsync(_factory.CreateClientDisconnectOptionsBuilder().Build(), cancellationToken);
|
||||
}
|
||||
|
||||
if (client is IDisposable disposable)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private IMqttClient? GetConnectedClient()
|
||||
{
|
||||
lock (_clientLock)
|
||||
{
|
||||
return _client is { IsConnected: true } client ? client : null;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPointValueUpdated(object? sender, PointValue pointValue)
|
||||
{
|
||||
// MQTT-originated values must not be reflected to the same broker again.
|
||||
if (pointValue.SourceProtocol == PointProtocol.Mqtt || !GetStatus().Connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = PublishPointValueSafelyAsync(pointValue);
|
||||
}
|
||||
|
||||
private async Task PublishPointValueSafelyAsync(PointValue pointValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PublishPointValueAsync(pointValue, _stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (_stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The status field has the error; a later adapter update or reconnect can retry.
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument ParsePayload(string rawPayload)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(rawPayload);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return JsonDocument.Parse(JsonSerializer.Serialize(rawPayload));
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping)
|
||||
{
|
||||
if (mapping.Format == MqttMappingFormat.Json && !string.IsNullOrWhiteSpace(mapping.JsonProperty))
|
||||
{
|
||||
if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty(mapping.JsonProperty, out var property))
|
||||
{
|
||||
throw new DomainValidationException($"Das JSON-Topic enthält keine Eigenschaft '{mapping.JsonProperty}'.");
|
||||
}
|
||||
|
||||
return property.Clone();
|
||||
}
|
||||
|
||||
return payload.Clone();
|
||||
}
|
||||
|
||||
private static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue)
|
||||
{
|
||||
if (mapping.Format == MqttMappingFormat.SeMonitoring)
|
||||
{
|
||||
return pointValue.Value.GetRawText();
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(mapping.JsonProperty))
|
||||
{
|
||||
return pointValue.Value.GetRawText();
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(pointValue.Value.GetRawText());
|
||||
return JsonSerializer.Serialize(new Dictionary<string, object?>
|
||||
{
|
||||
["timestamp"] = pointValue.UpdatedAtUtc.ToString("O"),
|
||||
[mapping.JsonProperty] = document.RootElement.Clone()
|
||||
});
|
||||
}
|
||||
|
||||
private static MqttQualityOfServiceLevel ToMqttQualityOfService(MqttQualityOfService qualityOfService) => qualityOfService switch
|
||||
{
|
||||
MqttQualityOfService.AtMostOnce => MqttQualityOfServiceLevel.AtMostOnce,
|
||||
MqttQualityOfService.AtLeastOnce => MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
MqttQualityOfService.ExactlyOnce => MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(qualityOfService))
|
||||
};
|
||||
|
||||
private void SetStatus(MqttClientStatus status) => Volatile.Write(ref _status, status);
|
||||
|
||||
private void UpdateStatus(Func<MqttClientStatus, MqttClientStatus> update) => SetStatus(update(GetStatus()));
|
||||
}
|
||||
Reference in new issue
Block a user