/// <summary> /// Adds a singleton <see cref="IDistributionServicePublisher"/> service that uses the <see cref="MqttDistributionServicePublisher"/> implementation. /// </summary> /// <param name="services"> /// The <see cref="IServiceCollection"/> to add the <see cref="MqttDistributionServicePublisher"/> to. /// </param> /// <returns> /// Returns <paramref name="services"/> after the operation has completed. /// </returns> public static IServiceCollection AddMqttDistributionServicePublisher(this IServiceCollection services) { services.AddSingleton <IMqttEndpoint>(serviceProvider => { IOptions <MqttNetworkOptions>?options = serviceProvider.GetService <IOptions <MqttNetworkOptions> >(); MqttNetworkOptions mqttNetworkOptions = options?.Value ?? new MqttNetworkOptions(); IEventIdCreationSource eventIdCreationSource = serviceProvider.GetRequiredService <IEventIdCreationSource>(); if (mqttNetworkOptions.BrokerType == BrokerType.SelfHosted) { ILogger <SelfHostedMqttBroker> logger = serviceProvider.GetRequiredService <ILogger <SelfHostedMqttBroker> >(); return(new SelfHostedMqttBroker(logger, eventIdCreationSource, mqttNetworkOptions.Port, mqttNetworkOptions.Timeout)); } else if (mqttNetworkOptions.BrokerType == BrokerType.Remote) { ILogger <RemoteMqttBroker> logger = serviceProvider.GetRequiredService <ILogger <RemoteMqttBroker> >(); return(new RemoteMqttBroker(logger, eventIdCreationSource, mqttNetworkOptions.Host ?? MqttNetworkOptions.Default.Host !, mqttNetworkOptions.Port, mqttNetworkOptions.Timeout)); } else { throw new InvalidOperationException("Unknown broker type: " + mqttNetworkOptions.BrokerType); } }); return(services.AddSingleton <IDistributionServicePublisher, MqttDistributionServicePublisher>()); }
public void ShouldReturnEventIdWithInitialId(int initialId, string eventName) { IEventIdCreationSource eventIdCreationSource = CreateInstance(initialId); EventId eventId = eventIdCreationSource.GetNextId(eventName); Assert.Equal(initialId, eventId.Id); Assert.Equal(eventName, eventId.Name); }
public SelfHostedMqttBroker( ILogger <SelfHostedMqttBroker> logger, IEventIdCreationSource eventIdCreationSource, int port, int timeout) { _logger = logger; _eventIdCreationSource = eventIdCreationSource; EventId eventId = GetNextEventId(); #if DEBUG _logger.LogDebug(eventId, "Creating Mqtt Server."); #endif if (port < 0x0000) { throw new ArgumentOutOfRangeException(nameof(port), port, "Port number too small."); } else if (timeout > 0xffff) { throw new ArgumentOutOfRangeException(nameof(port), port, "Port number too large."); } if (timeout < 1) { throw new ArgumentOutOfRangeException(nameof(timeout), timeout, "Timeout timespan too small."); } else if (timeout > 99999) { throw new ArgumentOutOfRangeException(nameof(timeout), timeout, "Timeout timespan too large."); } _logger.LogInformation(eventId, $"MQTT Server Communication Timeout: {timeout} ms."); var serverOptionsBuilder = new MqttServerOptionsBuilder() .WithClientId(ClientId) .WithoutEncryptedEndpoint() .WithConnectionBacklog(100) .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(timeout)) .WithDefaultEndpointPort(port); _mqttServer = new MqttFactory().CreateMqttServer(); _mqttServer.UseClientConnectedHandler(HandleClientConnectedAsync); _mqttServer.UseClientDisconnectedHandler(HandleClientDisconnectedAsync); try { _logger.LogInformation(eventId, $"Starting Mqtt-Server (mqtt://0.0.0.0:{port})."); _mqttServer.StartAsync(serverOptionsBuilder.Build()).GetAwaiter().GetResult(); } catch (Exception exception) { string errorMessage = "Failed to start Mqtt-Server."; _logger.LogCritical(eventId, exception, errorMessage); throw new Exception(errorMessage);; } }
public void ShouldReturnEventIdsWithIncrementalIdValues(int initialId, string eventName) { IEventIdCreationSource eventIdCreationSource = CreateInstance(initialId); foreach (int id in Enumerable.Range(initialId, 100)) { EventId eventId = eventIdCreationSource.GetNextId(eventName); Assert.Equal(id, eventId.Id); Assert.Equal(eventName, eventId.Name); } }
public void ShouldCreateUniqueIds_WithSameEventName(string eventName) { IEventIdCreationSource eventIdCreationSource = CreateInstance(); HashSet <int> ids = new HashSet <int>(); foreach (int i in Enumerable.Range(0, 100)) { EventId eventId = eventIdCreationSource.GetNextId(eventName); Assert.True(ids.Add(eventId.Id)); Assert.Equal(eventName, eventId.Name); } }
public void ShouldCreateUniqueIds_WithDifferentEventName() { IEventIdCreationSource eventIdCreationSource = CreateInstance(); HashSet <int> ids = new HashSet <int>(); string eventNameTemplate = "EventName{0}"; foreach (int i in Enumerable.Range(0, 100)) { string eventName = string.Format(eventNameTemplate, i); EventId eventId = eventIdCreationSource.GetNextId(eventName); Assert.True(ids.Add(eventId.Id)); Assert.Equal(eventName, eventId.Name); } }
public RemoteMqttBroker( ILogger <RemoteMqttBroker> logger, IEventIdCreationSource eventIdCreationSource, string host, int port, int timeout) { _logger = logger; _eventIdCreationSource = eventIdCreationSource; EventId eventId = GetNextEventId(); #if DEBUG _logger.LogDebug(eventId, "Creating Mqtt Client."); #endif if (port < 0x0000) { throw new ArgumentOutOfRangeException(nameof(port), port, "Port number too small."); } else if (timeout > 0xffff) { throw new ArgumentOutOfRangeException(nameof(port), port, "Port number too large."); } if (timeout < 1) { throw new ArgumentOutOfRangeException(nameof(timeout), timeout, "Timeout timespan too small."); } else if (timeout > 99999) { throw new ArgumentOutOfRangeException(nameof(timeout), timeout, "Timeout timespan too large."); } _logger.LogInformation(eventId, $"MQTT Client Communication Timeout: {timeout} ms."); var clientOptionsBuilder = new MqttClientOptionsBuilder() .WithClientId(ClientId) .WithCommunicationTimeout(TimeSpan.FromMilliseconds(timeout)) .WithTcpServer(host, port); _mqttClient = new MqttFactory().CreateMqttClient(); CancellationTokenSource?cancellationTokenSource = null; #region Connecting to remote Mqtt Broker try { _logger.LogInformation(eventId, $"Connecting to remote Mqtt-Broker (mqtt://{host}:{port})."); cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)); //timeout var result = _mqttClient.ConnectAsync(clientOptionsBuilder.Build(), cancellationTokenSource.Token).GetAwaiter().GetResult(); if (result.ResultCode != MqttClientConnectResultCode.Success) { throw new Exception("Mqtt-Client ConnectResultCode Success expected. Actual: " + result.ResultCode); } } catch (OperationCanceledException) { string errorMessage = "Connect to remote Mqtt-Broker timed out."; _logger.LogCritical(eventId, errorMessage); throw new Exception(errorMessage); } catch (Exception exception) { string errorMessage = "Failed to connect to remote Mqtt-Broker."; _logger.LogCritical(eventId, exception, errorMessage); throw new Exception(errorMessage); } finally { cancellationTokenSource?.Dispose(); } #endregion #region Subscribing to relevant Events try { _logger.LogInformation(eventId, $"Subscribing to relevant events."); MqttQualityOfServiceLevel mqttQualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce; MqttClientSubscribeResultCode expectedSubscribeResultCode = MqttClientSubscribeResultCode.GrantedQoS1; MqttClientSubscribeOptionsBuilder subscribeOptionsBuilder = new MqttClientSubscribeOptionsBuilder() .WithTopicFilter(MqttTopics.ClientJoinRequested, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientJoinSucceeded, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientJoinFailed, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientGoodbye, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FragmentDistributionRequested, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FragmentDistributionObtained, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FragmentDistributionFailed, mqttQualityOfServiceLevel); cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)); //timeout MqttClientSubscribeResult result = _mqttClient.SubscribeAsync(subscribeOptionsBuilder.Build(), cancellationTokenSource.Token).GetAwaiter().GetResult(); foreach (MqttClientSubscribeResultItem item in result.Items) { if (item.ResultCode != expectedSubscribeResultCode) { throw new Exception($"Expected SubscribeResultCode {expectedSubscribeResultCode} for topic \"{item.TopicFilter.Topic}\". Actual: {item.ResultCode}"); } } } catch (OperationCanceledException) { string errorMessage = "Subscribing to all relevant Events to remote Mqtt-Broker timed out."; _logger.LogCritical(eventId, errorMessage); DisconnectOnError(errorMessage); throw new Exception(errorMessage); } catch (Exception exception) { string errorMessage = "Failed to subscribe to all relevant topics with expected SubscribeResultCode."; _logger.LogCritical(eventId, exception, errorMessage); DisconnectOnError(errorMessage); throw new Exception(errorMessage); } finally { cancellationTokenSource?.Dispose(); } #endregion void DisconnectOnError(string reasonString) { try { _logger.LogInformation("Disconnecting from remote Mqtt-Broker"); MqttClientDisconnectOptions disconnectOptions = new MqttClientDisconnectOptions() { ReasonCode = MqttClientDisconnectReason.NormalDisconnection, ReasonString = reasonString }; cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)); _mqttClient.DisconnectAsync(disconnectOptions, cancellationTokenSource.Token).GetAwaiter().GetResult(); } catch (OperationCanceledException) { _logger.LogError(eventId, "Disconnecting from remote Mqtt-Broker timed out."); } catch (Exception exception) { _logger.LogError(eventId, exception, "Disconnecting from remote Mqtt-Broker failed."); } finally { cancellationTokenSource?.Dispose(); } } }
public RemoteMqttBroker( ILogger <RemoteMqttBroker> logger, IEventIdCreationSource eventIdCreationSource, IOptions <MqttNetworkOptions>?options = null) { _logger = logger; _eventIdCreationSource = eventIdCreationSource; EventId eventId = GetNextEventId(); _logger.LogInformation(eventId, $"Creating Mqtt Client (Id: {ClientId})."); MqttNetworkOptions mqttNetworkOptions = options?.Value ?? MqttNetworkOptions.Default; mqttNetworkOptions.Host ??= MqttNetworkOptions.Default.Host !; if (mqttNetworkOptions.Port < 0x0000) { throw new ArgumentOutOfRangeException(nameof(mqttNetworkOptions.Port), mqttNetworkOptions.Port, "Port number too small."); } else if (mqttNetworkOptions.Port > 0xffff) { throw new ArgumentOutOfRangeException(nameof(mqttNetworkOptions.Port), mqttNetworkOptions.Port, "Port number too large."); } if (mqttNetworkOptions.Timeout < 1) { throw new ArgumentOutOfRangeException(nameof(mqttNetworkOptions.Timeout), mqttNetworkOptions.Timeout, "Timeout timespan too small."); } else if (mqttNetworkOptions.Timeout > 99999) { throw new ArgumentOutOfRangeException(nameof(mqttNetworkOptions.Timeout), mqttNetworkOptions.Timeout, "Timeout timespan too large."); } _logger.LogInformation(eventId, $"MQTT Client Communication Timeout: {mqttNetworkOptions.Timeout} ms."); var clientOptionsBuilder = new MqttClientOptionsBuilder() .WithClientId(ClientId) .WithCommunicationTimeout(TimeSpan.FromSeconds(60)) .WithTcpServer(mqttNetworkOptions.Host, mqttNetworkOptions.Port); _mqttClient = new MqttFactory().CreateMqttClient(); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(eventArgs => { _logger.LogDebug("Client Connected. Reason: " + (eventArgs.AuthenticateResult?.ReasonString ?? "null")); }); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(eventArgs => { _logger.LogDebug(eventArgs.Exception, "Client Disconnected. Reason: " + (eventArgs.AuthenticateResult?.ReasonString ?? "null")); }); CancellationTokenSource?cancellationTokenSource = null; #region Connecting to remote Mqtt Broker try { _logger.LogInformation(eventId, $"Connecting to remote Mqtt-Broker (mqtt://{mqttNetworkOptions.Host}:{mqttNetworkOptions.Port})."); cancellationTokenSource = new CancellationTokenSource(TimeoutTimeSpan); var result = _mqttClient.ConnectAsync(clientOptionsBuilder.Build(), cancellationTokenSource.Token).GetAwaiter().GetResult(); if (result.ResultCode != MqttClientConnectResultCode.Success) { throw new Exception("Mqtt-Client ConnectResultCode Success expected. Actual: " + result.ResultCode); } } catch (OperationCanceledException) { string errorMessage = "Connect to remote Mqtt-Broker timed out."; _logger.LogCritical(eventId, errorMessage); throw new Exception(errorMessage); } catch (Exception exception) { string errorMessage = "Failed to connect to remote Mqtt-Broker."; _logger.LogCritical(eventId, exception, errorMessage); throw new Exception(errorMessage); } finally { cancellationTokenSource?.Dispose(); } #endregion #region Subscribing to relevant Events try { _logger.LogInformation(eventId, $"Subscribing to relevant events."); MqttQualityOfServiceLevel mqttQualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce; MqttClientSubscribeResultCode expectedSubscribeResultCode = MqttClientSubscribeResultCode.GrantedQoS1; MqttClientSubscribeOptionsBuilder subscribeOptionsBuilder = new MqttClientSubscribeOptionsBuilder() .WithTopicFilter(MqttTopics.TrackerHello, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.TrackerGoodbye, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientJoinAccepted, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientJoinDenied, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientRegistered, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.ClientGoodbye, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FileInfoPublished, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FragmentDistributionStarted, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FragmentDistributionDelivered, mqttQualityOfServiceLevel) .WithTopicFilter(MqttTopics.FragmentDistributionEnded, mqttQualityOfServiceLevel); cancellationTokenSource = new CancellationTokenSource(TimeoutTimeSpan); //timeout MqttClientSubscribeResult result = _mqttClient.SubscribeAsync(subscribeOptionsBuilder.Build(), cancellationTokenSource.Token).GetAwaiter().GetResult(); foreach (MqttClientSubscribeResultItem item in result.Items) { if (item.ResultCode != expectedSubscribeResultCode) { throw new Exception($"Expected SubscribeResultCode {expectedSubscribeResultCode} for topic \"{item.TopicFilter.Topic}\". Actual: {item.ResultCode}"); } } } catch (Exception exception) { string errorMessage; if (exception is OperationCanceledException) { errorMessage = "Subscribing to all relevant Events to remote Mqtt-Broker timed out."; _logger.LogCritical(eventId, errorMessage); } else { errorMessage = "Failed to subscribe to all relevant topics with expected SubscribeResultCode."; _logger.LogCritical(eventId, exception, errorMessage); } try { _logger.LogInformation("Disconnecting from remote Mqtt-Broker"); MqttClientDisconnectOptions disconnectOptions = new MqttClientDisconnectOptions() { ReasonCode = MqttClientDisconnectReason.NormalDisconnection, ReasonString = errorMessage }; cancellationTokenSource = new CancellationTokenSource(TimeoutTimeSpan); _mqttClient.DisconnectAsync(disconnectOptions, cancellationTokenSource.Token).GetAwaiter().GetResult(); } catch (OperationCanceledException) { _logger.LogError(eventId, "Disconnecting from remote Mqtt-Broker timed out."); } catch (Exception disconnectException) { _logger.LogError(eventId, disconnectException, "Disconnecting from remote Mqtt-Broker failed."); } finally { cancellationTokenSource?.Dispose(); } throw new Exception(errorMessage); } finally { cancellationTokenSource?.Dispose(); } #endregion }