/// <summary> /// Starts the service. /// </summary> public void Start() { try { var certificate = new X509Certificate2( Path.Combine(this.currentPath, "certificate.pfx"), "test", X509KeyStorageFlags.Exportable); Config config; #if DEBUG using (var r = new StreamReader($"{this.currentPath}\\appsettings.Development.json")) { var json = r.ReadToEnd(); config = JsonConvert.DeserializeObject <Config>(json); } #else using (var r = new StreamReader($"{this.currentPath}\\appsettings.json")) { var json = r.ReadToEnd(); config = JsonConvert.DeserializeObject <Config>(json); } #endif var optionsBuilder = new MqttServerOptionsBuilder(); optionsBuilder = config.UnencryptedPort == null ? optionsBuilder.WithoutDefaultEndpoint() : optionsBuilder.WithDefaultEndpoint() .WithDefaultEndpointPort(config.UnencryptedPort.Value); optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(config.Port) .WithEncryptionCertificate(certificate.Export(X509ContentType.Pfx)) .WithEncryptionSslProtocol(SslProtocols.Tls12) .WithConnectionValidator(this.ValidateConnection) .WithSubscriptionInterceptor(this.ValidateSubscription) .WithApplicationMessageInterceptor(this.ValidatePublish); this.mqttServer = new MqttFactory().CreateMqttServer(); this.mqttServer.StartAsync(optionsBuilder.Build()); this.mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(this.HandleUnsubscription); this.mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(this.HandleDisconnect); this.clusterClient = this.ConnectOrleansClient(config).Result; var repositoryGrain = this.clusterClient.GetGrain <IMqttRepositoryGrain>(0); repositoryGrain.ConnectBroker(config.BrokerConnectionSettings, this.brokerId); this.logger.Information("Started MQTT server."); } catch (Exception ex) { this.logger.Fatal("An error occured: {ex}.", ex); Environment.Exit(0); } }
/// <inheritdoc cref="BackgroundService"/> /// <summary> /// Triggered when the application host is ready to start the service. /// </summary> /// <param name="cancellationToken">Indicates that the start process has been aborted.</param> /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns> /// <seealso cref="BackgroundService"/> public override async Task StartAsync(CancellationToken cancellationToken) { this.logger.Information("Starting MQTT server..."); try { var currentLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var certificate = new X509Certificate2( // ReSharper disable once AssignNullToNotNullAttribute Path.Combine(currentLocation, "certificate.pfx"), "test", X509KeyStorageFlags.Exportable); var optionsBuilder = new MqttServerOptionsBuilder(); optionsBuilder = this.clusterConfiguration.UnencryptedPort == null ? optionsBuilder.WithoutDefaultEndpoint() : optionsBuilder.WithDefaultEndpoint() .WithDefaultEndpointPort(this.clusterConfiguration.UnencryptedPort.Value); optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(this.clusterConfiguration.Port) .WithEncryptionCertificate(certificate.Export(X509ContentType.Pfx)) .WithEncryptionSslProtocol(SslProtocols.Tls12) .WithConnectionValidator(this) .WithSubscriptionInterceptor(this) .WithApplicationMessageInterceptor(this) .WithUnsubscriptionInterceptor(this); this.mqttServer = new MqttFactory().CreateMqttServer(); // Todo: Move this to handler once available this.mqttServer.ClientDisconnectedHandler = this; await this.mqttServer.StartAsync(optionsBuilder.Build()); await this.ConnectOrleansClient(); var repositoryGrain = clusterClient.GetGrain <IMqttRepositoryGrain>(0); await repositoryGrain.ConnectBroker(this.clusterConfiguration.BrokerConnectionSettings, this.brokerId); this.logger.Information("Started MQTT server."); } catch (Exception ex) { Environment.ExitCode = 1; this.logger.Fatal("An error occurred: {@ex}.", ex); } await base.StartAsync(cancellationToken); }
private IMqttServerOptions CreateMqttServerOptions() { var options = new MqttServerOptionsBuilder() .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)) .WithConnectionValidator(_mqttConnectionValidator) .WithStorage(_mqttServerStorage); // Configure unencrypted connections if (_settings.TcpEndPoint.Enabled) { options.WithDefaultEndpoint(); if (_settings.TcpEndPoint.TryReadIPv4(out var address4)) { options.WithDefaultEndpointBoundIPAddress(address4); } if (_settings.TcpEndPoint.TryReadIPv6(out var address6)) { options.WithDefaultEndpointBoundIPV6Address(address6); } if (_settings.TcpEndPoint.Port > 0) { options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port); } } else { options.WithoutDefaultEndpoint(); } if (_settings.ConnectionBacklog > 0) { options.WithConnectionBacklog(_settings.ConnectionBacklog); } if (_settings.EnablePersistentSessions) { options.WithPersistentSessions(); } if (_settings.UseOriginalReseiverClientId) { options.WithApplicationMessageInterceptor(_messageInterceptor); } return(options.Build()); }
IMqttServerOptions CreateMqttServerOptions() { var options = new MqttServerOptionsBuilder() .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)) .WithConnectionValidator(_mqttConnectionValidator) .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor) .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor) .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor) .WithStorage(_mqttServerStorage); // Configure unencrypted connections if (_settings.TcpEndPoint.Enabled) { options.WithDefaultEndpoint(); if (_settings.TcpEndPoint.TryReadIPv4(out var address4)) { options.WithDefaultEndpointBoundIPAddress(address4); } if (_settings.TcpEndPoint.TryReadIPv6(out var address6)) { options.WithDefaultEndpointBoundIPV6Address(address6); } if (_settings.TcpEndPoint.Port > 0) { options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port); } } else { options.WithoutDefaultEndpoint(); } // Configure encrypted connections if (_settings.EncryptedTcpEndPoint.Enabled) { #if NETCOREAPP3_1 || NET5_0 options .WithEncryptedEndpoint() .WithEncryptionSslProtocol(SslProtocols.Tls13); #else options .WithEncryptedEndpoint() .WithEncryptionSslProtocol(SslProtocols.Tls12); #endif if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path)) { IMqttServerCertificateCredentials certificateCredentials = null; if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password)) { certificateCredentials = new MqttServerCertificateCredentials { Password = _settings.EncryptedTcpEndPoint.Certificate.Password }; } options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials); } if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4)) { options.WithEncryptedEndpointBoundIPAddress(address4); } if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6)) { options.WithEncryptedEndpointBoundIPV6Address(address6); } if (_settings.EncryptedTcpEndPoint.Port > 0) { options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port); } } else { options.WithoutEncryptedEndpoint(); } if (_settings.ConnectionBacklog > 0) { options.WithConnectionBacklog(_settings.ConnectionBacklog); } if (_settings.EnablePersistentSessions) { options.WithPersistentSessions(); } return(options.Build()); }
IMqttServerOptions CreateMqttServerOptions() { // Create client id if none provided var cid = string.IsNullOrWhiteSpace(_settings.BrokerClientId) ? Guid.NewGuid().ToString("N").ToUpper() : _settings.BrokerClientId; var options = new MqttServerOptionsBuilder() .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)) .WithConnectionValidator(_mqttConnectionValidator) .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor) .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor) .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor) .WithClientId(cid); // Configure unencrypted connections if (_settings.TcpEndPoint.Enabled) { options.WithDefaultEndpoint(); if (_settings.TcpEndPoint.TryReadIPv4(out var address4)) { options.WithDefaultEndpointBoundIPAddress(address4); } if (_settings.TcpEndPoint.TryReadIPv6(out var address6)) { options.WithDefaultEndpointBoundIPV6Address(address6); } if (_settings.TcpEndPoint.Port > 0) { options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port); _logger.LogInformation($"MQTT Broker '{_settings.BrokerName}' listening on TCP port {_settings.TcpEndPoint.Port}, ClientID: {cid}"); } } else { options.WithoutDefaultEndpoint(); } // Configure encrypted connections if (_settings.EncryptedTcpEndPoint.Enabled) { options .WithEncryptedEndpoint() .WithEncryptionSslProtocol(SslProtocols.Tls13); if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path)) { IMqttServerCertificateCredentials certificateCredentials = null; if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password)) { certificateCredentials = new MqttServerCertificateCredentials { Password = _settings.EncryptedTcpEndPoint.Certificate.Password }; } options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials); } if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4)) { options.WithEncryptedEndpointBoundIPAddress(address4); } if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6)) { options.WithEncryptedEndpointBoundIPV6Address(address6); } if (_settings.EncryptedTcpEndPoint.Port > 0) { options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port); _logger.LogInformation($"MQTT Broker {_settings.BrokerName} listening on SSL port {_settings.TcpEndPoint.Port}"); } } else { options.WithoutEncryptedEndpoint(); } if (_settings.ConnectionBacklog > 0) { options.WithConnectionBacklog(_settings.ConnectionBacklog); } if (_settings.EnablePersistentSessions) { options.WithPersistentSessions(); } return(options.Build()); }