/// <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()); }
public async Task <MqttServer> StartServer(MqttServerOptionsBuilder optionsBuilder) { optionsBuilder.WithDefaultEndpoint(); optionsBuilder.WithDefaultEndpointPort(ServerPort); optionsBuilder.WithMaxPendingMessagesPerClient(int.MaxValue); var options = optionsBuilder.Build(); var server = CreateServer(options); await server.StartAsync(); // The OS has chosen the port to we have to properly expose it to the tests. ServerPort = options.DefaultEndpointOptions.Port; return(server); }
public static void UseMqttBrokerOption(this MqttServerOptionsBuilder builder, IMqttServerStorage storage) { var options = MQTTBrokerOption; if (options.BrokerCertificate != null) { builder.WithEncryptionCertificate(options.BrokerCertificate.Export(X509ContentType.Pfx)) .WithEncryptedEndpoint() .WithEncryptedEndpointPort(options.SSLPort); } builder.WithDefaultEndpoint() .WithDefaultEndpointPort(options.Port) .WithStorage(storage) .Build(); }
public MQTTServer() { var serverOptBuilder = new MqttServerOptionsBuilder(); serverOptBuilder.WithDefaultEndpoint() .WithDefaultEndpoint() .WithDefaultEndpointPort(108) .WithSubscriptionInterceptor(c => { c.AcceptSubscription = true; }) .WithApplicationMessageInterceptor(c => { c.AcceptPublish = true; }); var options = serverOptBuilder.Build(); mqttServer = new MQTTnet.MqttFactory().CreateMqttServer(); var recieveHander = new MsgRecieveHandler(); var connectedHandler = new MqttServerClientConnectedHandler(); var subsciptionHandler = new MqttServerClientSubscribedTopicHandler(); mqttServer.ApplicationMessageReceivedHandler = recieveHander; mqttServer.ClientConnectedHandler = connectedHandler; mqttServer.ClientSubscribedTopicHandler = subsciptionHandler; mqttServer.StartAsync(options).Wait(); var tc = new TimerCallback(timerCallback); var timer = new System.Threading.Timer(tc); timer.Change(3000, 3000); }
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()); }
static Igloo15MqttServer InitializeServer(Options config, ILoggerFactory factory) { Igloo15MqttServer server = null; try { MqttServerOptionsBuilder serverBuilder = new MqttServerOptionsBuilder(); if (config.Encrypted && File.Exists(config.CertificateLocation)) { if (config.IPAddress == "Any") { serverBuilder.WithEncryptedEndpoint(); } else if (IPAddress.TryParse(config.IPAddress, out IPAddress address)) { serverBuilder.WithEncryptedEndpointBoundIPAddress(address); } else { _logger.LogWarning($"Failed to parse provided IP Address : {config.IPAddress} using default"); serverBuilder.WithEncryptedEndpoint(); } serverBuilder.WithEncryptedEndpointPort(config.Port); var certificate = new X509Certificate2(config.CertificateLocation, config.CertificatePassword); var certBytes = certificate.Export(X509ContentType.Cert); serverBuilder.WithEncryptionCertificate(certBytes); } else { if (config.IPAddress == "Any") { serverBuilder.WithDefaultEndpoint(); } else if (IPAddress.TryParse(config.IPAddress, out IPAddress address)) { serverBuilder.WithDefaultEndpointBoundIPAddress(address); } else { _logger.LogWarning("Failed to parse provided IP Address : {IPAddress} using default", config.IPAddress); serverBuilder.WithDefaultEndpoint(); } serverBuilder.WithDefaultEndpointPort(config.Port); } if (config.Persistent) { serverBuilder.WithPersistentSessions(); } if (!String.IsNullOrEmpty(config.MessageStorageLocation)) { serverBuilder.WithStorage(new RetainedMessageHandler(config.MessageStorageLocation)); } if (config.ShowSubscriptions) { serverBuilder.WithSubscriptionInterceptor(_interceptors.SubscriptionInterceptor); } if (config.ShowMessages) { serverBuilder.WithApplicationMessageInterceptor(_interceptors.MessageInterceptor); } if (config.ShowClientConnections) { serverBuilder.WithConnectionValidator(_interceptors.ConnectionInterceptor); } serverBuilder .WithConnectionBacklog(config.ConnectionBacklog) .WithMaxPendingMessagesPerClient(config.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(config.CommunicationTimeout)); server = new Igloo15MqttServer(serverBuilder.Build(), factory); } catch (Exception e) { _logger.LogError(e, "Exception occured during Initialization of Server"); return(null); } return(server); }
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()); }